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/TypeFinder.h"
18 #include "llvm/Transforms/Utils/Cloning.h"
21 //===----------------------------------------------------------------------===//
22 // TypeMap implementation.
23 //===----------------------------------------------------------------------===//
26 class TypeMapTy : public ValueMapTypeRemapper {
27 /// This is a mapping from a source type to a destination type to use.
28 DenseMap<Type *, Type *> MappedTypes;
30 /// When checking to see if two subgraphs are isomorphic, we speculatively
31 /// add types to MappedTypes, but keep track of them here in case we need to
33 SmallVector<Type *, 16> SpeculativeTypes;
35 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
37 /// This is a list of non-opaque structs in the source module that are mapped
38 /// to an opaque struct in the destination module.
39 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
41 /// This is the set of opaque types in the destination modules who are
42 /// getting a body from the source module.
43 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
46 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
47 : DstStructTypesSet(DstStructTypesSet) {}
49 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
50 /// Indicate that the specified type in the destination module is conceptually
51 /// equivalent to the specified type in the source module.
52 void addTypeMapping(Type *DstTy, Type *SrcTy);
54 /// Produce a body for an opaque type in the dest module from a type
55 /// definition in the source module.
56 void linkDefinedTypeBodies();
58 /// Return the mapped type to use for the specified input type from the
60 Type *get(Type *SrcTy);
61 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
63 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
65 FunctionType *get(FunctionType *T) {
66 return cast<FunctionType>(get((Type *)T));
70 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
72 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
76 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
77 assert(SpeculativeTypes.empty());
78 assert(SpeculativeDstOpaqueTypes.empty());
80 // Check to see if these types are recursively isomorphic and establish a
81 // mapping between them if so.
82 if (!areTypesIsomorphic(DstTy, SrcTy)) {
83 // Oops, they aren't isomorphic. Just discard this request by rolling out
84 // any speculative mappings we've established.
85 for (Type *Ty : SpeculativeTypes)
86 MappedTypes.erase(Ty);
88 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
89 SpeculativeDstOpaqueTypes.size());
90 for (StructType *Ty : SpeculativeDstOpaqueTypes)
91 DstResolvedOpaqueTypes.erase(Ty);
93 for (Type *Ty : SpeculativeTypes)
94 if (auto *STy = dyn_cast<StructType>(Ty))
98 SpeculativeTypes.clear();
99 SpeculativeDstOpaqueTypes.clear();
102 /// Recursively walk this pair of types, returning true if they are isomorphic,
103 /// false if they are not.
104 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
105 // Two types with differing kinds are clearly not isomorphic.
106 if (DstTy->getTypeID() != SrcTy->getTypeID())
109 // If we have an entry in the MappedTypes table, then we have our answer.
110 Type *&Entry = MappedTypes[SrcTy];
112 return Entry == DstTy;
114 // Two identical types are clearly isomorphic. Remember this
115 // non-speculatively.
116 if (DstTy == SrcTy) {
121 // Okay, we have two types with identical kinds that we haven't seen before.
123 // If this is an opaque struct type, special case it.
124 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
125 // Mapping an opaque type to any struct, just keep the dest struct.
126 if (SSTy->isOpaque()) {
128 SpeculativeTypes.push_back(SrcTy);
132 // Mapping a non-opaque source type to an opaque dest. If this is the first
133 // type that we're mapping onto this destination type then we succeed. Keep
134 // the dest, but fill it in later. If this is the second (different) type
135 // that we're trying to map onto the same opaque type then we fail.
136 if (cast<StructType>(DstTy)->isOpaque()) {
137 // We can only map one source type onto the opaque destination type.
138 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
140 SrcDefinitionsToResolve.push_back(SSTy);
141 SpeculativeTypes.push_back(SrcTy);
142 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
148 // If the number of subtypes disagree between the two types, then we fail.
149 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
152 // Fail if any of the extra properties (e.g. array size) of the type disagree.
153 if (isa<IntegerType>(DstTy))
154 return false; // bitwidth disagrees.
155 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
156 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
159 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
160 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
162 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
163 StructType *SSTy = cast<StructType>(SrcTy);
164 if (DSTy->isLiteral() != SSTy->isLiteral() ||
165 DSTy->isPacked() != SSTy->isPacked())
167 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
168 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
170 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
171 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
175 // Otherwise, we speculate that these two types will line up and recursively
176 // check the subelements.
178 SpeculativeTypes.push_back(SrcTy);
180 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
181 if (!areTypesIsomorphic(DstTy->getContainedType(I),
182 SrcTy->getContainedType(I)))
185 // If everything seems to have lined up, then everything is great.
189 void TypeMapTy::linkDefinedTypeBodies() {
190 SmallVector<Type *, 16> Elements;
191 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
192 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
193 assert(DstSTy->isOpaque());
195 // Map the body of the source type over to a new body for the dest type.
196 Elements.resize(SrcSTy->getNumElements());
197 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
198 Elements[I] = get(SrcSTy->getElementType(I));
200 DstSTy->setBody(Elements, SrcSTy->isPacked());
201 DstStructTypesSet.switchToNonOpaque(DstSTy);
203 SrcDefinitionsToResolve.clear();
204 DstResolvedOpaqueTypes.clear();
207 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
208 ArrayRef<Type *> ETypes) {
209 DTy->setBody(ETypes, STy->isPacked());
212 if (STy->hasName()) {
213 SmallString<16> TmpName = STy->getName();
215 DTy->setName(TmpName);
218 DstStructTypesSet.addNonOpaque(DTy);
221 Type *TypeMapTy::get(Type *Ty) {
222 SmallPtrSet<StructType *, 8> Visited;
223 return get(Ty, Visited);
226 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
227 // If we already have an entry for this type, return it.
228 Type **Entry = &MappedTypes[Ty];
232 // These are types that LLVM itself will unique.
233 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
237 for (auto &Pair : MappedTypes) {
238 assert(!(Pair.first != Ty && Pair.second == Ty) &&
239 "mapping to a source type");
244 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
245 StructType *DTy = StructType::create(Ty->getContext());
249 // If this is not a recursive type, then just map all of the elements and
250 // then rebuild the type from inside out.
251 SmallVector<Type *, 4> ElementTypes;
253 // If there are no element types to map, then the type is itself. This is
254 // true for the anonymous {} struct, things like 'float', integers, etc.
255 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
258 // Remap all of the elements, keeping track of whether any of them change.
259 bool AnyChange = false;
260 ElementTypes.resize(Ty->getNumContainedTypes());
261 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
262 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
263 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
266 // If we found our type while recursively processing stuff, just use it.
267 Entry = &MappedTypes[Ty];
269 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
270 if (DTy->isOpaque()) {
271 auto *STy = cast<StructType>(Ty);
272 finishType(DTy, STy, ElementTypes);
278 // If all of the element types mapped directly over and the type is not
279 // a nomed struct, then the type is usable as-is.
280 if (!AnyChange && IsUniqued)
283 // Otherwise, rebuild a modified type.
284 switch (Ty->getTypeID()) {
286 llvm_unreachable("unknown derived type to remap");
287 case Type::ArrayTyID:
288 return *Entry = ArrayType::get(ElementTypes[0],
289 cast<ArrayType>(Ty)->getNumElements());
290 case Type::VectorTyID:
291 return *Entry = VectorType::get(ElementTypes[0],
292 cast<VectorType>(Ty)->getNumElements());
293 case Type::PointerTyID:
294 return *Entry = PointerType::get(ElementTypes[0],
295 cast<PointerType>(Ty)->getAddressSpace());
296 case Type::FunctionTyID:
297 return *Entry = FunctionType::get(ElementTypes[0],
298 makeArrayRef(ElementTypes).slice(1),
299 cast<FunctionType>(Ty)->isVarArg());
300 case Type::StructTyID: {
301 auto *STy = cast<StructType>(Ty);
302 bool IsPacked = STy->isPacked();
304 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
306 // If the type is opaque, we can just use it directly.
307 if (STy->isOpaque()) {
308 DstStructTypesSet.addOpaque(STy);
312 if (StructType *OldT =
313 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
315 return *Entry = OldT;
319 DstStructTypesSet.addNonOpaque(STy);
323 StructType *DTy = StructType::create(Ty->getContext());
324 finishType(DTy, STy, ElementTypes);
330 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
332 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
333 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
335 //===----------------------------------------------------------------------===//
336 // ModuleLinker implementation.
337 //===----------------------------------------------------------------------===//
342 /// Creates prototypes for functions that are lazily linked on the fly. This
343 /// speeds up linking for modules with many/ lazily linked functions of which
345 class GlobalValueMaterializer final : public ValueMaterializer {
349 GlobalValueMaterializer(IRLinker *ModLinker) : ModLinker(ModLinker) {}
350 Value *materializeDeclFor(Value *V) override;
351 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
354 class LocalValueMaterializer final : public ValueMaterializer {
358 LocalValueMaterializer(IRLinker *ModLinker) : ModLinker(ModLinker) {}
359 Value *materializeDeclFor(Value *V) override;
360 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
363 /// This is responsible for keeping track of the state used for moving data
364 /// from SrcM to DstM.
369 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
372 GlobalValueMaterializer GValMaterializer;
373 LocalValueMaterializer LValMaterializer;
375 /// Mapping of values from what they used to be in Src, to what they are now
376 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
377 /// due to the use of Value handles which the Linker doesn't actually need,
378 /// but this allows us to reuse the ValueMapper code.
379 ValueToValueMapTy ValueMap;
380 ValueToValueMapTy AliasValueMap;
382 DenseSet<GlobalValue *> ValuesToLink;
383 std::vector<GlobalValue *> Worklist;
385 void maybeAdd(GlobalValue *GV) {
386 if (ValuesToLink.insert(GV).second)
387 Worklist.push_back(GV);
390 /// Set to true when all global value body linking is complete (including
391 /// lazy linking). Used to prevent metadata linking from creating new
393 bool DoneLinkingBodies = false;
395 bool HasError = false;
397 /// Handles cloning of a global values from the source module into
398 /// the destination module, including setting the attributes and visibility.
399 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
401 /// Helper method for setting a message and returning an error code.
402 bool emitError(const Twine &Message) {
403 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
408 void emitWarning(const Twine &Message) {
409 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
412 /// Given a global in the source module, return the global in the
413 /// destination module that is being linked to, if any.
414 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
415 // If the source has no name it can't link. If it has local linkage,
416 // there is no name match-up going on.
417 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
420 // Otherwise see if we have a match in the destination module's symtab.
421 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
425 // If we found a global with the same name in the dest module, but it has
426 // internal linkage, we are really not doing any linkage here.
427 if (DGV->hasLocalLinkage())
430 // Otherwise, we do in fact link to the destination global.
434 void computeTypeMapping();
436 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
437 const GlobalVariable *SrcGV);
439 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
440 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
442 bool linkModuleFlagsMetadata();
444 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
445 bool linkFunctionBody(Function &Dst, Function &Src);
446 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
447 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
449 /// Functions that take care of cloning a specific global value type
450 /// into the destination module.
451 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
452 Function *copyFunctionProto(const Function *SF);
453 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
455 void linkNamedMDNodes();
458 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set, Module &SrcM,
459 ArrayRef<GlobalValue *> ValuesToLink,
460 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
461 : DstM(DstM), SrcM(SrcM), AddLazyFor(AddLazyFor), TypeMap(Set),
462 GValMaterializer(this), LValMaterializer(this) {
463 for (GlobalValue *GV : ValuesToLink)
468 Value *materializeDeclFor(Value *V, bool ForAlias);
469 void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias);
473 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
474 /// table. This is good for all clients except for us. Go through the trouble
475 /// to force this back.
476 static void forceRenaming(GlobalValue *GV, StringRef Name) {
477 // If the global doesn't force its name or if it already has the right name,
478 // there is nothing for us to do.
479 if (GV->hasLocalLinkage() || GV->getName() == Name)
482 Module *M = GV->getParent();
484 // If there is a conflict, rename the conflict.
485 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
486 GV->takeName(ConflictGV);
487 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
488 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
490 GV->setName(Name); // Force the name back
494 Value *GlobalValueMaterializer::materializeDeclFor(Value *V) {
495 return ModLinker->materializeDeclFor(V, false);
498 void GlobalValueMaterializer::materializeInitFor(GlobalValue *New,
500 ModLinker->materializeInitFor(New, Old, false);
503 Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
504 return ModLinker->materializeDeclFor(V, true);
507 void LocalValueMaterializer::materializeInitFor(GlobalValue *New,
509 ModLinker->materializeInitFor(New, Old, true);
512 Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) {
513 auto *SGV = dyn_cast<GlobalValue>(V);
517 return linkGlobalValueProto(SGV, ForAlias);
520 void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old,
522 // If we already created the body, just return.
523 if (auto *F = dyn_cast<Function>(New)) {
524 if (!F->isDeclaration())
526 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
527 if (V->hasInitializer())
530 auto *A = cast<GlobalAlias>(New);
535 if (ForAlias || shouldLink(New, *Old))
536 linkGlobalValueBody(*New, *Old);
539 /// Loop through the global variables in the src module and merge them into the
541 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
542 // No linking to be performed or linking from the source: simply create an
543 // identical version of the symbol over in the dest module... the
544 // initializer will be filled in later by LinkGlobalInits.
545 GlobalVariable *NewDGV =
546 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
547 SGVar->isConstant(), GlobalValue::ExternalLinkage,
548 /*init*/ nullptr, SGVar->getName(),
549 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
550 SGVar->getType()->getAddressSpace());
551 NewDGV->setAlignment(SGVar->getAlignment());
555 /// Link the function in the source module into the destination module if
556 /// needed, setting up mapping information.
557 Function *IRLinker::copyFunctionProto(const Function *SF) {
558 // If there is no linkage to be performed or we are linking from the source,
560 return Function::Create(TypeMap.get(SF->getFunctionType()),
561 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
564 /// Set up prototypes for any aliases that come over from the source module.
565 GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
566 // If there is no linkage to be performed or we're linking from the source,
568 auto *Ty = TypeMap.get(SGA->getValueType());
569 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
570 GlobalValue::ExternalLinkage, SGA->getName(),
574 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
575 bool ForDefinition) {
577 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
578 NewGV = copyGlobalVariableProto(SGVar);
579 } else if (auto *SF = dyn_cast<Function>(SGV)) {
580 NewGV = copyFunctionProto(SF);
583 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
585 NewGV = new GlobalVariable(
586 DstM, TypeMap.get(SGV->getType()->getElementType()),
587 /*isConstant*/ false, GlobalValue::ExternalLinkage,
588 /*init*/ nullptr, SGV->getName(),
589 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
590 SGV->getType()->getAddressSpace());
594 NewGV->setLinkage(SGV->getLinkage());
595 else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() ||
596 SGV->hasLinkOnceLinkage())
597 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
599 NewGV->copyAttributesFrom(SGV);
603 /// Loop over all of the linked values to compute type mappings. For example,
604 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
605 /// types 'Foo' but one got renamed when the module was loaded into the same
607 void IRLinker::computeTypeMapping() {
608 for (GlobalValue &SGV : SrcM.globals()) {
609 GlobalValue *DGV = getLinkedToGlobal(&SGV);
613 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
614 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
618 // Unify the element type of appending arrays.
619 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
620 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
621 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
624 for (GlobalValue &SGV : SrcM)
625 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
626 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
628 for (GlobalValue &SGV : SrcM.aliases())
629 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
630 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
632 // Incorporate types by name, scanning all the types in the source module.
633 // At this point, the destination module may have a type "%foo = { i32 }" for
634 // example. When the source module got loaded into the same LLVMContext, if
635 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
636 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
637 for (StructType *ST : Types) {
641 // Check to see if there is a dot in the name followed by a digit.
642 size_t DotPos = ST->getName().rfind('.');
643 if (DotPos == 0 || DotPos == StringRef::npos ||
644 ST->getName().back() == '.' ||
645 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
648 // Check to see if the destination module has a struct with the prefix name.
649 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
653 // Don't use it if this actually came from the source module. They're in
654 // the same LLVMContext after all. Also don't use it unless the type is
655 // actually used in the destination module. This can happen in situations
660 // %Z = type { %A } %B = type { %C.1 }
661 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
662 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
663 // %C = type { i8* } %B.3 = type { %C.1 }
665 // When we link Module B with Module A, the '%B' in Module B is
666 // used. However, that would then use '%C.1'. But when we process '%C.1',
667 // we prefer to take the '%C' version. So we are then left with both
668 // '%C.1' and '%C' being used for the same types. This leads to some
669 // variables using one type and some using the other.
670 if (TypeMap.DstStructTypesSet.hasType(DST))
671 TypeMap.addTypeMapping(DST, ST);
674 // Now that we have discovered all of the type equivalences, get a body for
675 // any 'opaque' types in the dest module that are now resolved.
676 TypeMap.linkDefinedTypeBodies();
679 static void getArrayElements(const Constant *C,
680 SmallVectorImpl<Constant *> &Dest) {
681 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
683 for (unsigned i = 0; i != NumElements; ++i)
684 Dest.push_back(C->getAggregateElement(i));
687 /// If there were any appending global variables, link them together now.
688 /// Return true on error.
689 Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
690 const GlobalVariable *SrcGV) {
691 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
694 StringRef Name = SrcGV->getName();
695 bool IsNewStructor = false;
696 bool IsOldStructor = false;
697 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
698 if (cast<StructType>(EltTy)->getNumElements() == 3)
699 IsNewStructor = true;
701 IsOldStructor = true;
704 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
706 auto &ST = *cast<StructType>(EltTy);
707 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
708 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
712 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
714 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
716 "Linking globals named '" + SrcGV->getName() +
717 "': can only link appending global with another appending global!");
721 // Check to see that they two arrays agree on type.
722 if (EltTy != DstTy->getElementType()) {
723 emitError("Appending variables with different element types!");
726 if (DstGV->isConstant() != SrcGV->isConstant()) {
727 emitError("Appending variables linked with different const'ness!");
731 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
733 "Appending variables with different alignment need to be linked!");
737 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
739 "Appending variables with different visibility need to be linked!");
743 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
745 "Appending variables with different unnamed_addr need to be linked!");
749 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
751 "Appending variables with different section name need to be linked!");
756 SmallVector<Constant *, 16> DstElements;
758 getArrayElements(DstGV->getInitializer(), DstElements);
760 SmallVector<Constant *, 16> SrcElements;
761 getArrayElements(SrcGV->getInitializer(), SrcElements);
765 std::remove_if(SrcElements.begin(), SrcElements.end(),
766 [this](Constant *E) {
767 auto *Key = dyn_cast<GlobalValue>(
768 E->getAggregateElement(2)->stripPointerCasts());
771 GlobalValue *DGV = getLinkedToGlobal(Key);
772 return !shouldLink(DGV, *Key);
775 uint64_t NewSize = DstElements.size() + SrcElements.size();
776 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
778 // Create the new global variable.
779 GlobalVariable *NG = new GlobalVariable(
780 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
781 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
782 SrcGV->getType()->getAddressSpace());
784 NG->copyAttributesFrom(SrcGV);
785 forceRenaming(NG, SrcGV->getName());
787 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
790 ValueMap[SrcGV] = Ret;
792 for (auto *V : SrcElements) {
795 auto *S = cast<ConstantStruct>(V);
796 auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
797 &TypeMap, &GValMaterializer);
798 auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
799 &TypeMap, &GValMaterializer);
800 Value *Null = Constant::getNullValue(VoidPtrTy);
802 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
804 NewV = MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap,
807 DstElements.push_back(NewV);
810 NG->setInitializer(ConstantArray::get(NewType, DstElements));
812 // Replace any uses of the two global variables with uses of the new
815 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
816 DstGV->eraseFromParent();
822 static bool useExistingDest(GlobalValue &SGV, GlobalValue *DGV,
827 if (SGV.isDeclaration())
830 if (DGV->isDeclarationForLinker() && !SGV.isDeclarationForLinker())
839 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
840 if (ValuesToLink.count(&SGV))
843 if (SGV.hasLocalLinkage())
846 if (DGV && !DGV->isDeclaration())
849 if (SGV.hasAvailableExternallyLinkage())
852 if (DoneLinkingBodies)
855 AddLazyFor(SGV, [this](GlobalValue &GV) { maybeAdd(&GV); });
856 return ValuesToLink.count(&SGV);
859 Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
860 GlobalValue *DGV = getLinkedToGlobal(SGV);
862 bool ShouldLink = shouldLink(DGV, *SGV);
864 // just missing from map
866 auto I = ValueMap.find(SGV);
867 if (I != ValueMap.end())
868 return cast<Constant>(I->second);
870 I = AliasValueMap.find(SGV);
871 if (I != AliasValueMap.end())
872 return cast<Constant>(I->second);
876 if (ShouldLink || !ForAlias)
877 DGV = getLinkedToGlobal(SGV);
879 // Handle the ultra special appending linkage case first.
880 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
881 if (SGV->hasAppendingLinkage())
882 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
883 cast<GlobalVariable>(SGV));
886 if (useExistingDest(*SGV, DGV, ShouldLink)) {
889 // If we are done linking global value bodies (i.e. we are performing
890 // metadata linking), don't link in the global value due to this
891 // reference, simply map it to null.
892 if (DoneLinkingBodies)
895 NewGV = copyGlobalValueProto(SGV, ShouldLink);
897 forceRenaming(NewGV, SGV->getName());
899 if (ShouldLink || ForAlias) {
900 if (const Comdat *SC = SGV->getComdat()) {
901 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
902 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
903 DC->setSelectionKind(SC->getSelectionKind());
909 if (!ShouldLink && ForAlias)
910 NewGV->setLinkage(GlobalValue::InternalLinkage);
914 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
916 if (DGV && NewGV != DGV) {
917 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
918 DGV->eraseFromParent();
924 /// Update the initializers in the Dest module now that all globals that may be
925 /// referenced are in Dest.
926 void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
927 // Figure out what the initializer looks like in the dest module.
928 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
929 RF_MoveDistinctMDs, &TypeMap, &GValMaterializer));
932 /// Copy the source function over into the dest function and fix up references
933 /// to values. At this point we know that Dest is an external function, and
935 bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
936 assert(Dst.isDeclaration() && !Src.isDeclaration());
938 // Materialize if needed.
939 if (std::error_code EC = Src.materialize())
940 return emitError(EC.message());
942 // Link in the prefix data.
943 if (Src.hasPrefixData())
944 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
945 RF_MoveDistinctMDs, &TypeMap,
948 // Link in the prologue data.
949 if (Src.hasPrologueData())
950 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
951 RF_MoveDistinctMDs, &TypeMap,
954 // Link in the personality function.
955 if (Src.hasPersonalityFn())
956 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
957 RF_MoveDistinctMDs, &TypeMap,
960 // Go through and convert function arguments over, remembering the mapping.
961 Function::arg_iterator DI = Dst.arg_begin();
962 for (Argument &Arg : Src.args()) {
963 DI->setName(Arg.getName()); // Copy the name over.
965 // Add a mapping to our mapping.
966 ValueMap[&Arg] = &*DI;
970 // Copy over the metadata attachments.
971 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
972 Src.getAllMetadata(MDs);
973 for (const auto &I : MDs)
974 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
975 &TypeMap, &GValMaterializer));
977 // Splice the body of the source function into the dest function.
978 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
980 // At this point, all of the instructions and values of the function are now
981 // copied over. The only problem is that they are still referencing values in
982 // the Source function as operands. Loop through all of the operands of the
983 // functions and patch them up to point to the local versions.
984 for (BasicBlock &BB : Dst)
985 for (Instruction &I : BB)
986 RemapInstruction(&I, ValueMap,
987 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
990 // There is no need to map the arguments anymore.
991 for (Argument &Arg : Src.args())
992 ValueMap.erase(&Arg);
998 void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
999 Constant *Aliasee = Src.getAliasee();
1000 Constant *Val = MapValue(Aliasee, AliasValueMap, RF_MoveDistinctMDs, &TypeMap,
1002 Dst.setAliasee(Val);
1005 bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1006 if (auto *F = dyn_cast<Function>(&Src))
1007 return linkFunctionBody(cast<Function>(Dst), *F);
1008 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1009 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1012 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1016 /// Insert all of the named MDNodes in Src into the Dest module.
1017 void IRLinker::linkNamedMDNodes() {
1018 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1019 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1020 // Don't link module flags here. Do them separately.
1021 if (&NMD == SrcModFlags)
1023 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1024 // Add Src elements into Dest node.
1025 for (const MDNode *op : NMD.operands())
1026 DestNMD->addOperand(MapMetadata(
1027 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1028 &TypeMap, &GValMaterializer));
1032 /// Merge the linker flags in Src into the Dest module.
1033 bool IRLinker::linkModuleFlagsMetadata() {
1034 // If the source module has no module flags, we are done.
1035 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1039 // If the destination module doesn't have module flags yet, then just copy
1040 // over the source module's flags.
1041 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1042 if (DstModFlags->getNumOperands() == 0) {
1043 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1044 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1049 // First build a map of the existing module flags and requirements.
1050 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1051 SmallSetVector<MDNode *, 16> Requirements;
1052 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1053 MDNode *Op = DstModFlags->getOperand(I);
1054 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1055 MDString *ID = cast<MDString>(Op->getOperand(1));
1057 if (Behavior->getZExtValue() == Module::Require) {
1058 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1060 Flags[ID] = std::make_pair(Op, I);
1064 // Merge in the flags from the source module, and also collect its set of
1066 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1067 MDNode *SrcOp = SrcModFlags->getOperand(I);
1068 ConstantInt *SrcBehavior =
1069 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1070 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1073 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1074 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1076 // If this is a requirement, add it and continue.
1077 if (SrcBehaviorValue == Module::Require) {
1078 // If the destination module does not already have this requirement, add
1080 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1081 DstModFlags->addOperand(SrcOp);
1086 // If there is no existing flag with this ID, just add it.
1088 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1089 DstModFlags->addOperand(SrcOp);
1093 // Otherwise, perform a merge.
1094 ConstantInt *DstBehavior =
1095 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1096 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1098 // If either flag has override behavior, handle it first.
1099 if (DstBehaviorValue == Module::Override) {
1100 // Diagnose inconsistent flags which both have override behavior.
1101 if (SrcBehaviorValue == Module::Override &&
1102 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1103 emitError("linking module flags '" + ID->getString() +
1104 "': IDs have conflicting override values");
1107 } else if (SrcBehaviorValue == Module::Override) {
1108 // Update the destination flag to that of the source.
1109 DstModFlags->setOperand(DstIndex, SrcOp);
1110 Flags[ID].first = SrcOp;
1114 // Diagnose inconsistent merge behavior types.
1115 if (SrcBehaviorValue != DstBehaviorValue) {
1116 emitError("linking module flags '" + ID->getString() +
1117 "': IDs have conflicting behaviors");
1121 auto replaceDstValue = [&](MDNode *New) {
1122 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1123 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1124 DstModFlags->setOperand(DstIndex, Flag);
1125 Flags[ID].first = Flag;
1128 // Perform the merge for standard behavior types.
1129 switch (SrcBehaviorValue) {
1130 case Module::Require:
1131 case Module::Override:
1132 llvm_unreachable("not possible");
1133 case Module::Error: {
1134 // Emit an error if the values differ.
1135 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1136 emitError("linking module flags '" + ID->getString() +
1137 "': IDs have conflicting values");
1141 case Module::Warning: {
1142 // Emit a warning if the values differ.
1143 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1144 emitWarning("linking module flags '" + ID->getString() +
1145 "': IDs have conflicting values");
1149 case Module::Append: {
1150 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1151 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1152 SmallVector<Metadata *, 8> MDs;
1153 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1154 MDs.append(DstValue->op_begin(), DstValue->op_end());
1155 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1157 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1160 case Module::AppendUnique: {
1161 SmallSetVector<Metadata *, 16> Elts;
1162 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1163 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1164 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1165 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1167 replaceDstValue(MDNode::get(DstM.getContext(),
1168 makeArrayRef(Elts.begin(), Elts.end())));
1174 // Check all of the requirements.
1175 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1176 MDNode *Requirement = Requirements[I];
1177 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1178 Metadata *ReqValue = Requirement->getOperand(1);
1180 MDNode *Op = Flags[Flag].first;
1181 if (!Op || Op->getOperand(2) != ReqValue) {
1182 emitError("linking module flags '" + Flag->getString() +
1183 "': does not have the required value");
1191 // This function returns true if the triples match.
1192 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1193 // If vendor is apple, ignore the version number.
1194 if (T0.getVendor() == Triple::Apple)
1195 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1196 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1201 // This function returns the merged triple.
1202 static std::string mergeTriples(const Triple &SrcTriple,
1203 const Triple &DstTriple) {
1204 // If vendor is apple, pick the triple with the larger version number.
1205 if (SrcTriple.getVendor() == Triple::Apple)
1206 if (DstTriple.isOSVersionLT(SrcTriple))
1207 return SrcTriple.str();
1209 return DstTriple.str();
1212 bool IRLinker::run() {
1213 // Inherit the target data from the source module if the destination module
1214 // doesn't have one already.
1215 if (DstM.getDataLayout().isDefault())
1216 DstM.setDataLayout(SrcM.getDataLayout());
1218 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1219 emitWarning("Linking two modules of different data layouts: '" +
1220 SrcM.getModuleIdentifier() + "' is '" +
1221 SrcM.getDataLayoutStr() + "' whereas '" +
1222 DstM.getModuleIdentifier() + "' is '" +
1223 DstM.getDataLayoutStr() + "'\n");
1226 // Copy the target triple from the source to dest if the dest's is empty.
1227 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1228 DstM.setTargetTriple(SrcM.getTargetTriple());
1230 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1232 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1233 emitWarning("Linking two modules of different target triples: " +
1234 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1235 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1236 DstM.getTargetTriple() + "'\n");
1238 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1240 // Append the module inline asm string.
1241 if (!SrcM.getModuleInlineAsm().empty()) {
1242 if (DstM.getModuleInlineAsm().empty())
1243 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1245 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1246 SrcM.getModuleInlineAsm());
1249 // Loop over all of the linked values to compute type mappings.
1250 computeTypeMapping();
1252 std::reverse(Worklist.begin(), Worklist.end());
1253 while (!Worklist.empty()) {
1254 GlobalValue *GV = Worklist.back();
1255 Worklist.pop_back();
1258 if (ValueMap.find(GV) != ValueMap.end() ||
1259 AliasValueMap.find(GV) != AliasValueMap.end())
1262 assert(!GV->isDeclaration());
1263 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &GValMaterializer);
1268 // Note that we are done linking global value bodies. This prevents
1269 // metadata linking from creating new references.
1270 DoneLinkingBodies = true;
1272 // Remap all of the named MDNodes in Src into the DstM module. We do this
1273 // after linking GlobalValues so that MDNodes that reference GlobalValues
1274 // are properly remapped.
1277 // Merge the module flags into the DstM module.
1278 if (linkModuleFlagsMetadata())
1284 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1285 : ETypes(E), IsPacked(P) {}
1287 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1288 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1290 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1291 if (IsPacked != That.IsPacked)
1293 if (ETypes != That.ETypes)
1298 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1299 return !this->operator==(That);
1302 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1303 return DenseMapInfo<StructType *>::getEmptyKey();
1306 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1307 return DenseMapInfo<StructType *>::getTombstoneKey();
1310 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1311 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1315 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1316 return getHashValue(KeyTy(ST));
1319 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1320 const StructType *RHS) {
1321 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1323 return LHS == KeyTy(RHS);
1326 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1327 const StructType *RHS) {
1328 if (RHS == getEmptyKey())
1329 return LHS == getEmptyKey();
1331 if (RHS == getTombstoneKey())
1332 return LHS == getTombstoneKey();
1334 return KeyTy(LHS) == KeyTy(RHS);
1337 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1338 assert(!Ty->isOpaque());
1339 NonOpaqueStructTypes.insert(Ty);
1342 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1343 assert(!Ty->isOpaque());
1344 NonOpaqueStructTypes.insert(Ty);
1345 bool Removed = OpaqueStructTypes.erase(Ty);
1350 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1351 assert(Ty->isOpaque());
1352 OpaqueStructTypes.insert(Ty);
1356 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1358 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1359 auto I = NonOpaqueStructTypes.find_as(Key);
1360 if (I == NonOpaqueStructTypes.end())
1365 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1367 return OpaqueStructTypes.count(Ty);
1368 auto I = NonOpaqueStructTypes.find(Ty);
1369 if (I == NonOpaqueStructTypes.end())
1374 IRMover::IRMover(Module &M) : Composite(M) {
1375 TypeFinder StructTypes;
1376 StructTypes.run(M, true);
1377 for (StructType *Ty : StructTypes) {
1379 IdentifiedStructTypes.addOpaque(Ty);
1381 IdentifiedStructTypes.addNonOpaque(Ty);
1386 Module &Src, ArrayRef<GlobalValue *> ValuesToLink,
1387 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
1388 IRLinker TheLinker(Composite, IdentifiedStructTypes, Src, ValuesToLink,
1390 bool RetCode = TheLinker.run();
1391 Composite.dropTriviallyDeadConstantArrays();