1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Linker/IRMover.h"
11 #include "LinkDiagnosticInfo.h"
12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DiagnosticPrinter.h"
17 #include "llvm/IR/GVMaterializer.h"
18 #include "llvm/IR/TypeFinder.h"
19 #include "llvm/Transforms/Utils/Cloning.h"
22 //===----------------------------------------------------------------------===//
23 // TypeMap implementation.
24 //===----------------------------------------------------------------------===//
27 class TypeMapTy : public ValueMapTypeRemapper {
28 /// This is a mapping from a source type to a destination type to use.
29 DenseMap<Type *, Type *> MappedTypes;
31 /// When checking to see if two subgraphs are isomorphic, we speculatively
32 /// add types to MappedTypes, but keep track of them here in case we need to
34 SmallVector<Type *, 16> SpeculativeTypes;
36 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
38 /// This is a list of non-opaque structs in the source module that are mapped
39 /// to an opaque struct in the destination module.
40 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
42 /// This is the set of opaque types in the destination modules who are
43 /// getting a body from the source module.
44 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
47 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
48 : DstStructTypesSet(DstStructTypesSet) {}
50 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
51 /// Indicate that the specified type in the destination module is conceptually
52 /// equivalent to the specified type in the source module.
53 void addTypeMapping(Type *DstTy, Type *SrcTy);
55 /// Produce a body for an opaque type in the dest module from a type
56 /// definition in the source module.
57 void linkDefinedTypeBodies();
59 /// Return the mapped type to use for the specified input type from the
61 Type *get(Type *SrcTy);
62 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
64 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
66 FunctionType *get(FunctionType *T) {
67 return cast<FunctionType>(get((Type *)T));
71 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
73 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
77 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
78 assert(SpeculativeTypes.empty());
79 assert(SpeculativeDstOpaqueTypes.empty());
81 // Check to see if these types are recursively isomorphic and establish a
82 // mapping between them if so.
83 if (!areTypesIsomorphic(DstTy, SrcTy)) {
84 // Oops, they aren't isomorphic. Just discard this request by rolling out
85 // any speculative mappings we've established.
86 for (Type *Ty : SpeculativeTypes)
87 MappedTypes.erase(Ty);
89 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
90 SpeculativeDstOpaqueTypes.size());
91 for (StructType *Ty : SpeculativeDstOpaqueTypes)
92 DstResolvedOpaqueTypes.erase(Ty);
94 for (Type *Ty : SpeculativeTypes)
95 if (auto *STy = dyn_cast<StructType>(Ty))
99 SpeculativeTypes.clear();
100 SpeculativeDstOpaqueTypes.clear();
103 /// Recursively walk this pair of types, returning true if they are isomorphic,
104 /// false if they are not.
105 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
106 // Two types with differing kinds are clearly not isomorphic.
107 if (DstTy->getTypeID() != SrcTy->getTypeID())
110 // If we have an entry in the MappedTypes table, then we have our answer.
111 Type *&Entry = MappedTypes[SrcTy];
113 return Entry == DstTy;
115 // Two identical types are clearly isomorphic. Remember this
116 // non-speculatively.
117 if (DstTy == SrcTy) {
122 // Okay, we have two types with identical kinds that we haven't seen before.
124 // If this is an opaque struct type, special case it.
125 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
126 // Mapping an opaque type to any struct, just keep the dest struct.
127 if (SSTy->isOpaque()) {
129 SpeculativeTypes.push_back(SrcTy);
133 // Mapping a non-opaque source type to an opaque dest. If this is the first
134 // type that we're mapping onto this destination type then we succeed. Keep
135 // the dest, but fill it in later. If this is the second (different) type
136 // that we're trying to map onto the same opaque type then we fail.
137 if (cast<StructType>(DstTy)->isOpaque()) {
138 // We can only map one source type onto the opaque destination type.
139 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
141 SrcDefinitionsToResolve.push_back(SSTy);
142 SpeculativeTypes.push_back(SrcTy);
143 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
149 // If the number of subtypes disagree between the two types, then we fail.
150 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
153 // Fail if any of the extra properties (e.g. array size) of the type disagree.
154 if (isa<IntegerType>(DstTy))
155 return false; // bitwidth disagrees.
156 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
157 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
160 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
161 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
163 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
164 StructType *SSTy = cast<StructType>(SrcTy);
165 if (DSTy->isLiteral() != SSTy->isLiteral() ||
166 DSTy->isPacked() != SSTy->isPacked())
168 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
169 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
171 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
172 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
176 // Otherwise, we speculate that these two types will line up and recursively
177 // check the subelements.
179 SpeculativeTypes.push_back(SrcTy);
181 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
182 if (!areTypesIsomorphic(DstTy->getContainedType(I),
183 SrcTy->getContainedType(I)))
186 // If everything seems to have lined up, then everything is great.
190 void TypeMapTy::linkDefinedTypeBodies() {
191 SmallVector<Type *, 16> Elements;
192 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
193 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
194 assert(DstSTy->isOpaque());
196 // Map the body of the source type over to a new body for the dest type.
197 Elements.resize(SrcSTy->getNumElements());
198 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
199 Elements[I] = get(SrcSTy->getElementType(I));
201 DstSTy->setBody(Elements, SrcSTy->isPacked());
202 DstStructTypesSet.switchToNonOpaque(DstSTy);
204 SrcDefinitionsToResolve.clear();
205 DstResolvedOpaqueTypes.clear();
208 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
209 ArrayRef<Type *> ETypes) {
210 DTy->setBody(ETypes, STy->isPacked());
213 if (STy->hasName()) {
214 SmallString<16> TmpName = STy->getName();
216 DTy->setName(TmpName);
219 DstStructTypesSet.addNonOpaque(DTy);
222 Type *TypeMapTy::get(Type *Ty) {
223 SmallPtrSet<StructType *, 8> Visited;
224 return get(Ty, Visited);
227 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
228 // If we already have an entry for this type, return it.
229 Type **Entry = &MappedTypes[Ty];
233 // These are types that LLVM itself will unique.
234 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
238 for (auto &Pair : MappedTypes) {
239 assert(!(Pair.first != Ty && Pair.second == Ty) &&
240 "mapping to a source type");
245 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
246 StructType *DTy = StructType::create(Ty->getContext());
250 // If this is not a recursive type, then just map all of the elements and
251 // then rebuild the type from inside out.
252 SmallVector<Type *, 4> ElementTypes;
254 // If there are no element types to map, then the type is itself. This is
255 // true for the anonymous {} struct, things like 'float', integers, etc.
256 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
259 // Remap all of the elements, keeping track of whether any of them change.
260 bool AnyChange = false;
261 ElementTypes.resize(Ty->getNumContainedTypes());
262 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
263 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
264 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
267 // If we found our type while recursively processing stuff, just use it.
268 Entry = &MappedTypes[Ty];
270 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
271 if (DTy->isOpaque()) {
272 auto *STy = cast<StructType>(Ty);
273 finishType(DTy, STy, ElementTypes);
279 // If all of the element types mapped directly over and the type is not
280 // a nomed struct, then the type is usable as-is.
281 if (!AnyChange && IsUniqued)
284 // Otherwise, rebuild a modified type.
285 switch (Ty->getTypeID()) {
287 llvm_unreachable("unknown derived type to remap");
288 case Type::ArrayTyID:
289 return *Entry = ArrayType::get(ElementTypes[0],
290 cast<ArrayType>(Ty)->getNumElements());
291 case Type::VectorTyID:
292 return *Entry = VectorType::get(ElementTypes[0],
293 cast<VectorType>(Ty)->getNumElements());
294 case Type::PointerTyID:
295 return *Entry = PointerType::get(ElementTypes[0],
296 cast<PointerType>(Ty)->getAddressSpace());
297 case Type::FunctionTyID:
298 return *Entry = FunctionType::get(ElementTypes[0],
299 makeArrayRef(ElementTypes).slice(1),
300 cast<FunctionType>(Ty)->isVarArg());
301 case Type::StructTyID: {
302 auto *STy = cast<StructType>(Ty);
303 bool IsPacked = STy->isPacked();
305 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
307 // If the type is opaque, we can just use it directly.
308 if (STy->isOpaque()) {
309 DstStructTypesSet.addOpaque(STy);
313 if (StructType *OldT =
314 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
316 return *Entry = OldT;
320 DstStructTypesSet.addNonOpaque(STy);
324 StructType *DTy = StructType::create(Ty->getContext());
325 finishType(DTy, STy, ElementTypes);
331 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
333 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
334 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
336 //===----------------------------------------------------------------------===//
337 // ModuleLinker implementation.
338 //===----------------------------------------------------------------------===//
343 /// Creates prototypes for functions that are lazily linked on the fly. This
344 /// speeds up linking for modules with many/ lazily linked functions of which
346 class GlobalValueMaterializer final : public ValueMaterializer {
350 GlobalValueMaterializer(IRLinker *ModLinker) : ModLinker(ModLinker) {}
351 Value *materializeDeclFor(Value *V) override;
352 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
353 Metadata *mapTemporaryMetadata(Metadata *MD) override;
354 void replaceTemporaryMetadata(const Metadata *OrigMD,
355 Metadata *NewMD) override;
358 class LocalValueMaterializer final : public ValueMaterializer {
362 LocalValueMaterializer(IRLinker *ModLinker) : ModLinker(ModLinker) {}
363 Value *materializeDeclFor(Value *V) override;
364 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
365 Metadata *mapTemporaryMetadata(Metadata *MD) override;
366 void replaceTemporaryMetadata(const Metadata *OrigMD,
367 Metadata *NewMD) override;
370 /// This is responsible for keeping track of the state used for moving data
371 /// from SrcM to DstM.
376 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
379 GlobalValueMaterializer GValMaterializer;
380 LocalValueMaterializer LValMaterializer;
382 /// Mapping of values from what they used to be in Src, to what they are now
383 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
384 /// due to the use of Value handles which the Linker doesn't actually need,
385 /// but this allows us to reuse the ValueMapper code.
386 ValueToValueMapTy ValueMap;
387 ValueToValueMapTy AliasValueMap;
389 DenseSet<GlobalValue *> ValuesToLink;
390 std::vector<GlobalValue *> Worklist;
392 void maybeAdd(GlobalValue *GV) {
393 if (ValuesToLink.insert(GV).second)
394 Worklist.push_back(GV);
397 /// Set to true when all global value body linking is complete (including
398 /// lazy linking). Used to prevent metadata linking from creating new
400 bool DoneLinkingBodies = false;
402 bool HasError = false;
404 /// Flag indicating that we are just linking metadata (after function
406 bool IsMetadataLinkingPostpass;
408 /// Flags to pass to value mapper invocations.
409 RemapFlags ValueMapperFlags = RF_MoveDistinctMDs;
411 /// Association between metadata values created during bitcode parsing and
412 /// the value id. Used to correlate temporary metadata created during
413 /// function importing with the final metadata parsed during the subsequent
414 /// metadata linking postpass.
415 DenseMap<const Metadata *, unsigned> MDValueToValIDMap;
417 /// Association between metadata value id and temporary metadata that
418 /// remains unmapped after function importing. Saved during function
419 /// importing and consumed during the metadata linking postpass.
420 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
422 /// Handles cloning of a global values from the source module into
423 /// the destination module, including setting the attributes and visibility.
424 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
426 /// Helper method for setting a message and returning an error code.
427 bool emitError(const Twine &Message) {
428 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
433 void emitWarning(const Twine &Message) {
434 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
437 /// Check whether we should be linking metadata from the source module.
438 bool shouldLinkMetadata() {
439 // ValIDToTempMDMap will be non-null when we are importing or otherwise want
440 // to link metadata lazily, and then when linking the metadata.
441 // We only want to return true for the former case.
442 return ValIDToTempMDMap == nullptr || IsMetadataLinkingPostpass;
445 /// Given a global in the source module, return the global in the
446 /// destination module that is being linked to, if any.
447 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
448 // If the source has no name it can't link. If it has local linkage,
449 // there is no name match-up going on.
450 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
453 // Otherwise see if we have a match in the destination module's symtab.
454 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
458 // If we found a global with the same name in the dest module, but it has
459 // internal linkage, we are really not doing any linkage here.
460 if (DGV->hasLocalLinkage())
463 // Otherwise, we do in fact link to the destination global.
467 void computeTypeMapping();
469 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
470 const GlobalVariable *SrcGV);
472 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
473 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
475 bool linkModuleFlagsMetadata();
477 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
478 bool linkFunctionBody(Function &Dst, Function &Src);
479 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
480 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
482 /// Functions that take care of cloning a specific global value type
483 /// into the destination module.
484 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
485 Function *copyFunctionProto(const Function *SF);
486 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
488 void linkNamedMDNodes();
491 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set, Module &SrcM,
492 ArrayRef<GlobalValue *> ValuesToLink,
493 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
494 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr,
495 bool IsMetadataLinkingPostpass = false)
496 : DstM(DstM), SrcM(SrcM), AddLazyFor(AddLazyFor), TypeMap(Set),
497 GValMaterializer(this), LValMaterializer(this),
498 IsMetadataLinkingPostpass(IsMetadataLinkingPostpass),
499 ValIDToTempMDMap(ValIDToTempMDMap) {
500 for (GlobalValue *GV : ValuesToLink)
503 // If appropriate, tell the value mapper that it can expect to see
504 // temporary metadata.
505 if (!shouldLinkMetadata())
506 ValueMapperFlags = ValueMapperFlags | RF_HaveUnmaterializedMetadata;
510 Value *materializeDeclFor(Value *V, bool ForAlias);
511 void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias);
513 /// Save the mapping between the given temporary metadata and its metadata
514 /// value id. Used to support metadata linking as a postpass for function
516 Metadata *mapTemporaryMetadata(Metadata *MD);
518 /// Replace any temporary metadata saved for the source metadata's id with
519 /// the new non-temporary metadata. Used when metadata linking as a postpass
520 /// for function importing.
521 void replaceTemporaryMetadata(const Metadata *OrigMD, Metadata *NewMD);
525 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
526 /// table. This is good for all clients except for us. Go through the trouble
527 /// to force this back.
528 static void forceRenaming(GlobalValue *GV, StringRef Name) {
529 // If the global doesn't force its name or if it already has the right name,
530 // there is nothing for us to do.
531 if (GV->hasLocalLinkage() || GV->getName() == Name)
534 Module *M = GV->getParent();
536 // If there is a conflict, rename the conflict.
537 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
538 GV->takeName(ConflictGV);
539 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
540 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
542 GV->setName(Name); // Force the name back
546 Value *GlobalValueMaterializer::materializeDeclFor(Value *V) {
547 return ModLinker->materializeDeclFor(V, false);
550 void GlobalValueMaterializer::materializeInitFor(GlobalValue *New,
552 ModLinker->materializeInitFor(New, Old, false);
555 Metadata *GlobalValueMaterializer::mapTemporaryMetadata(Metadata *MD) {
556 return ModLinker->mapTemporaryMetadata(MD);
559 void GlobalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD,
561 ModLinker->replaceTemporaryMetadata(OrigMD, NewMD);
564 Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
565 return ModLinker->materializeDeclFor(V, true);
568 void LocalValueMaterializer::materializeInitFor(GlobalValue *New,
570 ModLinker->materializeInitFor(New, Old, true);
573 Metadata *LocalValueMaterializer::mapTemporaryMetadata(Metadata *MD) {
574 return ModLinker->mapTemporaryMetadata(MD);
577 void LocalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD,
579 ModLinker->replaceTemporaryMetadata(OrigMD, NewMD);
582 Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) {
583 auto *SGV = dyn_cast<GlobalValue>(V);
587 return linkGlobalValueProto(SGV, ForAlias);
590 void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old,
592 // If we already created the body, just return.
593 if (auto *F = dyn_cast<Function>(New)) {
594 if (!F->isDeclaration())
596 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
597 if (V->hasInitializer())
600 auto *A = cast<GlobalAlias>(New);
605 if (ForAlias || shouldLink(New, *Old))
606 linkGlobalValueBody(*New, *Old);
609 Metadata *IRLinker::mapTemporaryMetadata(Metadata *MD) {
610 if (!ValIDToTempMDMap)
612 // If this temporary metadata has a value id recorded during function
613 // parsing, record that in the ValIDToTempMDMap if one was provided.
614 if (MDValueToValIDMap.count(MD)) {
615 unsigned Idx = MDValueToValIDMap[MD];
616 // Check if we created a temp MD when importing a different function from
617 // this module. If so, reuse it the same temporary metadata, otherwise
618 // add this temporary metadata to the map.
619 if (!ValIDToTempMDMap->count(Idx)) {
620 MDNode *Node = cast<MDNode>(MD);
621 assert(Node->isTemporary());
622 (*ValIDToTempMDMap)[Idx] = Node;
624 return (*ValIDToTempMDMap)[Idx];
629 void IRLinker::replaceTemporaryMetadata(const Metadata *OrigMD,
631 if (!ValIDToTempMDMap)
634 auto *N = dyn_cast_or_null<MDNode>(NewMD);
635 assert(!N || !N->isTemporary());
637 // If a mapping between metadata value ids and temporary metadata
638 // created during function importing was provided, and the source
639 // metadata has a value id recorded during metadata parsing, replace
640 // the temporary metadata with the final mapped metadata now.
641 if (MDValueToValIDMap.count(OrigMD)) {
642 unsigned Idx = MDValueToValIDMap[OrigMD];
643 // Nothing to do if we didn't need to create a temporary metadata during
644 // function importing.
645 if (!ValIDToTempMDMap->count(Idx))
647 MDNode *TempMD = (*ValIDToTempMDMap)[Idx];
648 TempMD->replaceAllUsesWith(NewMD);
649 MDNode::deleteTemporary(TempMD);
650 ValIDToTempMDMap->erase(Idx);
654 /// Loop through the global variables in the src module and merge them into the
656 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
657 // No linking to be performed or linking from the source: simply create an
658 // identical version of the symbol over in the dest module... the
659 // initializer will be filled in later by LinkGlobalInits.
660 GlobalVariable *NewDGV =
661 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
662 SGVar->isConstant(), GlobalValue::ExternalLinkage,
663 /*init*/ nullptr, SGVar->getName(),
664 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
665 SGVar->getType()->getAddressSpace());
666 NewDGV->setAlignment(SGVar->getAlignment());
670 /// Link the function in the source module into the destination module if
671 /// needed, setting up mapping information.
672 Function *IRLinker::copyFunctionProto(const Function *SF) {
673 // If there is no linkage to be performed or we are linking from the source,
675 return Function::Create(TypeMap.get(SF->getFunctionType()),
676 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
679 /// Set up prototypes for any aliases that come over from the source module.
680 GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
681 // If there is no linkage to be performed or we're linking from the source,
683 auto *Ty = TypeMap.get(SGA->getValueType());
684 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
685 GlobalValue::ExternalLinkage, SGA->getName(),
689 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
690 bool ForDefinition) {
692 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
693 NewGV = copyGlobalVariableProto(SGVar);
694 } else if (auto *SF = dyn_cast<Function>(SGV)) {
695 NewGV = copyFunctionProto(SF);
698 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
700 NewGV = new GlobalVariable(
701 DstM, TypeMap.get(SGV->getType()->getElementType()),
702 /*isConstant*/ false, GlobalValue::ExternalLinkage,
703 /*init*/ nullptr, SGV->getName(),
704 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
705 SGV->getType()->getAddressSpace());
709 NewGV->setLinkage(SGV->getLinkage());
710 else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() ||
711 SGV->hasLinkOnceLinkage())
712 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
714 NewGV->copyAttributesFrom(SGV);
718 /// Loop over all of the linked values to compute type mappings. For example,
719 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
720 /// types 'Foo' but one got renamed when the module was loaded into the same
722 void IRLinker::computeTypeMapping() {
723 for (GlobalValue &SGV : SrcM.globals()) {
724 GlobalValue *DGV = getLinkedToGlobal(&SGV);
728 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
729 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
733 // Unify the element type of appending arrays.
734 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
735 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
736 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
739 for (GlobalValue &SGV : SrcM)
740 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
741 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
743 for (GlobalValue &SGV : SrcM.aliases())
744 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
745 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
747 // Incorporate types by name, scanning all the types in the source module.
748 // At this point, the destination module may have a type "%foo = { i32 }" for
749 // example. When the source module got loaded into the same LLVMContext, if
750 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
751 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
752 for (StructType *ST : Types) {
756 // Check to see if there is a dot in the name followed by a digit.
757 size_t DotPos = ST->getName().rfind('.');
758 if (DotPos == 0 || DotPos == StringRef::npos ||
759 ST->getName().back() == '.' ||
760 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
763 // Check to see if the destination module has a struct with the prefix name.
764 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
768 // Don't use it if this actually came from the source module. They're in
769 // the same LLVMContext after all. Also don't use it unless the type is
770 // actually used in the destination module. This can happen in situations
775 // %Z = type { %A } %B = type { %C.1 }
776 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
777 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
778 // %C = type { i8* } %B.3 = type { %C.1 }
780 // When we link Module B with Module A, the '%B' in Module B is
781 // used. However, that would then use '%C.1'. But when we process '%C.1',
782 // we prefer to take the '%C' version. So we are then left with both
783 // '%C.1' and '%C' being used for the same types. This leads to some
784 // variables using one type and some using the other.
785 if (TypeMap.DstStructTypesSet.hasType(DST))
786 TypeMap.addTypeMapping(DST, ST);
789 // Now that we have discovered all of the type equivalences, get a body for
790 // any 'opaque' types in the dest module that are now resolved.
791 TypeMap.linkDefinedTypeBodies();
794 static void getArrayElements(const Constant *C,
795 SmallVectorImpl<Constant *> &Dest) {
796 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
798 for (unsigned i = 0; i != NumElements; ++i)
799 Dest.push_back(C->getAggregateElement(i));
802 /// If there were any appending global variables, link them together now.
803 /// Return true on error.
804 Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
805 const GlobalVariable *SrcGV) {
806 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
809 StringRef Name = SrcGV->getName();
810 bool IsNewStructor = false;
811 bool IsOldStructor = false;
812 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
813 if (cast<StructType>(EltTy)->getNumElements() == 3)
814 IsNewStructor = true;
816 IsOldStructor = true;
819 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
821 auto &ST = *cast<StructType>(EltTy);
822 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
823 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
827 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
829 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
831 "Linking globals named '" + SrcGV->getName() +
832 "': can only link appending global with another appending global!");
836 // Check to see that they two arrays agree on type.
837 if (EltTy != DstTy->getElementType()) {
838 emitError("Appending variables with different element types!");
841 if (DstGV->isConstant() != SrcGV->isConstant()) {
842 emitError("Appending variables linked with different const'ness!");
846 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
848 "Appending variables with different alignment need to be linked!");
852 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
854 "Appending variables with different visibility need to be linked!");
858 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
860 "Appending variables with different unnamed_addr need to be linked!");
864 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
866 "Appending variables with different section name need to be linked!");
871 SmallVector<Constant *, 16> DstElements;
873 getArrayElements(DstGV->getInitializer(), DstElements);
875 SmallVector<Constant *, 16> SrcElements;
876 getArrayElements(SrcGV->getInitializer(), SrcElements);
880 std::remove_if(SrcElements.begin(), SrcElements.end(),
881 [this](Constant *E) {
882 auto *Key = dyn_cast<GlobalValue>(
883 E->getAggregateElement(2)->stripPointerCasts());
886 GlobalValue *DGV = getLinkedToGlobal(Key);
887 return !shouldLink(DGV, *Key);
890 uint64_t NewSize = DstElements.size() + SrcElements.size();
891 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
893 // Create the new global variable.
894 GlobalVariable *NG = new GlobalVariable(
895 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
896 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
897 SrcGV->getType()->getAddressSpace());
899 NG->copyAttributesFrom(SrcGV);
900 forceRenaming(NG, SrcGV->getName());
902 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
905 ValueMap[SrcGV] = Ret;
907 for (auto *V : SrcElements) {
910 auto *S = cast<ConstantStruct>(V);
911 auto *E1 = MapValue(S->getOperand(0), ValueMap, ValueMapperFlags,
912 &TypeMap, &GValMaterializer);
913 auto *E2 = MapValue(S->getOperand(1), ValueMap, ValueMapperFlags,
914 &TypeMap, &GValMaterializer);
915 Value *Null = Constant::getNullValue(VoidPtrTy);
917 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
920 MapValue(V, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
922 DstElements.push_back(NewV);
925 NG->setInitializer(ConstantArray::get(NewType, DstElements));
927 // Replace any uses of the two global variables with uses of the new
930 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
931 DstGV->eraseFromParent();
937 static bool useExistingDest(GlobalValue &SGV, GlobalValue *DGV,
942 if (SGV.isDeclaration())
945 if (DGV->isDeclarationForLinker() && !SGV.isDeclarationForLinker())
954 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
955 // Already imported all the values. Just map to the Dest value
956 // in case it is referenced in the metadata.
957 if (IsMetadataLinkingPostpass) {
958 assert(!ValuesToLink.count(&SGV) &&
959 "Source value unexpectedly requested for link during metadata link");
963 if (ValuesToLink.count(&SGV))
966 if (SGV.hasLocalLinkage())
969 if (DGV && !DGV->isDeclaration())
972 if (SGV.hasAvailableExternallyLinkage())
975 if (DoneLinkingBodies)
978 AddLazyFor(SGV, [this](GlobalValue &GV) { maybeAdd(&GV); });
979 return ValuesToLink.count(&SGV);
982 Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
983 GlobalValue *DGV = getLinkedToGlobal(SGV);
985 bool ShouldLink = shouldLink(DGV, *SGV);
987 // just missing from map
989 auto I = ValueMap.find(SGV);
990 if (I != ValueMap.end())
991 return cast<Constant>(I->second);
993 I = AliasValueMap.find(SGV);
994 if (I != AliasValueMap.end())
995 return cast<Constant>(I->second);
999 if (ShouldLink || !ForAlias)
1000 DGV = getLinkedToGlobal(SGV);
1002 // Handle the ultra special appending linkage case first.
1003 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1004 if (SGV->hasAppendingLinkage())
1005 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1006 cast<GlobalVariable>(SGV));
1009 if (useExistingDest(*SGV, DGV, ShouldLink)) {
1012 // If we are done linking global value bodies (i.e. we are performing
1013 // metadata linking), don't link in the global value due to this
1014 // reference, simply map it to null.
1015 if (DoneLinkingBodies)
1018 NewGV = copyGlobalValueProto(SGV, ShouldLink);
1020 forceRenaming(NewGV, SGV->getName());
1022 if (ShouldLink || ForAlias) {
1023 if (const Comdat *SC = SGV->getComdat()) {
1024 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1025 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1026 DC->setSelectionKind(SC->getSelectionKind());
1032 if (!ShouldLink && ForAlias)
1033 NewGV->setLinkage(GlobalValue::InternalLinkage);
1035 Constant *C = NewGV;
1037 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1039 if (DGV && NewGV != DGV) {
1040 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1041 DGV->eraseFromParent();
1047 /// Update the initializers in the Dest module now that all globals that may be
1048 /// referenced are in Dest.
1049 void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1050 // Figure out what the initializer looks like in the dest module.
1051 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, ValueMapperFlags,
1052 &TypeMap, &GValMaterializer));
1055 /// Copy the source function over into the dest function and fix up references
1056 /// to values. At this point we know that Dest is an external function, and
1057 /// that Src is not.
1058 bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1059 assert(Dst.isDeclaration() && !Src.isDeclaration());
1061 // Materialize if needed.
1062 if (std::error_code EC = Src.materialize())
1063 return emitError(EC.message());
1065 if (!shouldLinkMetadata())
1066 // This is only supported for lazy links. Do after materialization of
1067 // a function and before remapping metadata on instructions below
1068 // in RemapInstruction, as the saved mapping is used to handle
1069 // the temporary metadata hanging off instructions.
1070 SrcM.getMaterializer()->saveMDValueList(MDValueToValIDMap, true);
1072 // Link in the prefix data.
1073 if (Src.hasPrefixData())
1074 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, ValueMapperFlags,
1075 &TypeMap, &GValMaterializer));
1077 // Link in the prologue data.
1078 if (Src.hasPrologueData())
1079 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1080 ValueMapperFlags, &TypeMap,
1081 &GValMaterializer));
1083 // Link in the personality function.
1084 if (Src.hasPersonalityFn())
1085 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1086 ValueMapperFlags, &TypeMap,
1087 &GValMaterializer));
1089 // Go through and convert function arguments over, remembering the mapping.
1090 Function::arg_iterator DI = Dst.arg_begin();
1091 for (Argument &Arg : Src.args()) {
1092 DI->setName(Arg.getName()); // Copy the name over.
1094 // Add a mapping to our mapping.
1095 ValueMap[&Arg] = &*DI;
1099 // Copy over the metadata attachments.
1100 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1101 Src.getAllMetadata(MDs);
1102 for (const auto &I : MDs)
1103 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, ValueMapperFlags,
1104 &TypeMap, &GValMaterializer));
1106 // Splice the body of the source function into the dest function.
1107 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1109 // At this point, all of the instructions and values of the function are now
1110 // copied over. The only problem is that they are still referencing values in
1111 // the Source function as operands. Loop through all of the operands of the
1112 // functions and patch them up to point to the local versions.
1113 for (BasicBlock &BB : Dst)
1114 for (Instruction &I : BB)
1115 RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries | ValueMapperFlags,
1116 &TypeMap, &GValMaterializer);
1118 // There is no need to map the arguments anymore.
1119 for (Argument &Arg : Src.args())
1120 ValueMap.erase(&Arg);
1122 Src.dematerialize();
1126 void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1127 Constant *Aliasee = Src.getAliasee();
1128 Constant *Val = MapValue(Aliasee, AliasValueMap, ValueMapperFlags, &TypeMap,
1130 Dst.setAliasee(Val);
1133 bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1134 if (auto *F = dyn_cast<Function>(&Src))
1135 return linkFunctionBody(cast<Function>(Dst), *F);
1136 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1137 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1140 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1144 /// Insert all of the named MDNodes in Src into the Dest module.
1145 void IRLinker::linkNamedMDNodes() {
1146 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1147 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1148 // Don't link module flags here. Do them separately.
1149 if (&NMD == SrcModFlags)
1151 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1152 // Add Src elements into Dest node.
1153 for (const MDNode *op : NMD.operands())
1154 DestNMD->addOperand(MapMetadata(
1155 op, ValueMap, ValueMapperFlags | RF_NullMapMissingGlobalValues,
1156 &TypeMap, &GValMaterializer));
1160 /// Merge the linker flags in Src into the Dest module.
1161 bool IRLinker::linkModuleFlagsMetadata() {
1162 // If the source module has no module flags, we are done.
1163 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1167 // If the destination module doesn't have module flags yet, then just copy
1168 // over the source module's flags.
1169 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1170 if (DstModFlags->getNumOperands() == 0) {
1171 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1172 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1177 // First build a map of the existing module flags and requirements.
1178 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1179 SmallSetVector<MDNode *, 16> Requirements;
1180 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1181 MDNode *Op = DstModFlags->getOperand(I);
1182 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1183 MDString *ID = cast<MDString>(Op->getOperand(1));
1185 if (Behavior->getZExtValue() == Module::Require) {
1186 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1188 Flags[ID] = std::make_pair(Op, I);
1192 // Merge in the flags from the source module, and also collect its set of
1194 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1195 MDNode *SrcOp = SrcModFlags->getOperand(I);
1196 ConstantInt *SrcBehavior =
1197 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1198 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1201 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1202 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1204 // If this is a requirement, add it and continue.
1205 if (SrcBehaviorValue == Module::Require) {
1206 // If the destination module does not already have this requirement, add
1208 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1209 DstModFlags->addOperand(SrcOp);
1214 // If there is no existing flag with this ID, just add it.
1216 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1217 DstModFlags->addOperand(SrcOp);
1221 // Otherwise, perform a merge.
1222 ConstantInt *DstBehavior =
1223 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1224 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1226 // If either flag has override behavior, handle it first.
1227 if (DstBehaviorValue == Module::Override) {
1228 // Diagnose inconsistent flags which both have override behavior.
1229 if (SrcBehaviorValue == Module::Override &&
1230 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1231 emitError("linking module flags '" + ID->getString() +
1232 "': IDs have conflicting override values");
1235 } else if (SrcBehaviorValue == Module::Override) {
1236 // Update the destination flag to that of the source.
1237 DstModFlags->setOperand(DstIndex, SrcOp);
1238 Flags[ID].first = SrcOp;
1242 // Diagnose inconsistent merge behavior types.
1243 if (SrcBehaviorValue != DstBehaviorValue) {
1244 emitError("linking module flags '" + ID->getString() +
1245 "': IDs have conflicting behaviors");
1249 auto replaceDstValue = [&](MDNode *New) {
1250 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1251 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1252 DstModFlags->setOperand(DstIndex, Flag);
1253 Flags[ID].first = Flag;
1256 // Perform the merge for standard behavior types.
1257 switch (SrcBehaviorValue) {
1258 case Module::Require:
1259 case Module::Override:
1260 llvm_unreachable("not possible");
1261 case Module::Error: {
1262 // Emit an error if the values differ.
1263 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1264 emitError("linking module flags '" + ID->getString() +
1265 "': IDs have conflicting values");
1269 case Module::Warning: {
1270 // Emit a warning if the values differ.
1271 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1272 emitWarning("linking module flags '" + ID->getString() +
1273 "': IDs have conflicting values");
1277 case Module::Append: {
1278 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1279 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1280 SmallVector<Metadata *, 8> MDs;
1281 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1282 MDs.append(DstValue->op_begin(), DstValue->op_end());
1283 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1285 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1288 case Module::AppendUnique: {
1289 SmallSetVector<Metadata *, 16> Elts;
1290 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1291 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1292 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1293 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1295 replaceDstValue(MDNode::get(DstM.getContext(),
1296 makeArrayRef(Elts.begin(), Elts.end())));
1302 // Check all of the requirements.
1303 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1304 MDNode *Requirement = Requirements[I];
1305 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1306 Metadata *ReqValue = Requirement->getOperand(1);
1308 MDNode *Op = Flags[Flag].first;
1309 if (!Op || Op->getOperand(2) != ReqValue) {
1310 emitError("linking module flags '" + Flag->getString() +
1311 "': does not have the required value");
1319 // This function returns true if the triples match.
1320 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1321 // If vendor is apple, ignore the version number.
1322 if (T0.getVendor() == Triple::Apple)
1323 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1324 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1329 // This function returns the merged triple.
1330 static std::string mergeTriples(const Triple &SrcTriple,
1331 const Triple &DstTriple) {
1332 // If vendor is apple, pick the triple with the larger version number.
1333 if (SrcTriple.getVendor() == Triple::Apple)
1334 if (DstTriple.isOSVersionLT(SrcTriple))
1335 return SrcTriple.str();
1337 return DstTriple.str();
1340 bool IRLinker::run() {
1341 // Inherit the target data from the source module if the destination module
1342 // doesn't have one already.
1343 if (DstM.getDataLayout().isDefault())
1344 DstM.setDataLayout(SrcM.getDataLayout());
1346 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1347 emitWarning("Linking two modules of different data layouts: '" +
1348 SrcM.getModuleIdentifier() + "' is '" +
1349 SrcM.getDataLayoutStr() + "' whereas '" +
1350 DstM.getModuleIdentifier() + "' is '" +
1351 DstM.getDataLayoutStr() + "'\n");
1354 // Copy the target triple from the source to dest if the dest's is empty.
1355 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1356 DstM.setTargetTriple(SrcM.getTargetTriple());
1358 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1360 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1361 emitWarning("Linking two modules of different target triples: " +
1362 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1363 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1364 DstM.getTargetTriple() + "'\n");
1366 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1368 // Append the module inline asm string.
1369 if (!SrcM.getModuleInlineAsm().empty()) {
1370 if (DstM.getModuleInlineAsm().empty())
1371 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1373 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1374 SrcM.getModuleInlineAsm());
1377 // Loop over all of the linked values to compute type mappings.
1378 computeTypeMapping();
1380 std::reverse(Worklist.begin(), Worklist.end());
1381 while (!Worklist.empty()) {
1382 GlobalValue *GV = Worklist.back();
1383 Worklist.pop_back();
1386 if (ValueMap.find(GV) != ValueMap.end() ||
1387 AliasValueMap.find(GV) != AliasValueMap.end())
1390 assert(!GV->isDeclaration());
1391 MapValue(GV, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
1396 // Note that we are done linking global value bodies. This prevents
1397 // metadata linking from creating new references.
1398 DoneLinkingBodies = true;
1400 // Remap all of the named MDNodes in Src into the DstM module. We do this
1401 // after linking GlobalValues so that MDNodes that reference GlobalValues
1402 // are properly remapped.
1403 if (shouldLinkMetadata()) {
1404 // Even if just linking metadata we should link decls above in case
1405 // any are referenced by metadata. IRLinker::shouldLink ensures that
1406 // we don't actually link anything from source.
1407 if (IsMetadataLinkingPostpass) {
1408 // Ensure metadata materialized
1409 if (SrcM.getMaterializer()->materializeMetadata())
1411 SrcM.getMaterializer()->saveMDValueList(MDValueToValIDMap, false);
1416 if (IsMetadataLinkingPostpass) {
1417 // Handle anything left in the ValIDToTempMDMap, such as metadata nodes
1418 // not reached by the dbg.cu NamedMD (i.e. only reached from
1420 // Walk the MDValueToValIDMap once to find the set of new (imported) MD
1421 // that still has corresponding temporary metadata, and invoke metadata
1422 // mapping on each one.
1423 for (auto MDI : MDValueToValIDMap) {
1424 if (!ValIDToTempMDMap->count(MDI.second))
1426 MapMetadata(MDI.first, ValueMap, ValueMapperFlags, &TypeMap,
1429 assert(ValIDToTempMDMap->empty());
1432 // Merge the module flags into the DstM module.
1433 if (linkModuleFlagsMetadata())
1440 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1441 : ETypes(E), IsPacked(P) {}
1443 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1444 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1446 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1447 if (IsPacked != That.IsPacked)
1449 if (ETypes != That.ETypes)
1454 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1455 return !this->operator==(That);
1458 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1459 return DenseMapInfo<StructType *>::getEmptyKey();
1462 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1463 return DenseMapInfo<StructType *>::getTombstoneKey();
1466 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1467 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1471 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1472 return getHashValue(KeyTy(ST));
1475 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1476 const StructType *RHS) {
1477 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1479 return LHS == KeyTy(RHS);
1482 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1483 const StructType *RHS) {
1484 if (RHS == getEmptyKey())
1485 return LHS == getEmptyKey();
1487 if (RHS == getTombstoneKey())
1488 return LHS == getTombstoneKey();
1490 return KeyTy(LHS) == KeyTy(RHS);
1493 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1494 assert(!Ty->isOpaque());
1495 NonOpaqueStructTypes.insert(Ty);
1498 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1499 assert(!Ty->isOpaque());
1500 NonOpaqueStructTypes.insert(Ty);
1501 bool Removed = OpaqueStructTypes.erase(Ty);
1506 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1507 assert(Ty->isOpaque());
1508 OpaqueStructTypes.insert(Ty);
1512 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1514 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1515 auto I = NonOpaqueStructTypes.find_as(Key);
1516 if (I == NonOpaqueStructTypes.end())
1521 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1523 return OpaqueStructTypes.count(Ty);
1524 auto I = NonOpaqueStructTypes.find(Ty);
1525 if (I == NonOpaqueStructTypes.end())
1530 IRMover::IRMover(Module &M) : Composite(M) {
1531 TypeFinder StructTypes;
1532 StructTypes.run(M, true);
1533 for (StructType *Ty : StructTypes) {
1535 IdentifiedStructTypes.addOpaque(Ty);
1537 IdentifiedStructTypes.addNonOpaque(Ty);
1542 Module &Src, ArrayRef<GlobalValue *> ValuesToLink,
1543 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
1544 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap,
1545 bool IsMetadataLinkingPostpass) {
1546 IRLinker TheLinker(Composite, IdentifiedStructTypes, Src, ValuesToLink,
1547 AddLazyFor, ValIDToTempMDMap, IsMetadataLinkingPostpass);
1548 bool RetCode = TheLinker.run();
1549 Composite.dropTriviallyDeadConstantArrays();