1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the LLVM module linker. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Linker/Linker.h" 15 #include "llvm-c/Linker.h" 16 #include "llvm/ADT/Hashing.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallString.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DebugInfo.h" 23 #include "llvm/IR/DiagnosticInfo.h" 24 #include "llvm/IR/DiagnosticPrinter.h" 25 #include "llvm/IR/LLVMContext.h" 26 #include "llvm/IR/Module.h" 27 #include "llvm/IR/TypeFinder.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Transforms/Utils/Cloning.h" 32 #include <cctype> 33 #include <tuple> 34 using namespace llvm; 35 36 37 //===----------------------------------------------------------------------===// 38 // TypeMap implementation. 39 //===----------------------------------------------------------------------===// 40 41 namespace { 42 class TypeMapTy : public ValueMapTypeRemapper { 43 /// This is a mapping from a source type to a destination type to use. 44 DenseMap<Type*, Type*> MappedTypes; 45 46 /// When checking to see if two subgraphs are isomorphic, we speculatively 47 /// add types to MappedTypes, but keep track of them here in case we need to 48 /// roll back. 49 SmallVector<Type*, 16> SpeculativeTypes; 50 51 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes; 52 53 /// This is a list of non-opaque structs in the source module that are mapped 54 /// to an opaque struct in the destination module. 55 SmallVector<StructType*, 16> SrcDefinitionsToResolve; 56 57 /// This is the set of opaque types in the destination modules who are 58 /// getting a body from the source module. 59 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 60 61 public: 62 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet) 63 : DstStructTypesSet(DstStructTypesSet) {} 64 65 Linker::IdentifiedStructTypeSet &DstStructTypesSet; 66 /// Indicate that the specified type in the destination module is conceptually 67 /// equivalent to the specified type in the source module. 68 void addTypeMapping(Type *DstTy, Type *SrcTy); 69 70 /// Produce a body for an opaque type in the dest module from a type 71 /// definition in the source module. 72 void linkDefinedTypeBodies(); 73 74 /// Return the mapped type to use for the specified input type from the 75 /// source module. 76 Type *get(Type *SrcTy); 77 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited); 78 79 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes); 80 81 FunctionType *get(FunctionType *T) { 82 return cast<FunctionType>(get((Type *)T)); 83 } 84 85 /// Dump out the type map for debugging purposes. 86 void dump() const { 87 for (auto &Pair : MappedTypes) { 88 dbgs() << "TypeMap: "; 89 Pair.first->print(dbgs()); 90 dbgs() << " => "; 91 Pair.second->print(dbgs()); 92 dbgs() << '\n'; 93 } 94 } 95 96 private: 97 Type *remapType(Type *SrcTy) override { return get(SrcTy); } 98 99 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 100 }; 101 } 102 103 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 104 assert(SpeculativeTypes.empty()); 105 assert(SpeculativeDstOpaqueTypes.empty()); 106 107 // Check to see if these types are recursively isomorphic and establish a 108 // mapping between them if so. 109 if (!areTypesIsomorphic(DstTy, SrcTy)) { 110 // Oops, they aren't isomorphic. Just discard this request by rolling out 111 // any speculative mappings we've established. 112 for (Type *Ty : SpeculativeTypes) 113 MappedTypes.erase(Ty); 114 115 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - 116 SpeculativeDstOpaqueTypes.size()); 117 for (StructType *Ty : SpeculativeDstOpaqueTypes) 118 DstResolvedOpaqueTypes.erase(Ty); 119 } else { 120 for (Type *Ty : SpeculativeTypes) 121 if (auto *STy = dyn_cast<StructType>(Ty)) 122 if (STy->hasName()) 123 STy->setName(""); 124 } 125 SpeculativeTypes.clear(); 126 SpeculativeDstOpaqueTypes.clear(); 127 } 128 129 /// Recursively walk this pair of types, returning true if they are isomorphic, 130 /// false if they are not. 131 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 132 // Two types with differing kinds are clearly not isomorphic. 133 if (DstTy->getTypeID() != SrcTy->getTypeID()) 134 return false; 135 136 // If we have an entry in the MappedTypes table, then we have our answer. 137 Type *&Entry = MappedTypes[SrcTy]; 138 if (Entry) 139 return Entry == DstTy; 140 141 // Two identical types are clearly isomorphic. Remember this 142 // non-speculatively. 143 if (DstTy == SrcTy) { 144 Entry = DstTy; 145 return true; 146 } 147 148 // Okay, we have two types with identical kinds that we haven't seen before. 149 150 // If this is an opaque struct type, special case it. 151 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 152 // Mapping an opaque type to any struct, just keep the dest struct. 153 if (SSTy->isOpaque()) { 154 Entry = DstTy; 155 SpeculativeTypes.push_back(SrcTy); 156 return true; 157 } 158 159 // Mapping a non-opaque source type to an opaque dest. If this is the first 160 // type that we're mapping onto this destination type then we succeed. Keep 161 // the dest, but fill it in later. If this is the second (different) type 162 // that we're trying to map onto the same opaque type then we fail. 163 if (cast<StructType>(DstTy)->isOpaque()) { 164 // We can only map one source type onto the opaque destination type. 165 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) 166 return false; 167 SrcDefinitionsToResolve.push_back(SSTy); 168 SpeculativeTypes.push_back(SrcTy); 169 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy)); 170 Entry = DstTy; 171 return true; 172 } 173 } 174 175 // If the number of subtypes disagree between the two types, then we fail. 176 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 177 return false; 178 179 // Fail if any of the extra properties (e.g. array size) of the type disagree. 180 if (isa<IntegerType>(DstTy)) 181 return false; // bitwidth disagrees. 182 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 183 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 184 return false; 185 186 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 187 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 188 return false; 189 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 190 StructType *SSTy = cast<StructType>(SrcTy); 191 if (DSTy->isLiteral() != SSTy->isLiteral() || 192 DSTy->isPacked() != SSTy->isPacked()) 193 return false; 194 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 195 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 196 return false; 197 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 198 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 199 return false; 200 } 201 202 // Otherwise, we speculate that these two types will line up and recursively 203 // check the subelements. 204 Entry = DstTy; 205 SpeculativeTypes.push_back(SrcTy); 206 207 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) 208 if (!areTypesIsomorphic(DstTy->getContainedType(I), 209 SrcTy->getContainedType(I))) 210 return false; 211 212 // If everything seems to have lined up, then everything is great. 213 return true; 214 } 215 216 void TypeMapTy::linkDefinedTypeBodies() { 217 SmallVector<Type*, 16> Elements; 218 for (StructType *SrcSTy : SrcDefinitionsToResolve) { 219 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 220 assert(DstSTy->isOpaque()); 221 222 // Map the body of the source type over to a new body for the dest type. 223 Elements.resize(SrcSTy->getNumElements()); 224 for (unsigned I = 0, E = Elements.size(); I != E; ++I) 225 Elements[I] = get(SrcSTy->getElementType(I)); 226 227 DstSTy->setBody(Elements, SrcSTy->isPacked()); 228 } 229 SrcDefinitionsToResolve.clear(); 230 DstResolvedOpaqueTypes.clear(); 231 } 232 233 void TypeMapTy::finishType(StructType *DTy, StructType *STy, 234 ArrayRef<Type *> ETypes) { 235 DTy->setBody(ETypes, STy->isPacked()); 236 237 // Steal STy's name. 238 if (STy->hasName()) { 239 SmallString<16> TmpName = STy->getName(); 240 STy->setName(""); 241 DTy->setName(TmpName); 242 } 243 244 DstStructTypesSet.addNonOpaque(DTy); 245 } 246 247 Type *TypeMapTy::get(Type *Ty) { 248 SmallPtrSet<StructType *, 8> Visited; 249 return get(Ty, Visited); 250 } 251 252 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) { 253 // If we already have an entry for this type, return it. 254 Type **Entry = &MappedTypes[Ty]; 255 if (*Entry) 256 return *Entry; 257 258 // These are types that LLVM itself will unique. 259 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral(); 260 261 #ifndef NDEBUG 262 if (!IsUniqued) { 263 for (auto &Pair : MappedTypes) { 264 assert(!(Pair.first != Ty && Pair.second == Ty) && 265 "mapping to a source type"); 266 } 267 } 268 #endif 269 270 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) { 271 StructType *DTy = StructType::create(Ty->getContext()); 272 return *Entry = DTy; 273 } 274 275 // If this is not a recursive type, then just map all of the elements and 276 // then rebuild the type from inside out. 277 SmallVector<Type *, 4> ElementTypes; 278 279 // If there are no element types to map, then the type is itself. This is 280 // true for the anonymous {} struct, things like 'float', integers, etc. 281 if (Ty->getNumContainedTypes() == 0 && IsUniqued) 282 return *Entry = Ty; 283 284 // Remap all of the elements, keeping track of whether any of them change. 285 bool AnyChange = false; 286 ElementTypes.resize(Ty->getNumContainedTypes()); 287 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { 288 ElementTypes[I] = get(Ty->getContainedType(I), Visited); 289 AnyChange |= ElementTypes[I] != Ty->getContainedType(I); 290 } 291 292 // If we found our type while recursively processing stuff, just use it. 293 Entry = &MappedTypes[Ty]; 294 if (*Entry) { 295 if (auto *DTy = dyn_cast<StructType>(*Entry)) { 296 if (DTy->isOpaque()) { 297 auto *STy = cast<StructType>(Ty); 298 finishType(DTy, STy, ElementTypes); 299 } 300 } 301 return *Entry; 302 } 303 304 // If all of the element types mapped directly over and the type is not 305 // a nomed struct, then the type is usable as-is. 306 if (!AnyChange && IsUniqued) 307 return *Entry = Ty; 308 309 // Otherwise, rebuild a modified type. 310 switch (Ty->getTypeID()) { 311 default: 312 llvm_unreachable("unknown derived type to remap"); 313 case Type::ArrayTyID: 314 return *Entry = ArrayType::get(ElementTypes[0], 315 cast<ArrayType>(Ty)->getNumElements()); 316 case Type::VectorTyID: 317 return *Entry = VectorType::get(ElementTypes[0], 318 cast<VectorType>(Ty)->getNumElements()); 319 case Type::PointerTyID: 320 return *Entry = PointerType::get(ElementTypes[0], 321 cast<PointerType>(Ty)->getAddressSpace()); 322 case Type::FunctionTyID: 323 return *Entry = FunctionType::get(ElementTypes[0], 324 makeArrayRef(ElementTypes).slice(1), 325 cast<FunctionType>(Ty)->isVarArg()); 326 case Type::StructTyID: { 327 auto *STy = cast<StructType>(Ty); 328 bool IsPacked = STy->isPacked(); 329 if (IsUniqued) 330 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked); 331 332 // If the type is opaque, we can just use it directly. 333 if (STy->isOpaque()) { 334 DstStructTypesSet.addOpaque(STy); 335 return *Entry = Ty; 336 } 337 338 if (StructType *OldT = 339 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) { 340 STy->setName(""); 341 return *Entry = OldT; 342 } 343 344 if (!AnyChange) { 345 DstStructTypesSet.addNonOpaque(STy); 346 return *Entry = Ty; 347 } 348 349 StructType *DTy = StructType::create(Ty->getContext()); 350 finishType(DTy, STy, ElementTypes); 351 return *Entry = DTy; 352 } 353 } 354 } 355 356 //===----------------------------------------------------------------------===// 357 // ModuleLinker implementation. 358 //===----------------------------------------------------------------------===// 359 360 namespace { 361 class ModuleLinker; 362 363 /// Creates prototypes for functions that are lazily linked on the fly. This 364 /// speeds up linking for modules with many/ lazily linked functions of which 365 /// few get used. 366 class ValueMaterializerTy : public ValueMaterializer { 367 TypeMapTy &TypeMap; 368 Module *DstM; 369 std::vector<GlobalValue *> &LazilyLinkGlobalValues; 370 371 public: 372 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 373 std::vector<GlobalValue *> &LazilyLinkGlobalValues) 374 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 375 LazilyLinkGlobalValues(LazilyLinkGlobalValues) {} 376 377 Value *materializeValueFor(Value *V) override; 378 }; 379 380 class LinkDiagnosticInfo : public DiagnosticInfo { 381 const Twine &Msg; 382 383 public: 384 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 385 void print(DiagnosticPrinter &DP) const override; 386 }; 387 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 388 const Twine &Msg) 389 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 390 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 391 392 /// This is an implementation class for the LinkModules function, which is the 393 /// entrypoint for this file. 394 class ModuleLinker { 395 Module *DstM, *SrcM; 396 397 TypeMapTy TypeMap; 398 ValueMaterializerTy ValMaterializer; 399 400 /// Mapping of values from what they used to be in Src, to what they are now 401 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead 402 /// due to the use of Value handles which the Linker doesn't actually need, 403 /// but this allows us to reuse the ValueMapper code. 404 ValueToValueMapTy ValueMap; 405 406 struct AppendingVarInfo { 407 GlobalVariable *NewGV; // New aggregate global in dest module. 408 const Constant *DstInit; // Old initializer from dest module. 409 const Constant *SrcInit; // Old initializer from src module. 410 }; 411 412 std::vector<AppendingVarInfo> AppendingVars; 413 414 // Set of items not to link in from source. 415 SmallPtrSet<const Value *, 16> DoNotLinkFromSource; 416 417 // Vector of GlobalValues to lazily link in. 418 std::vector<GlobalValue *> LazilyLinkGlobalValues; 419 420 /// Functions that have replaced other functions. 421 SmallPtrSet<const Function *, 16> OverridingFunctions; 422 423 DiagnosticHandlerFunction DiagnosticHandler; 424 425 public: 426 ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM, 427 DiagnosticHandlerFunction DiagnosticHandler) 428 : DstM(dstM), SrcM(srcM), TypeMap(Set), 429 ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues), 430 DiagnosticHandler(DiagnosticHandler) {} 431 432 bool run(); 433 434 private: 435 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest, 436 const GlobalValue &Src); 437 438 /// Helper method for setting a message and returning an error code. 439 bool emitError(const Twine &Message) { 440 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message)); 441 return true; 442 } 443 444 void emitWarning(const Twine &Message) { 445 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message)); 446 } 447 448 bool getComdatLeader(Module *M, StringRef ComdatName, 449 const GlobalVariable *&GVar); 450 bool computeResultingSelectionKind(StringRef ComdatName, 451 Comdat::SelectionKind Src, 452 Comdat::SelectionKind Dst, 453 Comdat::SelectionKind &Result, 454 bool &LinkFromSrc); 455 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>> 456 ComdatsChosen; 457 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK, 458 bool &LinkFromSrc); 459 460 /// Given a global in the source module, return the global in the 461 /// destination module that is being linked to, if any. 462 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { 463 // If the source has no name it can't link. If it has local linkage, 464 // there is no name match-up going on. 465 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 466 return nullptr; 467 468 // Otherwise see if we have a match in the destination module's symtab. 469 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 470 if (!DGV) 471 return nullptr; 472 473 // If we found a global with the same name in the dest module, but it has 474 // internal linkage, we are really not doing any linkage here. 475 if (DGV->hasLocalLinkage()) 476 return nullptr; 477 478 // Otherwise, we do in fact link to the destination global. 479 return DGV; 480 } 481 482 void computeTypeMapping(); 483 484 void upgradeMismatchedGlobalArray(StringRef Name); 485 void upgradeMismatchedGlobals(); 486 487 bool linkAppendingVarProto(GlobalVariable *DstGV, 488 const GlobalVariable *SrcGV); 489 490 bool linkGlobalValueProto(GlobalValue *GV); 491 bool linkModuleFlagsMetadata(); 492 493 void linkAppendingVarInit(const AppendingVarInfo &AVI); 494 495 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src); 496 bool linkFunctionBody(Function &Dst, Function &Src); 497 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src); 498 bool linkGlobalValueBody(GlobalValue &Src); 499 500 void linkNamedMDNodes(); 501 void stripReplacedSubprograms(); 502 }; 503 } 504 505 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 506 /// table. This is good for all clients except for us. Go through the trouble 507 /// to force this back. 508 static void forceRenaming(GlobalValue *GV, StringRef Name) { 509 // If the global doesn't force its name or if it already has the right name, 510 // there is nothing for us to do. 511 if (GV->hasLocalLinkage() || GV->getName() == Name) 512 return; 513 514 Module *M = GV->getParent(); 515 516 // If there is a conflict, rename the conflict. 517 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 518 GV->takeName(ConflictGV); 519 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 520 assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 521 } else { 522 GV->setName(Name); // Force the name back 523 } 524 } 525 526 /// copy additional attributes (those not needed to construct a GlobalValue) 527 /// from the SrcGV to the DestGV. 528 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 529 DestGV->copyAttributesFrom(SrcGV); 530 forceRenaming(DestGV, SrcGV->getName()); 531 } 532 533 static bool isLessConstraining(GlobalValue::VisibilityTypes a, 534 GlobalValue::VisibilityTypes b) { 535 if (a == GlobalValue::HiddenVisibility) 536 return false; 537 if (b == GlobalValue::HiddenVisibility) 538 return true; 539 if (a == GlobalValue::ProtectedVisibility) 540 return false; 541 if (b == GlobalValue::ProtectedVisibility) 542 return true; 543 return false; 544 } 545 546 /// Loop through the global variables in the src module and merge them into the 547 /// dest module. 548 static GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM, 549 const GlobalVariable *SGVar) { 550 // No linking to be performed or linking from the source: simply create an 551 // identical version of the symbol over in the dest module... the 552 // initializer will be filled in later by LinkGlobalInits. 553 GlobalVariable *NewDGV = new GlobalVariable( 554 DstM, TypeMap.get(SGVar->getType()->getElementType()), 555 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr, 556 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), 557 SGVar->getType()->getAddressSpace()); 558 559 return NewDGV; 560 } 561 562 /// Link the function in the source module into the destination module if 563 /// needed, setting up mapping information. 564 static Function *copyFunctionProto(TypeMapTy &TypeMap, Module &DstM, 565 const Function *SF) { 566 // If there is no linkage to be performed or we are linking from the source, 567 // bring SF over. 568 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(), 569 SF->getName(), &DstM); 570 } 571 572 /// Set up prototypes for any aliases that come over from the source module. 573 static GlobalAlias *copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM, 574 const GlobalAlias *SGA) { 575 // If there is no linkage to be performed or we're linking from the source, 576 // bring over SGA. 577 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 578 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 579 SGA->getLinkage(), SGA->getName(), &DstM); 580 } 581 582 static GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM, 583 const GlobalValue *SGV) { 584 GlobalValue *NewGV; 585 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) 586 NewGV = copyGlobalVariableProto(TypeMap, DstM, SGVar); 587 else if (auto *SF = dyn_cast<Function>(SGV)) 588 NewGV = copyFunctionProto(TypeMap, DstM, SF); 589 else 590 NewGV = copyGlobalAliasProto(TypeMap, DstM, cast<GlobalAlias>(SGV)); 591 copyGVAttributes(NewGV, SGV); 592 return NewGV; 593 } 594 595 Value *ValueMaterializerTy::materializeValueFor(Value *V) { 596 auto *SGV = dyn_cast<GlobalValue>(V); 597 if (!SGV) 598 return nullptr; 599 600 GlobalValue *DGV = copyGlobalValueProto(TypeMap, *DstM, SGV); 601 602 if (Comdat *SC = SGV->getComdat()) { 603 if (auto *DGO = dyn_cast<GlobalObject>(DGV)) { 604 Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 605 DGO->setComdat(DC); 606 } 607 } 608 609 LazilyLinkGlobalValues.push_back(SGV); 610 return DGV; 611 } 612 613 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 614 const GlobalVariable *&GVar) { 615 const GlobalValue *GVal = M->getNamedValue(ComdatName); 616 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 617 GVal = GA->getBaseObject(); 618 if (!GVal) 619 // We cannot resolve the size of the aliasee yet. 620 return emitError("Linking COMDATs named '" + ComdatName + 621 "': COMDAT key involves incomputable alias size."); 622 } 623 624 GVar = dyn_cast_or_null<GlobalVariable>(GVal); 625 if (!GVar) 626 return emitError( 627 "Linking COMDATs named '" + ComdatName + 628 "': GlobalVariable required for data dependent selection!"); 629 630 return false; 631 } 632 633 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 634 Comdat::SelectionKind Src, 635 Comdat::SelectionKind Dst, 636 Comdat::SelectionKind &Result, 637 bool &LinkFromSrc) { 638 // The ability to mix Comdat::SelectionKind::Any with 639 // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 640 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 641 Dst == Comdat::SelectionKind::Largest; 642 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 643 Src == Comdat::SelectionKind::Largest; 644 if (DstAnyOrLargest && SrcAnyOrLargest) { 645 if (Dst == Comdat::SelectionKind::Largest || 646 Src == Comdat::SelectionKind::Largest) 647 Result = Comdat::SelectionKind::Largest; 648 else 649 Result = Comdat::SelectionKind::Any; 650 } else if (Src == Dst) { 651 Result = Dst; 652 } else { 653 return emitError("Linking COMDATs named '" + ComdatName + 654 "': invalid selection kinds!"); 655 } 656 657 switch (Result) { 658 case Comdat::SelectionKind::Any: 659 // Go with Dst. 660 LinkFromSrc = false; 661 break; 662 case Comdat::SelectionKind::NoDuplicates: 663 return emitError("Linking COMDATs named '" + ComdatName + 664 "': noduplicates has been violated!"); 665 case Comdat::SelectionKind::ExactMatch: 666 case Comdat::SelectionKind::Largest: 667 case Comdat::SelectionKind::SameSize: { 668 const GlobalVariable *DstGV; 669 const GlobalVariable *SrcGV; 670 if (getComdatLeader(DstM, ComdatName, DstGV) || 671 getComdatLeader(SrcM, ComdatName, SrcGV)) 672 return true; 673 674 const DataLayout *DstDL = DstM->getDataLayout(); 675 const DataLayout *SrcDL = SrcM->getDataLayout(); 676 if (!DstDL || !SrcDL) { 677 return emitError( 678 "Linking COMDATs named '" + ComdatName + 679 "': can't do size dependent selection without DataLayout!"); 680 } 681 uint64_t DstSize = 682 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 683 uint64_t SrcSize = 684 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 685 if (Result == Comdat::SelectionKind::ExactMatch) { 686 if (SrcGV->getInitializer() != DstGV->getInitializer()) 687 return emitError("Linking COMDATs named '" + ComdatName + 688 "': ExactMatch violated!"); 689 LinkFromSrc = false; 690 } else if (Result == Comdat::SelectionKind::Largest) { 691 LinkFromSrc = SrcSize > DstSize; 692 } else if (Result == Comdat::SelectionKind::SameSize) { 693 if (SrcSize != DstSize) 694 return emitError("Linking COMDATs named '" + ComdatName + 695 "': SameSize violated!"); 696 LinkFromSrc = false; 697 } else { 698 llvm_unreachable("unknown selection kind"); 699 } 700 break; 701 } 702 } 703 704 return false; 705 } 706 707 bool ModuleLinker::getComdatResult(const Comdat *SrcC, 708 Comdat::SelectionKind &Result, 709 bool &LinkFromSrc) { 710 Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 711 StringRef ComdatName = SrcC->getName(); 712 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 713 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 714 715 if (DstCI == ComdatSymTab.end()) { 716 // Use the comdat if it is only available in one of the modules. 717 LinkFromSrc = true; 718 Result = SSK; 719 return false; 720 } 721 722 const Comdat *DstC = &DstCI->second; 723 Comdat::SelectionKind DSK = DstC->getSelectionKind(); 724 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 725 LinkFromSrc); 726 } 727 728 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 729 const GlobalValue &Dest, 730 const GlobalValue &Src) { 731 // We always have to add Src if it has appending linkage. 732 if (Src.hasAppendingLinkage()) { 733 LinkFromSrc = true; 734 return false; 735 } 736 737 bool SrcIsDeclaration = Src.isDeclarationForLinker(); 738 bool DestIsDeclaration = Dest.isDeclarationForLinker(); 739 740 if (SrcIsDeclaration) { 741 // If Src is external or if both Src & Dest are external.. Just link the 742 // external globals, we aren't adding anything. 743 if (Src.hasDLLImportStorageClass()) { 744 // If one of GVs is marked as DLLImport, result should be dllimport'ed. 745 LinkFromSrc = DestIsDeclaration; 746 return false; 747 } 748 // If the Dest is weak, use the source linkage. 749 LinkFromSrc = Dest.hasExternalWeakLinkage(); 750 return false; 751 } 752 753 if (DestIsDeclaration) { 754 // If Dest is external but Src is not: 755 LinkFromSrc = true; 756 return false; 757 } 758 759 if (Src.hasCommonLinkage()) { 760 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 761 LinkFromSrc = true; 762 return false; 763 } 764 765 if (!Dest.hasCommonLinkage()) { 766 LinkFromSrc = false; 767 return false; 768 } 769 770 // FIXME: Make datalayout mandatory and just use getDataLayout(). 771 DataLayout DL(Dest.getParent()); 772 773 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 774 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 775 LinkFromSrc = SrcSize > DestSize; 776 return false; 777 } 778 779 if (Src.isWeakForLinker()) { 780 assert(!Dest.hasExternalWeakLinkage()); 781 assert(!Dest.hasAvailableExternallyLinkage()); 782 783 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 784 LinkFromSrc = true; 785 return false; 786 } 787 788 LinkFromSrc = false; 789 return false; 790 } 791 792 if (Dest.isWeakForLinker()) { 793 assert(Src.hasExternalLinkage()); 794 LinkFromSrc = true; 795 return false; 796 } 797 798 assert(!Src.hasExternalWeakLinkage()); 799 assert(!Dest.hasExternalWeakLinkage()); 800 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 801 "Unexpected linkage type!"); 802 return emitError("Linking globals named '" + Src.getName() + 803 "': symbol multiply defined!"); 804 } 805 806 /// Loop over all of the linked values to compute type mappings. For example, 807 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 808 /// types 'Foo' but one got renamed when the module was loaded into the same 809 /// LLVMContext. 810 void ModuleLinker::computeTypeMapping() { 811 for (GlobalValue &SGV : SrcM->globals()) { 812 GlobalValue *DGV = getLinkedToGlobal(&SGV); 813 if (!DGV) 814 continue; 815 816 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { 817 TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 818 continue; 819 } 820 821 // Unify the element type of appending arrays. 822 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 823 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType()); 824 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 825 } 826 827 for (GlobalValue &SGV : *SrcM) { 828 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 829 TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 830 } 831 832 for (GlobalValue &SGV : SrcM->aliases()) { 833 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 834 TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 835 } 836 837 // Incorporate types by name, scanning all the types in the source module. 838 // At this point, the destination module may have a type "%foo = { i32 }" for 839 // example. When the source module got loaded into the same LLVMContext, if 840 // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 841 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes(); 842 for (StructType *ST : Types) { 843 if (!ST->hasName()) 844 continue; 845 846 // Check to see if there is a dot in the name followed by a digit. 847 size_t DotPos = ST->getName().rfind('.'); 848 if (DotPos == 0 || DotPos == StringRef::npos || 849 ST->getName().back() == '.' || 850 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1]))) 851 continue; 852 853 // Check to see if the destination module has a struct with the prefix name. 854 StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)); 855 if (!DST) 856 continue; 857 858 // Don't use it if this actually came from the source module. They're in 859 // the same LLVMContext after all. Also don't use it unless the type is 860 // actually used in the destination module. This can happen in situations 861 // like this: 862 // 863 // Module A Module B 864 // -------- -------- 865 // %Z = type { %A } %B = type { %C.1 } 866 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 867 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 868 // %C = type { i8* } %B.3 = type { %C.1 } 869 // 870 // When we link Module B with Module A, the '%B' in Module B is 871 // used. However, that would then use '%C.1'. But when we process '%C.1', 872 // we prefer to take the '%C' version. So we are then left with both 873 // '%C.1' and '%C' being used for the same types. This leads to some 874 // variables using one type and some using the other. 875 if (TypeMap.DstStructTypesSet.hasType(DST)) 876 TypeMap.addTypeMapping(DST, ST); 877 } 878 879 // Now that we have discovered all of the type equivalences, get a body for 880 // any 'opaque' types in the dest module that are now resolved. 881 TypeMap.linkDefinedTypeBodies(); 882 } 883 884 static void upgradeGlobalArray(GlobalVariable *GV) { 885 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 886 StructType *OldTy = cast<StructType>(ATy->getElementType()); 887 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 888 889 // Get the upgraded 3 element type. 890 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 891 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 892 VoidPtrTy}; 893 StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 894 895 // Build new constants with a null third field filled in. 896 Constant *OldInitC = GV->getInitializer(); 897 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 898 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 899 // Invalid initializer; give up. 900 return; 901 std::vector<Constant *> Initializers; 902 if (OldInit && OldInit->getNumOperands()) { 903 Value *Null = Constant::getNullValue(VoidPtrTy); 904 for (Use &U : OldInit->operands()) { 905 ConstantStruct *Init = cast<ConstantStruct>(U.get()); 906 Initializers.push_back(ConstantStruct::get( 907 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 908 } 909 } 910 assert(Initializers.size() == ATy->getNumElements() && 911 "Failed to copy all array elements"); 912 913 // Replace the old GV with a new one. 914 ATy = ArrayType::get(NewTy, Initializers.size()); 915 Constant *NewInit = ConstantArray::get(ATy, Initializers); 916 GlobalVariable *NewGV = new GlobalVariable( 917 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 918 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 919 GV->isExternallyInitialized()); 920 NewGV->copyAttributesFrom(GV); 921 NewGV->takeName(GV); 922 assert(GV->use_empty() && "program cannot use initializer list"); 923 GV->eraseFromParent(); 924 } 925 926 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 927 // Look for the global arrays. 928 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 929 if (!DstGV) 930 return; 931 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 932 if (!SrcGV) 933 return; 934 935 // Check if the types already match. 936 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 937 auto *SrcTy = 938 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 939 if (DstTy == SrcTy) 940 return; 941 942 // Grab the element types. We can only upgrade an array of a two-field 943 // struct. Only bother if the other one has three-fields. 944 auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 945 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 946 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 947 upgradeGlobalArray(DstGV); 948 return; 949 } 950 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 951 upgradeGlobalArray(SrcGV); 952 953 // We can't upgrade any other differences. 954 } 955 956 void ModuleLinker::upgradeMismatchedGlobals() { 957 upgradeMismatchedGlobalArray("llvm.global_ctors"); 958 upgradeMismatchedGlobalArray("llvm.global_dtors"); 959 } 960 961 /// If there were any appending global variables, link them together now. 962 /// Return true on error. 963 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 964 const GlobalVariable *SrcGV) { 965 966 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 967 return emitError("Linking globals named '" + SrcGV->getName() + 968 "': can only link appending global with another appending global!"); 969 970 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 971 ArrayType *SrcTy = 972 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 973 Type *EltTy = DstTy->getElementType(); 974 975 // Check to see that they two arrays agree on type. 976 if (EltTy != SrcTy->getElementType()) 977 return emitError("Appending variables with different element types!"); 978 if (DstGV->isConstant() != SrcGV->isConstant()) 979 return emitError("Appending variables linked with different const'ness!"); 980 981 if (DstGV->getAlignment() != SrcGV->getAlignment()) 982 return emitError( 983 "Appending variables with different alignment need to be linked!"); 984 985 if (DstGV->getVisibility() != SrcGV->getVisibility()) 986 return emitError( 987 "Appending variables with different visibility need to be linked!"); 988 989 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 990 return emitError( 991 "Appending variables with different unnamed_addr need to be linked!"); 992 993 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 994 return emitError( 995 "Appending variables with different section name need to be linked!"); 996 997 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 998 ArrayType *NewType = ArrayType::get(EltTy, NewSize); 999 1000 // Create the new global variable. 1001 GlobalVariable *NG = 1002 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 1003 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 1004 DstGV->getThreadLocalMode(), 1005 DstGV->getType()->getAddressSpace()); 1006 1007 // Propagate alignment, visibility and section info. 1008 copyGVAttributes(NG, DstGV); 1009 1010 AppendingVarInfo AVI; 1011 AVI.NewGV = NG; 1012 AVI.DstInit = DstGV->getInitializer(); 1013 AVI.SrcInit = SrcGV->getInitializer(); 1014 AppendingVars.push_back(AVI); 1015 1016 // Replace any uses of the two global variables with uses of the new 1017 // global. 1018 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 1019 1020 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 1021 DstGV->eraseFromParent(); 1022 1023 // Track the source variable so we don't try to link it. 1024 DoNotLinkFromSource.insert(SrcGV); 1025 1026 return false; 1027 } 1028 1029 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) { 1030 GlobalValue *DGV = getLinkedToGlobal(SGV); 1031 1032 // Handle the ultra special appending linkage case first. 1033 if (DGV && DGV->hasAppendingLinkage()) 1034 return linkAppendingVarProto(cast<GlobalVariable>(DGV), 1035 cast<GlobalVariable>(SGV)); 1036 1037 bool LinkFromSrc = true; 1038 Comdat *C = nullptr; 1039 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility(); 1040 bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 1041 1042 if (const Comdat *SC = SGV->getComdat()) { 1043 Comdat::SelectionKind SK; 1044 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1045 C = DstM->getOrInsertComdat(SC->getName()); 1046 C->setSelectionKind(SK); 1047 } else if (DGV) { 1048 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV)) 1049 return true; 1050 } 1051 1052 if (!LinkFromSrc) { 1053 // Track the source global so that we don't attempt to copy it over when 1054 // processing global initializers. 1055 DoNotLinkFromSource.insert(SGV); 1056 1057 if (DGV) 1058 // Make sure to remember this mapping. 1059 ValueMap[SGV] = 1060 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType())); 1061 } 1062 1063 if (DGV) { 1064 Visibility = isLessConstraining(Visibility, DGV->getVisibility()) 1065 ? DGV->getVisibility() 1066 : Visibility; 1067 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1068 } 1069 1070 if (!LinkFromSrc && !DGV) 1071 return false; 1072 1073 GlobalValue *NewGV; 1074 if (!LinkFromSrc) { 1075 NewGV = DGV; 1076 } else { 1077 // If the GV is to be lazily linked, don't create it just yet. 1078 // The ValueMaterializerTy will deal with creating it if it's used. 1079 if (!DGV && (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() || 1080 SGV->hasAvailableExternallyLinkage())) { 1081 DoNotLinkFromSource.insert(SGV); 1082 return false; 1083 } 1084 1085 NewGV = copyGlobalValueProto(TypeMap, *DstM, SGV); 1086 1087 if (DGV && isa<Function>(DGV)) 1088 if (auto *NewF = dyn_cast<Function>(NewGV)) 1089 OverridingFunctions.insert(NewF); 1090 } 1091 1092 NewGV->setUnnamedAddr(HasUnnamedAddr); 1093 NewGV->setVisibility(Visibility); 1094 1095 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { 1096 if (C) 1097 NewGO->setComdat(C); 1098 1099 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage()) 1100 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment())); 1101 } 1102 1103 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) { 1104 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV); 1105 auto *SGVar = dyn_cast<GlobalVariable>(SGV); 1106 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() && 1107 (!DGVar->isConstant() || !SGVar->isConstant())) 1108 NewGVar->setConstant(false); 1109 } 1110 1111 // Make sure to remember this mapping. 1112 if (NewGV != DGV) { 1113 if (DGV) { 1114 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType())); 1115 DGV->eraseFromParent(); 1116 } 1117 ValueMap[SGV] = NewGV; 1118 } 1119 1120 return false; 1121 } 1122 1123 static void getArrayElements(const Constant *C, 1124 SmallVectorImpl<Constant *> &Dest) { 1125 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 1126 1127 for (unsigned i = 0; i != NumElements; ++i) 1128 Dest.push_back(C->getAggregateElement(i)); 1129 } 1130 1131 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1132 // Merge the initializer. 1133 SmallVector<Constant *, 16> DstElements; 1134 getArrayElements(AVI.DstInit, DstElements); 1135 1136 SmallVector<Constant *, 16> SrcElements; 1137 getArrayElements(AVI.SrcInit, SrcElements); 1138 1139 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1140 1141 StringRef Name = AVI.NewGV->getName(); 1142 bool IsNewStructor = 1143 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1144 cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1145 1146 for (auto *V : SrcElements) { 1147 if (IsNewStructor) { 1148 Constant *Key = V->getAggregateElement(2); 1149 if (DoNotLinkFromSource.count(Key)) 1150 continue; 1151 } 1152 DstElements.push_back( 1153 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1154 } 1155 if (IsNewStructor) { 1156 NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1157 AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1158 } 1159 1160 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1161 } 1162 1163 /// Update the initializers in the Dest module now that all globals that may be 1164 /// referenced are in Dest. 1165 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) { 1166 // Figure out what the initializer looks like in the dest module. 1167 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, RF_None, &TypeMap, 1168 &ValMaterializer)); 1169 } 1170 1171 /// Copy the source function over into the dest function and fix up references 1172 /// to values. At this point we know that Dest is an external function, and 1173 /// that Src is not. 1174 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) { 1175 assert(Dst.isDeclaration() && !Src.isDeclaration()); 1176 1177 // Materialize if needed. 1178 if (std::error_code EC = Src.materialize()) 1179 return emitError(EC.message()); 1180 1181 // Link in the prefix data. 1182 if (Src.hasPrefixData()) 1183 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, RF_None, &TypeMap, 1184 &ValMaterializer)); 1185 1186 // Link in the prologue data. 1187 if (Src.hasPrologueData()) 1188 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, RF_None, 1189 &TypeMap, &ValMaterializer)); 1190 1191 // Go through and convert function arguments over, remembering the mapping. 1192 Function::arg_iterator DI = Dst.arg_begin(); 1193 for (Argument &Arg : Src.args()) { 1194 DI->setName(Arg.getName()); // Copy the name over. 1195 1196 // Add a mapping to our mapping. 1197 ValueMap[&Arg] = DI; 1198 ++DI; 1199 } 1200 1201 // Splice the body of the source function into the dest function. 1202 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList()); 1203 1204 // At this point, all of the instructions and values of the function are now 1205 // copied over. The only problem is that they are still referencing values in 1206 // the Source function as operands. Loop through all of the operands of the 1207 // functions and patch them up to point to the local versions. 1208 for (BasicBlock &BB : Dst) 1209 for (Instruction &I : BB) 1210 RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries, &TypeMap, 1211 &ValMaterializer); 1212 1213 // There is no need to map the arguments anymore. 1214 for (Argument &Arg : Src.args()) 1215 ValueMap.erase(&Arg); 1216 1217 Src.Dematerialize(); 1218 return false; 1219 } 1220 1221 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) { 1222 Constant *Aliasee = Src.getAliasee(); 1223 Constant *Val = 1224 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 1225 Dst.setAliasee(Val); 1226 } 1227 1228 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) { 1229 Value *Dst = ValueMap[&Src]; 1230 assert(Dst); 1231 if (auto *F = dyn_cast<Function>(&Src)) 1232 return linkFunctionBody(cast<Function>(*Dst), *F); 1233 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) { 1234 linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar); 1235 return false; 1236 } 1237 linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src)); 1238 return false; 1239 } 1240 1241 /// Insert all of the named MDNodes in Src into the Dest module. 1242 void ModuleLinker::linkNamedMDNodes() { 1243 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1244 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1245 E = SrcM->named_metadata_end(); I != E; ++I) { 1246 // Don't link module flags here. Do them separately. 1247 if (&*I == SrcModFlags) continue; 1248 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1249 // Add Src elements into Dest node. 1250 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1251 DestNMD->addOperand(MapMetadata(I->getOperand(i), ValueMap, RF_None, 1252 &TypeMap, &ValMaterializer)); 1253 } 1254 } 1255 1256 /// Drop DISubprograms that have been superseded. 1257 /// 1258 /// FIXME: this creates an asymmetric result: we strip losing subprograms from 1259 /// DstM, but leave losing subprograms in SrcM. Instead we should also strip 1260 /// losers from SrcM, but this requires extra plumbing in MapMetadata. 1261 void ModuleLinker::stripReplacedSubprograms() { 1262 // Avoid quadratic runtime by returning early when there's nothing to do. 1263 if (OverridingFunctions.empty()) 1264 return; 1265 1266 // Move the functions now, so the set gets cleared even on early returns. 1267 auto Functions = std::move(OverridingFunctions); 1268 OverridingFunctions.clear(); 1269 1270 // Drop subprograms whose functions have been overridden by the new compile 1271 // unit. 1272 NamedMDNode *CompileUnits = DstM->getNamedMetadata("llvm.dbg.cu"); 1273 if (!CompileUnits) 1274 return; 1275 for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) { 1276 DICompileUnit CU(CompileUnits->getOperand(I)); 1277 assert(CU && "Expected valid compile unit"); 1278 1279 DITypedArray<DISubprogram> SPs(CU.getSubprograms()); 1280 assert(SPs && "Expected valid subprogram array"); 1281 1282 SmallVector<Metadata *, 16> NewSPs; 1283 NewSPs.reserve(SPs.getNumElements()); 1284 for (unsigned S = 0, SE = SPs.getNumElements(); S != SE; ++S) { 1285 DISubprogram SP = SPs.getElement(S); 1286 if (SP && SP.getFunction() && Functions.count(SP.getFunction())) 1287 continue; 1288 1289 NewSPs.push_back(SP); 1290 } 1291 1292 // Redirect operand to the overriding subprogram. 1293 if (NewSPs.size() != SPs.getNumElements()) 1294 CU.replaceSubprograms(DIArray(MDNode::get(DstM->getContext(), NewSPs))); 1295 } 1296 } 1297 1298 /// Merge the linker flags in Src into the Dest module. 1299 bool ModuleLinker::linkModuleFlagsMetadata() { 1300 // If the source module has no module flags, we are done. 1301 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1302 if (!SrcModFlags) return false; 1303 1304 // If the destination module doesn't have module flags yet, then just copy 1305 // over the source module's flags. 1306 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 1307 if (DstModFlags->getNumOperands() == 0) { 1308 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 1309 DstModFlags->addOperand(SrcModFlags->getOperand(I)); 1310 1311 return false; 1312 } 1313 1314 // First build a map of the existing module flags and requirements. 1315 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags; 1316 SmallSetVector<MDNode*, 16> Requirements; 1317 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1318 MDNode *Op = DstModFlags->getOperand(I); 1319 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0)); 1320 MDString *ID = cast<MDString>(Op->getOperand(1)); 1321 1322 if (Behavior->getZExtValue() == Module::Require) { 1323 Requirements.insert(cast<MDNode>(Op->getOperand(2))); 1324 } else { 1325 Flags[ID] = std::make_pair(Op, I); 1326 } 1327 } 1328 1329 // Merge in the flags from the source module, and also collect its set of 1330 // requirements. 1331 bool HasErr = false; 1332 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1333 MDNode *SrcOp = SrcModFlags->getOperand(I); 1334 ConstantInt *SrcBehavior = 1335 mdconst::extract<ConstantInt>(SrcOp->getOperand(0)); 1336 MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 1337 MDNode *DstOp; 1338 unsigned DstIndex; 1339 std::tie(DstOp, DstIndex) = Flags.lookup(ID); 1340 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 1341 1342 // If this is a requirement, add it and continue. 1343 if (SrcBehaviorValue == Module::Require) { 1344 // If the destination module does not already have this requirement, add 1345 // it. 1346 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 1347 DstModFlags->addOperand(SrcOp); 1348 } 1349 continue; 1350 } 1351 1352 // If there is no existing flag with this ID, just add it. 1353 if (!DstOp) { 1354 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands()); 1355 DstModFlags->addOperand(SrcOp); 1356 continue; 1357 } 1358 1359 // Otherwise, perform a merge. 1360 ConstantInt *DstBehavior = 1361 mdconst::extract<ConstantInt>(DstOp->getOperand(0)); 1362 unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 1363 1364 // If either flag has override behavior, handle it first. 1365 if (DstBehaviorValue == Module::Override) { 1366 // Diagnose inconsistent flags which both have override behavior. 1367 if (SrcBehaviorValue == Module::Override && 1368 SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1369 HasErr |= emitError("linking module flags '" + ID->getString() + 1370 "': IDs have conflicting override values"); 1371 } 1372 continue; 1373 } else if (SrcBehaviorValue == Module::Override) { 1374 // Update the destination flag to that of the source. 1375 DstModFlags->setOperand(DstIndex, SrcOp); 1376 Flags[ID].first = SrcOp; 1377 continue; 1378 } 1379 1380 // Diagnose inconsistent merge behavior types. 1381 if (SrcBehaviorValue != DstBehaviorValue) { 1382 HasErr |= emitError("linking module flags '" + ID->getString() + 1383 "': IDs have conflicting behaviors"); 1384 continue; 1385 } 1386 1387 auto replaceDstValue = [&](MDNode *New) { 1388 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New}; 1389 MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps); 1390 DstModFlags->setOperand(DstIndex, Flag); 1391 Flags[ID].first = Flag; 1392 }; 1393 1394 // Perform the merge for standard behavior types. 1395 switch (SrcBehaviorValue) { 1396 case Module::Require: 1397 case Module::Override: llvm_unreachable("not possible"); 1398 case Module::Error: { 1399 // Emit an error if the values differ. 1400 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1401 HasErr |= emitError("linking module flags '" + ID->getString() + 1402 "': IDs have conflicting values"); 1403 } 1404 continue; 1405 } 1406 case Module::Warning: { 1407 // Emit a warning if the values differ. 1408 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1409 emitWarning("linking module flags '" + ID->getString() + 1410 "': IDs have conflicting values"); 1411 } 1412 continue; 1413 } 1414 case Module::Append: { 1415 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1416 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1417 SmallVector<Metadata *, 8> MDs; 1418 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands()); 1419 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1420 MDs.push_back(DstValue->getOperand(i)); 1421 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1422 MDs.push_back(SrcValue->getOperand(i)); 1423 1424 replaceDstValue(MDNode::get(DstM->getContext(), MDs)); 1425 break; 1426 } 1427 case Module::AppendUnique: { 1428 SmallSetVector<Metadata *, 16> Elts; 1429 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1430 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1431 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1432 Elts.insert(DstValue->getOperand(i)); 1433 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1434 Elts.insert(SrcValue->getOperand(i)); 1435 1436 replaceDstValue(MDNode::get(DstM->getContext(), 1437 makeArrayRef(Elts.begin(), Elts.end()))); 1438 break; 1439 } 1440 } 1441 } 1442 1443 // Check all of the requirements. 1444 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 1445 MDNode *Requirement = Requirements[I]; 1446 MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1447 Metadata *ReqValue = Requirement->getOperand(1); 1448 1449 MDNode *Op = Flags[Flag].first; 1450 if (!Op || Op->getOperand(2) != ReqValue) { 1451 HasErr |= emitError("linking module flags '" + Flag->getString() + 1452 "': does not have the required value"); 1453 continue; 1454 } 1455 } 1456 1457 return HasErr; 1458 } 1459 1460 bool ModuleLinker::run() { 1461 assert(DstM && "Null destination module"); 1462 assert(SrcM && "Null source module"); 1463 1464 // Inherit the target data from the source module if the destination module 1465 // doesn't have one already. 1466 if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1467 DstM->setDataLayout(SrcM->getDataLayout()); 1468 1469 // Copy the target triple from the source to dest if the dest's is empty. 1470 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1471 DstM->setTargetTriple(SrcM->getTargetTriple()); 1472 1473 if (SrcM->getDataLayout() && DstM->getDataLayout() && 1474 *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1475 emitWarning("Linking two modules of different data layouts: '" + 1476 SrcM->getModuleIdentifier() + "' is '" + 1477 SrcM->getDataLayoutStr() + "' whereas '" + 1478 DstM->getModuleIdentifier() + "' is '" + 1479 DstM->getDataLayoutStr() + "'\n"); 1480 } 1481 if (!SrcM->getTargetTriple().empty() && 1482 DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1483 emitWarning("Linking two modules of different target triples: " + 1484 SrcM->getModuleIdentifier() + "' is '" + 1485 SrcM->getTargetTriple() + "' whereas '" + 1486 DstM->getModuleIdentifier() + "' is '" + 1487 DstM->getTargetTriple() + "'\n"); 1488 } 1489 1490 // Append the module inline asm string. 1491 if (!SrcM->getModuleInlineAsm().empty()) { 1492 if (DstM->getModuleInlineAsm().empty()) 1493 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1494 else 1495 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1496 SrcM->getModuleInlineAsm()); 1497 } 1498 1499 // Loop over all of the linked values to compute type mappings. 1500 computeTypeMapping(); 1501 1502 ComdatsChosen.clear(); 1503 for (const auto &SMEC : SrcM->getComdatSymbolTable()) { 1504 const Comdat &C = SMEC.getValue(); 1505 if (ComdatsChosen.count(&C)) 1506 continue; 1507 Comdat::SelectionKind SK; 1508 bool LinkFromSrc; 1509 if (getComdatResult(&C, SK, LinkFromSrc)) 1510 return true; 1511 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1512 } 1513 1514 // Upgrade mismatched global arrays. 1515 upgradeMismatchedGlobals(); 1516 1517 // Insert all of the globals in src into the DstM module... without linking 1518 // initializers (which could refer to functions not yet mapped over). 1519 for (Module::global_iterator I = SrcM->global_begin(), 1520 E = SrcM->global_end(); I != E; ++I) 1521 if (linkGlobalValueProto(I)) 1522 return true; 1523 1524 // Link the functions together between the two modules, without doing function 1525 // bodies... this just adds external function prototypes to the DstM 1526 // function... We do this so that when we begin processing function bodies, 1527 // all of the global values that may be referenced are available in our 1528 // ValueMap. 1529 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1530 if (linkGlobalValueProto(I)) 1531 return true; 1532 1533 // If there were any aliases, link them now. 1534 for (Module::alias_iterator I = SrcM->alias_begin(), 1535 E = SrcM->alias_end(); I != E; ++I) 1536 if (linkGlobalValueProto(I)) 1537 return true; 1538 1539 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1540 linkAppendingVarInit(AppendingVars[i]); 1541 1542 for (const auto &Entry : DstM->getComdatSymbolTable()) { 1543 const Comdat &C = Entry.getValue(); 1544 if (C.getSelectionKind() == Comdat::Any) 1545 continue; 1546 const GlobalValue *GV = SrcM->getNamedValue(C.getName()); 1547 assert(GV); 1548 MapValue(GV, ValueMap, RF_None, &TypeMap, &ValMaterializer); 1549 } 1550 1551 // Link in the function bodies that are defined in the source module into 1552 // DstM. 1553 for (Function &SF : *SrcM) { 1554 // Skip if no body (function is external). 1555 if (SF.isDeclaration()) 1556 continue; 1557 1558 // Skip if not linking from source. 1559 if (DoNotLinkFromSource.count(&SF)) 1560 continue; 1561 1562 if (linkGlobalValueBody(SF)) 1563 return true; 1564 } 1565 1566 // Resolve all uses of aliases with aliasees. 1567 for (GlobalAlias &Src : SrcM->aliases()) { 1568 if (DoNotLinkFromSource.count(&Src)) 1569 continue; 1570 linkGlobalValueBody(Src); 1571 } 1572 1573 // Strip replaced subprograms before linking together compile units. 1574 stripReplacedSubprograms(); 1575 1576 // Remap all of the named MDNodes in Src into the DstM module. We do this 1577 // after linking GlobalValues so that MDNodes that reference GlobalValues 1578 // are properly remapped. 1579 linkNamedMDNodes(); 1580 1581 // Merge the module flags into the DstM module. 1582 if (linkModuleFlagsMetadata()) 1583 return true; 1584 1585 // Update the initializers in the DstM module now that all globals that may 1586 // be referenced are in DstM. 1587 for (GlobalVariable &Src : SrcM->globals()) { 1588 // Only process initialized GV's or ones not already in dest. 1589 if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src)) 1590 continue; 1591 linkGlobalValueBody(Src); 1592 } 1593 1594 // Process vector of lazily linked in functions. 1595 while (!LazilyLinkGlobalValues.empty()) { 1596 GlobalValue *SGV = LazilyLinkGlobalValues.back(); 1597 LazilyLinkGlobalValues.pop_back(); 1598 1599 assert(!SGV->isDeclaration() && "users should not pass down decls"); 1600 if (linkGlobalValueBody(*SGV)) 1601 return true; 1602 } 1603 1604 return false; 1605 } 1606 1607 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P) 1608 : ETypes(E), IsPacked(P) {} 1609 1610 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST) 1611 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {} 1612 1613 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const { 1614 if (IsPacked != That.IsPacked) 1615 return false; 1616 if (ETypes != That.ETypes) 1617 return false; 1618 return true; 1619 } 1620 1621 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const { 1622 return !this->operator==(That); 1623 } 1624 1625 StructType *Linker::StructTypeKeyInfo::getEmptyKey() { 1626 return DenseMapInfo<StructType *>::getEmptyKey(); 1627 } 1628 1629 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() { 1630 return DenseMapInfo<StructType *>::getTombstoneKey(); 1631 } 1632 1633 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) { 1634 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()), 1635 Key.IsPacked); 1636 } 1637 1638 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) { 1639 return getHashValue(KeyTy(ST)); 1640 } 1641 1642 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS, 1643 const StructType *RHS) { 1644 if (RHS == getEmptyKey() || RHS == getTombstoneKey()) 1645 return false; 1646 return LHS == KeyTy(RHS); 1647 } 1648 1649 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS, 1650 const StructType *RHS) { 1651 if (RHS == getEmptyKey()) 1652 return LHS == getEmptyKey(); 1653 1654 if (RHS == getTombstoneKey()) 1655 return LHS == getTombstoneKey(); 1656 1657 return KeyTy(LHS) == KeyTy(RHS); 1658 } 1659 1660 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) { 1661 assert(!Ty->isOpaque()); 1662 NonOpaqueStructTypes.insert(Ty); 1663 } 1664 1665 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) { 1666 assert(Ty->isOpaque()); 1667 OpaqueStructTypes.insert(Ty); 1668 } 1669 1670 StructType * 1671 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes, 1672 bool IsPacked) { 1673 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked); 1674 auto I = NonOpaqueStructTypes.find_as(Key); 1675 if (I == NonOpaqueStructTypes.end()) 1676 return nullptr; 1677 return *I; 1678 } 1679 1680 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) { 1681 if (Ty->isOpaque()) 1682 return OpaqueStructTypes.count(Ty); 1683 auto I = NonOpaqueStructTypes.find(Ty); 1684 if (I == NonOpaqueStructTypes.end()) 1685 return false; 1686 return *I == Ty; 1687 } 1688 1689 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 1690 this->Composite = M; 1691 this->DiagnosticHandler = DiagnosticHandler; 1692 1693 TypeFinder StructTypes; 1694 StructTypes.run(*M, true); 1695 for (StructType *Ty : StructTypes) { 1696 if (Ty->isOpaque()) 1697 IdentifiedStructTypes.addOpaque(Ty); 1698 else 1699 IdentifiedStructTypes.addNonOpaque(Ty); 1700 } 1701 } 1702 1703 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 1704 init(M, DiagnosticHandler); 1705 } 1706 1707 Linker::Linker(Module *M) { 1708 init(M, [this](const DiagnosticInfo &DI) { 1709 Composite->getContext().diagnose(DI); 1710 }); 1711 } 1712 1713 Linker::~Linker() { 1714 } 1715 1716 void Linker::deleteModule() { 1717 delete Composite; 1718 Composite = nullptr; 1719 } 1720 1721 bool Linker::linkInModule(Module *Src) { 1722 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, 1723 DiagnosticHandler); 1724 return TheLinker.run(); 1725 } 1726 1727 //===----------------------------------------------------------------------===// 1728 // LinkModules entrypoint. 1729 //===----------------------------------------------------------------------===// 1730 1731 /// This function links two modules together, with the resulting Dest module 1732 /// modified to be the composite of the two input modules. If an error occurs, 1733 /// true is returned and ErrorMsg (if not null) is set to indicate the problem. 1734 /// Upon failure, the Dest module could be in a modified state, and shouldn't be 1735 /// relied on to be consistent. 1736 bool Linker::LinkModules(Module *Dest, Module *Src, 1737 DiagnosticHandlerFunction DiagnosticHandler) { 1738 Linker L(Dest, DiagnosticHandler); 1739 return L.linkInModule(Src); 1740 } 1741 1742 bool Linker::LinkModules(Module *Dest, Module *Src) { 1743 Linker L(Dest); 1744 return L.linkInModule(Src); 1745 } 1746 1747 //===----------------------------------------------------------------------===// 1748 // C API. 1749 //===----------------------------------------------------------------------===// 1750 1751 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1752 LLVMLinkerMode Mode, char **OutMessages) { 1753 Module *D = unwrap(Dest); 1754 std::string Message; 1755 raw_string_ostream Stream(Message); 1756 DiagnosticPrinterRawOStream DP(Stream); 1757 1758 LLVMBool Result = Linker::LinkModules( 1759 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); }); 1760 1761 if (OutMessages && Result) 1762 *OutMessages = strdup(Message.c_str()); 1763 return Result; 1764 } 1765