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