[NFC][RISCV] Remove CFIIndex argument from allocateStack (#117871)
[llvm-project.git] / llvm / lib / Linker / IRMover.cpp
bloba0c3f2c5b0baf60bcf69a6c9d6282e51d4cd0c0a
1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Linker/IRMover.h"
10 #include "LinkDiagnosticInfo.h"
11 #include "llvm/ADT/ScopeExit.h"
12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DebugInfoMetadata.h"
18 #include "llvm/IR/DiagnosticPrinter.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GVMaterializer.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PseudoProbe.h"
27 #include "llvm/IR/TypeFinder.h"
28 #include "llvm/Object/ModuleSymbolTable.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/TargetParser/Triple.h"
32 #include "llvm/Transforms/Utils/ValueMapper.h"
33 #include <optional>
34 #include <utility>
35 using namespace llvm;
37 /// Most of the errors produced by this module are inconvertible StringErrors.
38 /// This convenience function lets us return one of those more easily.
39 static Error stringErr(const Twine &T) {
40 return make_error<StringError>(T, inconvertibleErrorCode());
43 //===----------------------------------------------------------------------===//
44 // TypeMap implementation.
45 //===----------------------------------------------------------------------===//
47 namespace {
48 class TypeMapTy : public ValueMapTypeRemapper {
49 /// This is a mapping from a source type to a destination type to use.
50 DenseMap<Type *, Type *> MappedTypes;
52 /// When checking to see if two subgraphs are isomorphic, we speculatively
53 /// add types to MappedTypes, but keep track of them here in case we need to
54 /// roll back.
55 SmallVector<Type *, 16> SpeculativeTypes;
57 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
59 /// This is a list of non-opaque structs in the source module that are mapped
60 /// to an opaque struct in the destination module.
61 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
63 /// This is the set of opaque types in the destination modules who are
64 /// getting a body from the source module.
65 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
67 public:
68 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
69 : DstStructTypesSet(DstStructTypesSet) {}
71 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
72 /// Indicate that the specified type in the destination module is conceptually
73 /// equivalent to the specified type in the source module.
74 void addTypeMapping(Type *DstTy, Type *SrcTy);
76 /// Produce a body for an opaque type in the dest module from a type
77 /// definition in the source module.
78 Error linkDefinedTypeBodies();
80 /// Return the mapped type to use for the specified input type from the
81 /// source module.
82 Type *get(Type *SrcTy);
83 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
85 FunctionType *get(FunctionType *T) {
86 return cast<FunctionType>(get((Type *)T));
89 private:
90 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 assert(SpeculativeTypes.empty());
98 assert(SpeculativeDstOpaqueTypes.empty());
100 // Check to see if these types are recursively isomorphic and establish a
101 // mapping between them if so.
102 if (!areTypesIsomorphic(DstTy, SrcTy)) {
103 // Oops, they aren't isomorphic. Just discard this request by rolling out
104 // any speculative mappings we've established.
105 for (Type *Ty : SpeculativeTypes)
106 MappedTypes.erase(Ty);
108 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
109 SpeculativeDstOpaqueTypes.size());
110 for (StructType *Ty : SpeculativeDstOpaqueTypes)
111 DstResolvedOpaqueTypes.erase(Ty);
112 } else {
113 // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
114 // and all its descendants to lower amount of renaming in LLVM context
115 // Renaming occurs because we load all source modules to the same context
116 // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
117 // As a result we may get several different types in the destination
118 // module, which are in fact the same.
119 for (Type *Ty : SpeculativeTypes)
120 if (auto *STy = dyn_cast<StructType>(Ty))
121 if (STy->hasName())
122 STy->setName("");
124 SpeculativeTypes.clear();
125 SpeculativeDstOpaqueTypes.clear();
128 /// Recursively walk this pair of types, returning true if they are isomorphic,
129 /// false if they are not.
130 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
131 // Two types with differing kinds are clearly not isomorphic.
132 if (DstTy->getTypeID() != SrcTy->getTypeID())
133 return false;
135 // If we have an entry in the MappedTypes table, then we have our answer.
136 Type *&Entry = MappedTypes[SrcTy];
137 if (Entry)
138 return Entry == DstTy;
140 // Two identical types are clearly isomorphic. Remember this
141 // non-speculatively.
142 if (DstTy == SrcTy) {
143 Entry = DstTy;
144 return true;
147 // Okay, we have two types with identical kinds that we haven't seen before.
149 // If this is an opaque struct type, special case it.
150 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
151 // Mapping an opaque type to any struct, just keep the dest struct.
152 if (SSTy->isOpaque()) {
153 Entry = DstTy;
154 SpeculativeTypes.push_back(SrcTy);
155 return true;
158 // Mapping a non-opaque source type to an opaque dest. If this is the first
159 // type that we're mapping onto this destination type then we succeed. Keep
160 // the dest, but fill it in later. If this is the second (different) type
161 // that we're trying to map onto the same opaque type then we fail.
162 if (cast<StructType>(DstTy)->isOpaque()) {
163 // We can only map one source type onto the opaque destination type.
164 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
165 return false;
166 SrcDefinitionsToResolve.push_back(SSTy);
167 SpeculativeTypes.push_back(SrcTy);
168 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
169 Entry = DstTy;
170 return true;
174 // If the number of subtypes disagree between the two types, then we fail.
175 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
176 return false;
178 // Fail if any of the extra properties (e.g. array size) of the type disagree.
179 if (isa<IntegerType>(DstTy))
180 return false; // bitwidth disagrees.
181 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
182 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
183 return false;
184 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
185 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
186 return false;
187 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
188 StructType *SSTy = cast<StructType>(SrcTy);
189 if (DSTy->isLiteral() != SSTy->isLiteral() ||
190 DSTy->isPacked() != SSTy->isPacked())
191 return false;
192 } else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
193 if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
194 return false;
195 } else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
196 if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
197 return false;
200 // Otherwise, we speculate that these two types will line up and recursively
201 // check the subelements.
202 Entry = DstTy;
203 SpeculativeTypes.push_back(SrcTy);
205 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
206 if (!areTypesIsomorphic(DstTy->getContainedType(I),
207 SrcTy->getContainedType(I)))
208 return false;
210 // If everything seems to have lined up, then everything is great.
211 return true;
214 Error TypeMapTy::linkDefinedTypeBodies() {
215 SmallVector<Type *, 16> Elements;
216 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
217 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
218 assert(DstSTy->isOpaque());
220 // Map the body of the source type over to a new body for the dest type.
221 Elements.resize(SrcSTy->getNumElements());
222 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
223 Elements[I] = get(SrcSTy->getElementType(I));
225 if (auto E = DstSTy->setBodyOrError(Elements, SrcSTy->isPacked()))
226 return E;
227 DstStructTypesSet.switchToNonOpaque(DstSTy);
229 SrcDefinitionsToResolve.clear();
230 DstResolvedOpaqueTypes.clear();
231 return Error::success();
234 Type *TypeMapTy::get(Type *Ty) {
235 SmallPtrSet<StructType *, 8> Visited;
236 return get(Ty, Visited);
239 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
240 // If we already have an entry for this type, return it.
241 Type **Entry = &MappedTypes[Ty];
242 if (*Entry)
243 return *Entry;
245 // These are types that LLVM itself will unique.
246 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
248 if (!IsUniqued) {
249 #ifndef NDEBUG
250 for (auto &Pair : MappedTypes) {
251 assert(!(Pair.first != Ty && Pair.second == Ty) &&
252 "mapping to a source type");
254 #endif
256 if (!Visited.insert(cast<StructType>(Ty)).second) {
257 StructType *DTy = StructType::create(Ty->getContext());
258 return *Entry = DTy;
262 // If this is not a recursive type, then just map all of the elements and
263 // then rebuild the type from inside out.
264 SmallVector<Type *, 4> ElementTypes;
266 // If there are no element types to map, then the type is itself. This is
267 // true for the anonymous {} struct, things like 'float', integers, etc.
268 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
269 return *Entry = Ty;
271 // Remap all of the elements, keeping track of whether any of them change.
272 bool AnyChange = false;
273 ElementTypes.resize(Ty->getNumContainedTypes());
274 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
275 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
276 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
279 // Refresh Entry after recursively processing stuff.
280 Entry = &MappedTypes[Ty];
281 assert(!*Entry && "Recursive type!");
283 // If all of the element types mapped directly over and the type is not
284 // a named struct, then the type is usable as-is.
285 if (!AnyChange && IsUniqued)
286 return *Entry = Ty;
288 // Otherwise, rebuild a modified type.
289 switch (Ty->getTypeID()) {
290 default:
291 llvm_unreachable("unknown derived type to remap");
292 case Type::ArrayTyID:
293 return *Entry = ArrayType::get(ElementTypes[0],
294 cast<ArrayType>(Ty)->getNumElements());
295 case Type::ScalableVectorTyID:
296 case Type::FixedVectorTyID:
297 return *Entry = VectorType::get(ElementTypes[0],
298 cast<VectorType>(Ty)->getElementCount());
299 case Type::PointerTyID:
300 return *Entry = PointerType::get(ElementTypes[0],
301 cast<PointerType>(Ty)->getAddressSpace());
302 case Type::FunctionTyID:
303 return *Entry = FunctionType::get(ElementTypes[0],
304 ArrayRef(ElementTypes).slice(1),
305 cast<FunctionType>(Ty)->isVarArg());
306 case Type::StructTyID: {
307 auto *STy = cast<StructType>(Ty);
308 bool IsPacked = STy->isPacked();
309 if (IsUniqued)
310 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
312 // If the type is opaque, we can just use it directly.
313 if (STy->isOpaque()) {
314 DstStructTypesSet.addOpaque(STy);
315 return *Entry = Ty;
318 if (StructType *OldT =
319 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
320 STy->setName("");
321 return *Entry = OldT;
324 if (!AnyChange) {
325 DstStructTypesSet.addNonOpaque(STy);
326 return *Entry = Ty;
329 StructType *DTy =
330 StructType::create(Ty->getContext(), ElementTypes, "", STy->isPacked());
332 // Steal STy's name.
333 if (STy->hasName()) {
334 SmallString<16> TmpName = STy->getName();
335 STy->setName("");
336 DTy->setName(TmpName);
339 DstStructTypesSet.addNonOpaque(DTy);
340 return *Entry = DTy;
345 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
346 const Twine &Msg)
347 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
348 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
350 //===----------------------------------------------------------------------===//
351 // IRLinker implementation.
352 //===----------------------------------------------------------------------===//
354 namespace {
355 class IRLinker;
357 /// Creates prototypes for functions that are lazily linked on the fly. This
358 /// speeds up linking for modules with many/ lazily linked functions of which
359 /// few get used.
360 class GlobalValueMaterializer final : public ValueMaterializer {
361 IRLinker &TheIRLinker;
363 public:
364 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
365 Value *materialize(Value *V) override;
368 class LocalValueMaterializer final : public ValueMaterializer {
369 IRLinker &TheIRLinker;
371 public:
372 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
373 Value *materialize(Value *V) override;
376 /// Type of the Metadata map in \a ValueToValueMapTy.
377 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
379 /// This is responsible for keeping track of the state used for moving data
380 /// from SrcM to DstM.
381 class IRLinker {
382 Module &DstM;
383 std::unique_ptr<Module> SrcM;
385 /// See IRMover::move().
386 IRMover::LazyCallback AddLazyFor;
388 TypeMapTy TypeMap;
389 GlobalValueMaterializer GValMaterializer;
390 LocalValueMaterializer LValMaterializer;
392 /// A metadata map that's shared between IRLinker instances.
393 MDMapT &SharedMDs;
395 /// Mapping of values from what they used to be in Src, to what they are now
396 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
397 /// due to the use of Value handles which the Linker doesn't actually need,
398 /// but this allows us to reuse the ValueMapper code.
399 ValueToValueMapTy ValueMap;
400 ValueToValueMapTy IndirectSymbolValueMap;
402 DenseSet<GlobalValue *> ValuesToLink;
403 std::vector<GlobalValue *> Worklist;
404 std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
406 /// Set of globals with eagerly copied metadata that may require remapping.
407 /// This remapping is performed after metadata linking.
408 DenseSet<GlobalObject *> UnmappedMetadata;
410 void maybeAdd(GlobalValue *GV) {
411 if (ValuesToLink.insert(GV).second)
412 Worklist.push_back(GV);
415 /// Whether we are importing globals for ThinLTO, as opposed to linking the
416 /// source module. If this flag is set, it means that we can rely on some
417 /// other object file to define any non-GlobalValue entities defined by the
418 /// source module. This currently causes us to not link retained types in
419 /// debug info metadata and module inline asm.
420 bool IsPerformingImport;
422 /// Set to true when all global value body linking is complete (including
423 /// lazy linking). Used to prevent metadata linking from creating new
424 /// references.
425 bool DoneLinkingBodies = false;
427 /// The Error encountered during materialization. We use an Optional here to
428 /// avoid needing to manage an unconsumed success value.
429 std::optional<Error> FoundError;
430 void setError(Error E) {
431 if (E)
432 FoundError = std::move(E);
435 /// Entry point for mapping values and alternate context for mapping aliases.
436 ValueMapper Mapper;
437 unsigned IndirectSymbolMCID;
439 /// Handles cloning of a global values from the source module into
440 /// the destination module, including setting the attributes and visibility.
441 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
443 void emitWarning(const Twine &Message) {
444 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
447 /// Given a global in the source module, return the global in the
448 /// destination module that is being linked to, if any.
449 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
450 // If the source has no name it can't link. If it has local linkage,
451 // there is no name match-up going on.
452 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
453 return nullptr;
455 // Otherwise see if we have a match in the destination module's symtab.
456 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
457 if (!DGV)
458 return nullptr;
460 // If we found a global with the same name in the dest module, but it has
461 // internal linkage, we are really not doing any linkage here.
462 if (DGV->hasLocalLinkage())
463 return nullptr;
465 // If we found an intrinsic declaration with mismatching prototypes, we
466 // probably had a nameclash. Don't use that version.
467 if (auto *FDGV = dyn_cast<Function>(DGV))
468 if (FDGV->isIntrinsic())
469 if (const auto *FSrcGV = dyn_cast<Function>(SrcGV))
470 if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
471 return nullptr;
473 // Otherwise, we do in fact link to the destination global.
474 return DGV;
477 void computeTypeMapping();
479 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
480 const GlobalVariable *SrcGV);
482 /// Given the GlobaValue \p SGV in the source module, and the matching
483 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
484 /// into the destination module.
486 /// Note this code may call the client-provided \p AddLazyFor.
487 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
488 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
489 bool ForIndirectSymbol);
491 Error linkModuleFlagsMetadata();
493 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
494 Error linkFunctionBody(Function &Dst, Function &Src);
495 void linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src);
496 void linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src);
497 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
499 /// Replace all types in the source AttributeList with the
500 /// corresponding destination type.
501 AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
503 /// Functions that take care of cloning a specific global value type
504 /// into the destination module.
505 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
506 Function *copyFunctionProto(const Function *SF);
507 GlobalValue *copyIndirectSymbolProto(const GlobalValue *SGV);
509 /// Perform "replace all uses with" operations. These work items need to be
510 /// performed as part of materialization, but we postpone them to happen after
511 /// materialization is done. The materializer called by ValueMapper is not
512 /// expected to delete constants, as ValueMapper is holding pointers to some
513 /// of them, but constant destruction may be indirectly triggered by RAUW.
514 /// Hence, the need to move this out of the materialization call chain.
515 void flushRAUWWorklist();
517 /// When importing for ThinLTO, prevent importing of types listed on
518 /// the DICompileUnit that we don't need a copy of in the importing
519 /// module.
520 void prepareCompileUnitsForImport();
521 void linkNamedMDNodes();
523 /// Update attributes while linking.
524 void updateAttributes(GlobalValue &GV);
526 public:
527 IRLinker(Module &DstM, MDMapT &SharedMDs,
528 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
529 ArrayRef<GlobalValue *> ValuesToLink,
530 IRMover::LazyCallback AddLazyFor, bool IsPerformingImport)
531 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
532 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
533 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
534 Mapper(ValueMap, RF_ReuseAndMutateDistinctMDs | RF_IgnoreMissingLocals,
535 &TypeMap, &GValMaterializer),
536 IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
537 IndirectSymbolValueMap, &LValMaterializer)) {
538 ValueMap.getMDMap() = std::move(SharedMDs);
539 for (GlobalValue *GV : ValuesToLink)
540 maybeAdd(GV);
541 if (IsPerformingImport)
542 prepareCompileUnitsForImport();
544 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
546 Error run();
547 Value *materialize(Value *V, bool ForIndirectSymbol);
551 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
552 /// table. This is good for all clients except for us. Go through the trouble
553 /// to force this back.
554 static void forceRenaming(GlobalValue *GV, StringRef Name) {
555 // If the global doesn't force its name or if it already has the right name,
556 // there is nothing for us to do.
557 if (GV->hasLocalLinkage() || GV->getName() == Name)
558 return;
560 Module *M = GV->getParent();
562 // If there is a conflict, rename the conflict.
563 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
564 GV->takeName(ConflictGV);
565 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
566 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
567 } else {
568 GV->setName(Name); // Force the name back
572 Value *GlobalValueMaterializer::materialize(Value *SGV) {
573 return TheIRLinker.materialize(SGV, false);
576 Value *LocalValueMaterializer::materialize(Value *SGV) {
577 return TheIRLinker.materialize(SGV, true);
580 Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
581 auto *SGV = dyn_cast<GlobalValue>(V);
582 if (!SGV)
583 return nullptr;
585 // If SGV is from dest, it was already materialized when dest was loaded.
586 if (SGV->getParent() == &DstM)
587 return nullptr;
589 // When linking a global from other modules than source & dest, skip
590 // materializing it because it would be mapped later when its containing
591 // module is linked. Linking it now would potentially pull in many types that
592 // may not be mapped properly.
593 if (SGV->getParent() != SrcM.get())
594 return nullptr;
596 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
597 if (!NewProto) {
598 setError(NewProto.takeError());
599 return nullptr;
601 if (!*NewProto)
602 return nullptr;
604 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
605 if (!New)
606 return *NewProto;
608 // If we already created the body, just return.
609 if (auto *F = dyn_cast<Function>(New)) {
610 if (!F->isDeclaration())
611 return New;
612 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
613 if (V->hasInitializer() || V->hasAppendingLinkage())
614 return New;
615 } else if (auto *GA = dyn_cast<GlobalAlias>(New)) {
616 if (GA->getAliasee())
617 return New;
618 } else if (auto *GI = dyn_cast<GlobalIFunc>(New)) {
619 if (GI->getResolver())
620 return New;
621 } else {
622 llvm_unreachable("Invalid GlobalValue type");
625 // If the global is being linked for an indirect symbol, it may have already
626 // been scheduled to satisfy a regular symbol. Similarly, a global being linked
627 // for a regular symbol may have already been scheduled for an indirect
628 // symbol. Check for these cases by looking in the other value map and
629 // confirming the same value has been scheduled. If there is an entry in the
630 // ValueMap but the value is different, it means that the value already had a
631 // definition in the destination module (linkonce for instance), but we need a
632 // new definition for the indirect symbol ("New" will be different).
633 if ((ForIndirectSymbol && ValueMap.lookup(SGV) == New) ||
634 (!ForIndirectSymbol && IndirectSymbolValueMap.lookup(SGV) == New))
635 return New;
637 if (ForIndirectSymbol || shouldLink(New, *SGV))
638 setError(linkGlobalValueBody(*New, *SGV));
640 updateAttributes(*New);
641 return New;
644 /// Loop through the global variables in the src module and merge them into the
645 /// dest module.
646 GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
647 // No linking to be performed or linking from the source: simply create an
648 // identical version of the symbol over in the dest module... the
649 // initializer will be filled in later by LinkGlobalInits.
650 GlobalVariable *NewDGV =
651 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
652 SGVar->isConstant(), GlobalValue::ExternalLinkage,
653 /*init*/ nullptr, SGVar->getName(),
654 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
655 SGVar->getAddressSpace());
656 NewDGV->setAlignment(SGVar->getAlign());
657 NewDGV->copyAttributesFrom(SGVar);
658 return NewDGV;
661 AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
662 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
663 for (int AttrIdx = Attribute::FirstTypeAttr;
664 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
665 Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
666 if (Attrs.hasAttributeAtIndex(i, TypedAttr)) {
667 if (Type *Ty =
668 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
669 Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
670 TypeMap.get(Ty));
671 break;
676 return Attrs;
679 /// Link the function in the source module into the destination module if
680 /// needed, setting up mapping information.
681 Function *IRLinker::copyFunctionProto(const Function *SF) {
682 // If there is no linkage to be performed or we are linking from the source,
683 // bring SF over.
684 auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
685 GlobalValue::ExternalLinkage,
686 SF->getAddressSpace(), SF->getName(), &DstM);
687 F->copyAttributesFrom(SF);
688 F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
689 F->IsNewDbgInfoFormat = SF->IsNewDbgInfoFormat;
690 return F;
693 /// Set up prototypes for any indirect symbols that come over from the source
694 /// module.
695 GlobalValue *IRLinker::copyIndirectSymbolProto(const GlobalValue *SGV) {
696 // If there is no linkage to be performed or we're linking from the source,
697 // bring over SGA.
698 auto *Ty = TypeMap.get(SGV->getValueType());
700 if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
701 auto *DGA = GlobalAlias::create(Ty, SGV->getAddressSpace(),
702 GlobalValue::ExternalLinkage,
703 SGV->getName(), &DstM);
704 DGA->copyAttributesFrom(GA);
705 return DGA;
708 if (auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
709 auto *DGI = GlobalIFunc::create(Ty, SGV->getAddressSpace(),
710 GlobalValue::ExternalLinkage,
711 SGV->getName(), nullptr, &DstM);
712 DGI->copyAttributesFrom(GI);
713 return DGI;
716 llvm_unreachable("Invalid source global value type");
719 GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
720 bool ForDefinition) {
721 GlobalValue *NewGV;
722 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
723 NewGV = copyGlobalVariableProto(SGVar);
724 } else if (auto *SF = dyn_cast<Function>(SGV)) {
725 NewGV = copyFunctionProto(SF);
726 } else {
727 if (ForDefinition)
728 NewGV = copyIndirectSymbolProto(SGV);
729 else if (SGV->getValueType()->isFunctionTy())
730 NewGV =
731 Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
732 GlobalValue::ExternalLinkage, SGV->getAddressSpace(),
733 SGV->getName(), &DstM);
734 else
735 NewGV =
736 new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
737 /*isConstant*/ false, GlobalValue::ExternalLinkage,
738 /*init*/ nullptr, SGV->getName(),
739 /*insertbefore*/ nullptr,
740 SGV->getThreadLocalMode(), SGV->getAddressSpace());
743 if (ForDefinition)
744 NewGV->setLinkage(SGV->getLinkage());
745 else if (SGV->hasExternalWeakLinkage())
746 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
748 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
749 // Metadata for global variables and function declarations is copied eagerly.
750 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration()) {
751 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
752 if (SGV->isDeclaration() && NewGO->hasMetadata())
753 UnmappedMetadata.insert(NewGO);
757 // Remove these copied constants in case this stays a declaration, since
758 // they point to the source module. If the def is linked the values will
759 // be mapped in during linkFunctionBody.
760 if (auto *NewF = dyn_cast<Function>(NewGV)) {
761 NewF->setPersonalityFn(nullptr);
762 NewF->setPrefixData(nullptr);
763 NewF->setPrologueData(nullptr);
766 return NewGV;
769 static StringRef getTypeNamePrefix(StringRef Name) {
770 size_t DotPos = Name.rfind('.');
771 return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
772 !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
773 ? Name
774 : Name.substr(0, DotPos);
777 /// Loop over all of the linked values to compute type mappings. For example,
778 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
779 /// types 'Foo' but one got renamed when the module was loaded into the same
780 /// LLVMContext.
781 void IRLinker::computeTypeMapping() {
782 for (GlobalValue &SGV : SrcM->globals()) {
783 GlobalValue *DGV = getLinkedToGlobal(&SGV);
784 if (!DGV)
785 continue;
787 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
788 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
789 continue;
792 // Unify the element type of appending arrays.
793 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
794 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
795 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
798 for (GlobalValue &SGV : *SrcM)
799 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
800 if (DGV->getType() == SGV.getType()) {
801 // If the types of DGV and SGV are the same, it means that DGV is from
802 // the source module and got added to DstM from a shared metadata. We
803 // shouldn't map this type to itself in case the type's components get
804 // remapped to a new type from DstM (for instance, during the loop over
805 // SrcM->getIdentifiedStructTypes() below).
806 continue;
809 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
812 for (GlobalValue &SGV : SrcM->aliases())
813 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
814 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
816 // Incorporate types by name, scanning all the types in the source module.
817 // At this point, the destination module may have a type "%foo = { i32 }" for
818 // example. When the source module got loaded into the same LLVMContext, if
819 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
820 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
821 for (StructType *ST : Types) {
822 if (!ST->hasName())
823 continue;
825 if (TypeMap.DstStructTypesSet.hasType(ST)) {
826 // This is actually a type from the destination module.
827 // getIdentifiedStructTypes() can have found it by walking debug info
828 // metadata nodes, some of which get linked by name when ODR Type Uniquing
829 // is enabled on the Context, from the source to the destination module.
830 continue;
833 auto STTypePrefix = getTypeNamePrefix(ST->getName());
834 if (STTypePrefix.size() == ST->getName().size())
835 continue;
837 // Check to see if the destination module has a struct with the prefix name.
838 StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
839 if (!DST)
840 continue;
842 // Don't use it if this actually came from the source module. They're in
843 // the same LLVMContext after all. Also don't use it unless the type is
844 // actually used in the destination module. This can happen in situations
845 // like this:
847 // Module A Module B
848 // -------- --------
849 // %Z = type { %A } %B = type { %C.1 }
850 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
851 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
852 // %C = type { i8* } %B.3 = type { %C.1 }
854 // When we link Module B with Module A, the '%B' in Module B is
855 // used. However, that would then use '%C.1'. But when we process '%C.1',
856 // we prefer to take the '%C' version. So we are then left with both
857 // '%C.1' and '%C' being used for the same types. This leads to some
858 // variables using one type and some using the other.
859 if (TypeMap.DstStructTypesSet.hasType(DST))
860 TypeMap.addTypeMapping(DST, ST);
863 // Now that we have discovered all of the type equivalences, get a body for
864 // any 'opaque' types in the dest module that are now resolved.
865 setError(TypeMap.linkDefinedTypeBodies());
868 static void getArrayElements(const Constant *C,
869 SmallVectorImpl<Constant *> &Dest) {
870 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
872 for (unsigned i = 0; i != NumElements; ++i)
873 Dest.push_back(C->getAggregateElement(i));
876 /// If there were any appending global variables, link them together now.
877 Expected<Constant *>
878 IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
879 const GlobalVariable *SrcGV) {
880 // Check that both variables have compatible properties.
881 if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
882 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
883 return stringErr(
884 "Linking globals named '" + SrcGV->getName() +
885 "': can only link appending global with another appending "
886 "global!");
888 if (DstGV->isConstant() != SrcGV->isConstant())
889 return stringErr("Appending variables linked with different const'ness!");
891 if (DstGV->getAlign() != SrcGV->getAlign())
892 return stringErr(
893 "Appending variables with different alignment need to be linked!");
895 if (DstGV->getVisibility() != SrcGV->getVisibility())
896 return stringErr(
897 "Appending variables with different visibility need to be linked!");
899 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
900 return stringErr(
901 "Appending variables with different unnamed_addr need to be linked!");
903 if (DstGV->getSection() != SrcGV->getSection())
904 return stringErr(
905 "Appending variables with different section name need to be linked!");
907 if (DstGV->getAddressSpace() != SrcGV->getAddressSpace())
908 return stringErr("Appending variables with different address spaces need "
909 "to be linked!");
912 // Do not need to do anything if source is a declaration.
913 if (SrcGV->isDeclaration())
914 return DstGV;
916 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
917 ->getElementType();
919 // FIXME: This upgrade is done during linking to support the C API. Once the
920 // old form is deprecated, we should move this upgrade to
921 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
922 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
923 StringRef Name = SrcGV->getName();
924 bool IsNewStructor = false;
925 bool IsOldStructor = false;
926 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
927 if (cast<StructType>(EltTy)->getNumElements() == 3)
928 IsNewStructor = true;
929 else
930 IsOldStructor = true;
933 PointerType *VoidPtrTy = PointerType::get(SrcGV->getContext(), 0);
934 if (IsOldStructor) {
935 auto &ST = *cast<StructType>(EltTy);
936 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
937 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
940 uint64_t DstNumElements = 0;
941 if (DstGV && !DstGV->isDeclaration()) {
942 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
943 DstNumElements = DstTy->getNumElements();
945 // Check to see that they two arrays agree on type.
946 if (EltTy != DstTy->getElementType())
947 return stringErr("Appending variables with different element types!");
950 SmallVector<Constant *, 16> SrcElements;
951 getArrayElements(SrcGV->getInitializer(), SrcElements);
953 if (IsNewStructor) {
954 erase_if(SrcElements, [this](Constant *E) {
955 auto *Key =
956 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
957 if (!Key)
958 return false;
959 GlobalValue *DGV = getLinkedToGlobal(Key);
960 return !shouldLink(DGV, *Key);
963 uint64_t NewSize = DstNumElements + SrcElements.size();
964 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
966 // Create the new global variable.
967 GlobalVariable *NG = new GlobalVariable(
968 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
969 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
970 SrcGV->getAddressSpace());
972 NG->copyAttributesFrom(SrcGV);
973 forceRenaming(NG, SrcGV->getName());
975 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
977 Mapper.scheduleMapAppendingVariable(
978 *NG,
979 (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
980 IsOldStructor, SrcElements);
982 // Replace any uses of the two global variables with uses of the new
983 // global.
984 if (DstGV) {
985 RAUWWorklist.push_back(std::make_pair(DstGV, NG));
988 return Ret;
991 bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
992 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
993 return true;
995 if (DGV && !DGV->isDeclarationForLinker())
996 return false;
998 if (SGV.isDeclaration() || DoneLinkingBodies)
999 return false;
1001 // Callback to the client to give a chance to lazily add the Global to the
1002 // list of value to link.
1003 bool LazilyAdded = false;
1004 if (AddLazyFor)
1005 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
1006 maybeAdd(&GV);
1007 LazilyAdded = true;
1009 return LazilyAdded;
1012 Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
1013 bool ForIndirectSymbol) {
1014 GlobalValue *DGV = getLinkedToGlobal(SGV);
1016 bool ShouldLink = shouldLink(DGV, *SGV);
1018 // just missing from map
1019 if (ShouldLink) {
1020 auto I = ValueMap.find(SGV);
1021 if (I != ValueMap.end())
1022 return cast<Constant>(I->second);
1024 I = IndirectSymbolValueMap.find(SGV);
1025 if (I != IndirectSymbolValueMap.end())
1026 return cast<Constant>(I->second);
1029 if (!ShouldLink && ForIndirectSymbol)
1030 DGV = nullptr;
1032 // Handle the ultra special appending linkage case first.
1033 if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
1034 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1035 cast<GlobalVariable>(SGV));
1037 bool NeedsRenaming = false;
1038 GlobalValue *NewGV;
1039 if (DGV && !ShouldLink) {
1040 NewGV = DGV;
1041 } else {
1042 // If we are done linking global value bodies (i.e. we are performing
1043 // metadata linking), don't link in the global value due to this
1044 // reference, simply map it to null.
1045 if (DoneLinkingBodies)
1046 return nullptr;
1048 NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1049 if (ShouldLink || !ForIndirectSymbol)
1050 NeedsRenaming = true;
1053 // Overloaded intrinsics have overloaded types names as part of their
1054 // names. If we renamed overloaded types we should rename the intrinsic
1055 // as well.
1056 if (Function *F = dyn_cast<Function>(NewGV))
1057 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
1058 // Note: remangleIntrinsicFunction does not copy metadata and as such
1059 // F should not occur in the set of objects with unmapped metadata.
1060 // If this assertion fails then remangleIntrinsicFunction needs updating.
1061 assert(!UnmappedMetadata.count(F) && "intrinsic has unmapped metadata");
1062 NewGV->eraseFromParent();
1063 NewGV = *Remangled;
1064 NeedsRenaming = false;
1067 if (NeedsRenaming)
1068 forceRenaming(NewGV, SGV->getName());
1070 if (ShouldLink || ForIndirectSymbol) {
1071 if (const Comdat *SC = SGV->getComdat()) {
1072 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1073 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1074 DC->setSelectionKind(SC->getSelectionKind());
1075 GO->setComdat(DC);
1080 if (!ShouldLink && ForIndirectSymbol)
1081 NewGV->setLinkage(GlobalValue::InternalLinkage);
1083 Constant *C = NewGV;
1084 // Only create a bitcast if necessary. In particular, with
1085 // DebugTypeODRUniquing we may reach metadata in the destination module
1086 // containing a GV from the source module, in which case SGV will be
1087 // the same as DGV and NewGV, and TypeMap.get() will assert since it
1088 // assumes it is being invoked on a type in the source module.
1089 if (DGV && NewGV != SGV) {
1090 C = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1091 NewGV, TypeMap.get(SGV->getType()));
1094 if (DGV && NewGV != DGV) {
1095 // Schedule "replace all uses with" to happen after materializing is
1096 // done. It is not safe to do it now, since ValueMapper may be holding
1097 // pointers to constants that will get deleted if RAUW runs.
1098 RAUWWorklist.push_back(std::make_pair(
1099 DGV,
1100 ConstantExpr::getPointerBitCastOrAddrSpaceCast(NewGV, DGV->getType())));
1103 return C;
1106 /// Update the initializers in the Dest module now that all globals that may be
1107 /// referenced are in Dest.
1108 void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
1109 // Figure out what the initializer looks like in the dest module.
1110 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
1113 /// Copy the source function over into the dest function and fix up references
1114 /// to values. At this point we know that Dest is an external function, and
1115 /// that Src is not.
1116 Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1117 assert(Dst.isDeclaration() && !Src.isDeclaration());
1119 // Materialize if needed.
1120 if (Error Err = Src.materialize())
1121 return Err;
1123 // Link in the operands without remapping.
1124 if (Src.hasPrefixData())
1125 Dst.setPrefixData(Src.getPrefixData());
1126 if (Src.hasPrologueData())
1127 Dst.setPrologueData(Src.getPrologueData());
1128 if (Src.hasPersonalityFn())
1129 Dst.setPersonalityFn(Src.getPersonalityFn());
1130 assert(Src.IsNewDbgInfoFormat == Dst.IsNewDbgInfoFormat);
1132 // Copy over the metadata attachments without remapping.
1133 Dst.copyMetadata(&Src, 0);
1135 // Steal arguments and splice the body of Src into Dst.
1136 Dst.stealArgumentListFrom(Src);
1137 Dst.splice(Dst.end(), &Src);
1139 // Everything has been moved over. Remap it.
1140 Mapper.scheduleRemapFunction(Dst);
1141 return Error::success();
1144 void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
1145 Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
1148 void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
1149 Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
1152 Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1153 if (auto *F = dyn_cast<Function>(&Src))
1154 return linkFunctionBody(cast<Function>(Dst), *F);
1155 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1156 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
1157 return Error::success();
1159 if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
1160 linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
1161 return Error::success();
1163 linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
1164 return Error::success();
1167 void IRLinker::flushRAUWWorklist() {
1168 for (const auto &Elem : RAUWWorklist) {
1169 GlobalValue *Old;
1170 Value *New;
1171 std::tie(Old, New) = Elem;
1173 Old->replaceAllUsesWith(New);
1174 Old->eraseFromParent();
1176 RAUWWorklist.clear();
1179 void IRLinker::prepareCompileUnitsForImport() {
1180 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
1181 if (!SrcCompileUnits)
1182 return;
1183 // When importing for ThinLTO, prevent importing of types listed on
1184 // the DICompileUnit that we don't need a copy of in the importing
1185 // module. They will be emitted by the originating module.
1186 for (MDNode *N : SrcCompileUnits->operands()) {
1187 auto *CU = cast<DICompileUnit>(N);
1188 assert(CU && "Expected valid compile unit");
1189 // Enums, macros, and retained types don't need to be listed on the
1190 // imported DICompileUnit. This means they will only be imported
1191 // if reached from the mapped IR.
1192 CU->replaceEnumTypes(nullptr);
1193 CU->replaceMacros(nullptr);
1194 CU->replaceRetainedTypes(nullptr);
1196 // The original definition (or at least its debug info - if the variable is
1197 // internalized and optimized away) will remain in the source module, so
1198 // there's no need to import them.
1199 // If LLVM ever does more advanced optimizations on global variables
1200 // (removing/localizing write operations, for instance) that can track
1201 // through debug info, this decision may need to be revisited - but do so
1202 // with care when it comes to debug info size. Emitting small CUs containing
1203 // only a few imported entities into every destination module may be very
1204 // size inefficient.
1205 CU->replaceGlobalVariables(nullptr);
1207 CU->replaceImportedEntities(nullptr);
1211 /// Insert all of the named MDNodes in Src into the Dest module.
1212 void IRLinker::linkNamedMDNodes() {
1213 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1214 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1215 // Don't link module flags here. Do them separately.
1216 if (&NMD == SrcModFlags)
1217 continue;
1218 // Don't import pseudo probe descriptors here for thinLTO. They will be
1219 // emitted by the originating module.
1220 if (IsPerformingImport && NMD.getName() == PseudoProbeDescMetadataName) {
1221 if (!DstM.getNamedMetadata(NMD.getName()))
1222 emitWarning("Pseudo-probe ignored: source module '" +
1223 SrcM->getModuleIdentifier() +
1224 "' is compiled with -fpseudo-probe-for-profiling while "
1225 "destination module '" +
1226 DstM.getModuleIdentifier() + "' is not\n");
1227 continue;
1229 // The stats are computed per module and will all be merged in the binary.
1230 // Importing the metadata will cause duplication of the stats.
1231 if (IsPerformingImport && NMD.getName() == "llvm.stats")
1232 continue;
1234 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1235 // Add Src elements into Dest node.
1236 for (const MDNode *Op : NMD.operands())
1237 DestNMD->addOperand(Mapper.mapMDNode(*Op));
1241 /// Merge the linker flags in Src into the Dest module.
1242 Error IRLinker::linkModuleFlagsMetadata() {
1243 // If the source module has no module flags, we are done.
1244 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1245 if (!SrcModFlags)
1246 return Error::success();
1248 // Check for module flag for updates before do anything.
1249 UpgradeModuleFlags(*SrcM);
1251 // If the destination module doesn't have module flags yet, then just copy
1252 // over the source module's flags.
1253 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1254 if (DstModFlags->getNumOperands() == 0) {
1255 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1256 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1258 return Error::success();
1261 // First build a map of the existing module flags and requirements.
1262 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1263 SmallSetVector<MDNode *, 16> Requirements;
1264 SmallVector<unsigned, 0> Mins;
1265 DenseSet<MDString *> SeenMin;
1266 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1267 MDNode *Op = DstModFlags->getOperand(I);
1268 uint64_t Behavior =
1269 mdconst::extract<ConstantInt>(Op->getOperand(0))->getZExtValue();
1270 MDString *ID = cast<MDString>(Op->getOperand(1));
1272 if (Behavior == Module::Require) {
1273 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1274 } else {
1275 if (Behavior == Module::Min)
1276 Mins.push_back(I);
1277 Flags[ID] = std::make_pair(Op, I);
1281 // Merge in the flags from the source module, and also collect its set of
1282 // requirements.
1283 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1284 MDNode *SrcOp = SrcModFlags->getOperand(I);
1285 ConstantInt *SrcBehavior =
1286 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1287 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1288 MDNode *DstOp;
1289 unsigned DstIndex;
1290 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1291 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1292 SeenMin.insert(ID);
1294 // If this is a requirement, add it and continue.
1295 if (SrcBehaviorValue == Module::Require) {
1296 // If the destination module does not already have this requirement, add
1297 // it.
1298 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1299 DstModFlags->addOperand(SrcOp);
1301 continue;
1304 // If there is no existing flag with this ID, just add it.
1305 if (!DstOp) {
1306 if (SrcBehaviorValue == Module::Min) {
1307 Mins.push_back(DstModFlags->getNumOperands());
1308 SeenMin.erase(ID);
1310 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1311 DstModFlags->addOperand(SrcOp);
1312 continue;
1315 // Otherwise, perform a merge.
1316 ConstantInt *DstBehavior =
1317 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1318 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1320 auto overrideDstValue = [&]() {
1321 DstModFlags->setOperand(DstIndex, SrcOp);
1322 Flags[ID].first = SrcOp;
1325 // If either flag has override behavior, handle it first.
1326 if (DstBehaviorValue == Module::Override) {
1327 // Diagnose inconsistent flags which both have override behavior.
1328 if (SrcBehaviorValue == Module::Override &&
1329 SrcOp->getOperand(2) != DstOp->getOperand(2))
1330 return stringErr("linking module flags '" + ID->getString() +
1331 "': IDs have conflicting override values in '" +
1332 SrcM->getModuleIdentifier() + "' and '" +
1333 DstM.getModuleIdentifier() + "'");
1334 continue;
1335 } else if (SrcBehaviorValue == Module::Override) {
1336 // Update the destination flag to that of the source.
1337 overrideDstValue();
1338 continue;
1341 // Diagnose inconsistent merge behavior types.
1342 if (SrcBehaviorValue != DstBehaviorValue) {
1343 bool MinAndWarn = (SrcBehaviorValue == Module::Min &&
1344 DstBehaviorValue == Module::Warning) ||
1345 (DstBehaviorValue == Module::Min &&
1346 SrcBehaviorValue == Module::Warning);
1347 bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
1348 DstBehaviorValue == Module::Warning) ||
1349 (DstBehaviorValue == Module::Max &&
1350 SrcBehaviorValue == Module::Warning);
1351 if (!(MaxAndWarn || MinAndWarn))
1352 return stringErr("linking module flags '" + ID->getString() +
1353 "': IDs have conflicting behaviors in '" +
1354 SrcM->getModuleIdentifier() + "' and '" +
1355 DstM.getModuleIdentifier() + "'");
1358 auto ensureDistinctOp = [&](MDNode *DstValue) {
1359 assert(isa<MDTuple>(DstValue) &&
1360 "Expected MDTuple when appending module flags");
1361 if (DstValue->isDistinct())
1362 return dyn_cast<MDTuple>(DstValue);
1363 ArrayRef<MDOperand> DstOperands = DstValue->operands();
1364 MDTuple *New = MDTuple::getDistinct(
1365 DstM.getContext(), SmallVector<Metadata *, 4>(DstOperands));
1366 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1367 MDNode *Flag = MDTuple::getDistinct(DstM.getContext(), FlagOps);
1368 DstModFlags->setOperand(DstIndex, Flag);
1369 Flags[ID].first = Flag;
1370 return New;
1373 // Emit a warning if the values differ and either source or destination
1374 // request Warning behavior.
1375 if ((DstBehaviorValue == Module::Warning ||
1376 SrcBehaviorValue == Module::Warning) &&
1377 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1378 std::string Str;
1379 raw_string_ostream(Str)
1380 << "linking module flags '" << ID->getString()
1381 << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
1382 << "' from " << SrcM->getModuleIdentifier() << " with '"
1383 << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
1384 << ')';
1385 emitWarning(Str);
1388 // Choose the minimum if either source or destination request Min behavior.
1389 if (DstBehaviorValue == Module::Min || SrcBehaviorValue == Module::Min) {
1390 ConstantInt *DstValue =
1391 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1392 ConstantInt *SrcValue =
1393 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1395 // The resulting flag should have a Min behavior, and contain the minimum
1396 // value from between the source and destination values.
1397 Metadata *FlagOps[] = {
1398 (DstBehaviorValue != Module::Min ? SrcOp : DstOp)->getOperand(0), ID,
1399 (SrcValue->getZExtValue() < DstValue->getZExtValue() ? SrcOp : DstOp)
1400 ->getOperand(2)};
1401 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1402 DstModFlags->setOperand(DstIndex, Flag);
1403 Flags[ID].first = Flag;
1404 continue;
1407 // Choose the maximum if either source or destination request Max behavior.
1408 if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
1409 ConstantInt *DstValue =
1410 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1411 ConstantInt *SrcValue =
1412 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1414 // The resulting flag should have a Max behavior, and contain the maximum
1415 // value from between the source and destination values.
1416 Metadata *FlagOps[] = {
1417 (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
1418 (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
1419 ->getOperand(2)};
1420 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1421 DstModFlags->setOperand(DstIndex, Flag);
1422 Flags[ID].first = Flag;
1423 continue;
1426 // Perform the merge for standard behavior types.
1427 switch (SrcBehaviorValue) {
1428 case Module::Require:
1429 case Module::Override:
1430 llvm_unreachable("not possible");
1431 case Module::Error: {
1432 // Emit an error if the values differ.
1433 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1434 std::string Str;
1435 raw_string_ostream(Str)
1436 << "linking module flags '" << ID->getString()
1437 << "': IDs have conflicting values: '" << *SrcOp->getOperand(2)
1438 << "' from " << SrcM->getModuleIdentifier() << ", and '"
1439 << *DstOp->getOperand(2) << "' from " + DstM.getModuleIdentifier();
1440 return stringErr(Str);
1442 continue;
1444 case Module::Warning: {
1445 break;
1447 case Module::Max: {
1448 break;
1450 case Module::Append: {
1451 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1452 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1453 for (const auto &O : SrcValue->operands())
1454 DstValue->push_back(O);
1455 break;
1457 case Module::AppendUnique: {
1458 SmallSetVector<Metadata *, 16> Elts;
1459 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1460 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1461 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1462 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1463 for (auto I = DstValue->getNumOperands(); I < Elts.size(); I++)
1464 DstValue->push_back(Elts[I]);
1465 break;
1471 // For the Min behavior, set the value to 0 if either module does not have the
1472 // flag.
1473 for (auto Idx : Mins) {
1474 MDNode *Op = DstModFlags->getOperand(Idx);
1475 MDString *ID = cast<MDString>(Op->getOperand(1));
1476 if (!SeenMin.count(ID)) {
1477 ConstantInt *V = mdconst::extract<ConstantInt>(Op->getOperand(2));
1478 Metadata *FlagOps[] = {
1479 Op->getOperand(0), ID,
1480 ConstantAsMetadata::get(ConstantInt::get(V->getType(), 0))};
1481 DstModFlags->setOperand(Idx, MDNode::get(DstM.getContext(), FlagOps));
1485 // Check all of the requirements.
1486 for (MDNode *Requirement : Requirements) {
1487 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1488 Metadata *ReqValue = Requirement->getOperand(1);
1490 MDNode *Op = Flags[Flag].first;
1491 if (!Op || Op->getOperand(2) != ReqValue)
1492 return stringErr("linking module flags '" + Flag->getString() +
1493 "': does not have the required value");
1495 return Error::success();
1498 /// Return InlineAsm adjusted with target-specific directives if required.
1499 /// For ARM and Thumb, we have to add directives to select the appropriate ISA
1500 /// to support mixing module-level inline assembly from ARM and Thumb modules.
1501 static std::string adjustInlineAsm(const std::string &InlineAsm,
1502 const Triple &Triple) {
1503 if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
1504 return ".text\n.balign 2\n.thumb\n" + InlineAsm;
1505 if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
1506 return ".text\n.balign 4\n.arm\n" + InlineAsm;
1507 return InlineAsm;
1510 void IRLinker::updateAttributes(GlobalValue &GV) {
1511 /// Remove nocallback attribute while linking, because nocallback attribute
1512 /// indicates that the function is only allowed to jump back into caller's
1513 /// module only by a return or an exception. When modules are linked, this
1514 /// property cannot be guaranteed anymore. For example, the nocallback
1515 /// function may contain a call to another module. But if we merge its caller
1516 /// and callee module here, and not the module containing the nocallback
1517 /// function definition itself, the nocallback property will be violated
1518 /// (since the nocallback function will call back into the newly merged module
1519 /// containing both its caller and callee). This could happen if the module
1520 /// containing the nocallback function definition is native code, so it does
1521 /// not participate in the LTO link. Note if the nocallback function does
1522 /// participate in the LTO link, and thus ends up in the merged module
1523 /// containing its caller and callee, removing the attribute doesn't hurt as
1524 /// it has no effect on definitions in the same module.
1525 if (auto *F = dyn_cast<Function>(&GV)) {
1526 if (!F->isIntrinsic())
1527 F->removeFnAttr(llvm::Attribute::NoCallback);
1529 // Remove nocallback attribute when it is on a call-site.
1530 for (BasicBlock &BB : *F)
1531 for (Instruction &I : BB)
1532 if (CallBase *CI = dyn_cast<CallBase>(&I))
1533 CI->removeFnAttr(Attribute::NoCallback);
1537 Error IRLinker::run() {
1538 // Ensure metadata materialized before value mapping.
1539 if (SrcM->getMaterializer())
1540 if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1541 return Err;
1543 // Convert source module to match dest for the duration of the link.
1544 ScopedDbgInfoFormatSetter FormatSetter(*SrcM, DstM.IsNewDbgInfoFormat);
1546 // Inherit the target data from the source module if the destination
1547 // module doesn't have one already.
1548 if (DstM.getDataLayout().isDefault())
1549 DstM.setDataLayout(SrcM->getDataLayout());
1551 // Copy the target triple from the source to dest if the dest's is empty.
1552 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1553 DstM.setTargetTriple(SrcM->getTargetTriple());
1555 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1557 // During CUDA compilation we have to link with the bitcode supplied with
1558 // CUDA. libdevice bitcode either has no data layout set (pre-CUDA-11), or has
1559 // the layout that is different from the one used by LLVM/clang (it does not
1560 // include i128). Issuing a warning is not very helpful as there's not much
1561 // the user can do about it.
1562 bool EnableDLWarning = true;
1563 bool EnableTripleWarning = true;
1564 if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
1565 std::string ModuleId = SrcM->getModuleIdentifier();
1566 StringRef FileName = llvm::sys::path::filename(ModuleId);
1567 bool SrcIsLibDevice =
1568 FileName.starts_with("libdevice") && FileName.ends_with(".10.bc");
1569 bool SrcHasLibDeviceDL =
1570 (SrcM->getDataLayoutStr().empty() ||
1571 SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
1572 // libdevice bitcode uses nvptx64-nvidia-gpulibs or just
1573 // 'nvptx-unknown-unknown' triple (before CUDA-10.x) and is compatible with
1574 // all NVPTX variants.
1575 bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
1576 SrcTriple.getOSName() == "gpulibs") ||
1577 (SrcTriple.getVendorName() == "unknown" &&
1578 SrcTriple.getOSName() == "unknown");
1579 EnableTripleWarning = !(SrcIsLibDevice && SrcHasLibDeviceTriple);
1580 EnableDLWarning = !(SrcIsLibDevice && SrcHasLibDeviceDL);
1583 if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
1584 emitWarning("Linking two modules of different data layouts: '" +
1585 SrcM->getModuleIdentifier() + "' is '" +
1586 SrcM->getDataLayoutStr() + "' whereas '" +
1587 DstM.getModuleIdentifier() + "' is '" +
1588 DstM.getDataLayoutStr() + "'\n");
1591 if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
1592 !SrcTriple.isCompatibleWith(DstTriple))
1593 emitWarning("Linking two modules of different target triples: '" +
1594 SrcM->getModuleIdentifier() + "' is '" +
1595 SrcM->getTargetTriple() + "' whereas '" +
1596 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1597 "'\n");
1599 DstM.setTargetTriple(SrcTriple.merge(DstTriple));
1601 // Loop over all of the linked values to compute type mappings.
1602 computeTypeMapping();
1604 std::reverse(Worklist.begin(), Worklist.end());
1605 while (!Worklist.empty()) {
1606 GlobalValue *GV = Worklist.back();
1607 Worklist.pop_back();
1609 // Already mapped.
1610 if (ValueMap.find(GV) != ValueMap.end() ||
1611 IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
1612 continue;
1614 assert(!GV->isDeclaration());
1615 Mapper.mapValue(*GV);
1616 if (FoundError)
1617 return std::move(*FoundError);
1618 flushRAUWWorklist();
1621 // Note that we are done linking global value bodies. This prevents
1622 // metadata linking from creating new references.
1623 DoneLinkingBodies = true;
1624 Mapper.addFlags(RF_NullMapMissingGlobalValues);
1626 // Remap all of the named MDNodes in Src into the DstM module. We do this
1627 // after linking GlobalValues so that MDNodes that reference GlobalValues
1628 // are properly remapped.
1629 linkNamedMDNodes();
1631 // Clean up any global objects with potentially unmapped metadata.
1632 // Specifically declarations which did not become definitions.
1633 for (GlobalObject *NGO : UnmappedMetadata) {
1634 if (NGO->isDeclaration())
1635 Mapper.remapGlobalObjectMetadata(*NGO);
1638 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1639 // Append the module inline asm string.
1640 DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
1641 SrcTriple));
1642 } else if (IsPerformingImport) {
1643 // Import any symver directives for symbols in DstM.
1644 ModuleSymbolTable::CollectAsmSymvers(*SrcM,
1645 [&](StringRef Name, StringRef Alias) {
1646 if (DstM.getNamedValue(Name)) {
1647 SmallString<256> S(".symver ");
1648 S += Name;
1649 S += ", ";
1650 S += Alias;
1651 DstM.appendModuleInlineAsm(S);
1656 // Reorder the globals just added to the destination module to match their
1657 // original order in the source module.
1658 for (GlobalVariable &GV : SrcM->globals()) {
1659 if (GV.hasAppendingLinkage())
1660 continue;
1661 Value *NewValue = Mapper.mapValue(GV);
1662 if (NewValue) {
1663 auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
1664 if (NewGV) {
1665 NewGV->removeFromParent();
1666 DstM.insertGlobalVariable(NewGV);
1671 // Merge the module flags into the DstM module.
1672 return linkModuleFlagsMetadata();
1675 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1676 : ETypes(E), IsPacked(P) {}
1678 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1679 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1681 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1682 return IsPacked == That.IsPacked && ETypes == That.ETypes;
1685 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1686 return !this->operator==(That);
1689 StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1690 return DenseMapInfo<StructType *>::getEmptyKey();
1693 StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1694 return DenseMapInfo<StructType *>::getTombstoneKey();
1697 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1698 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1699 Key.IsPacked);
1702 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1703 return getHashValue(KeyTy(ST));
1706 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1707 const StructType *RHS) {
1708 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1709 return false;
1710 return LHS == KeyTy(RHS);
1713 bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1714 const StructType *RHS) {
1715 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1716 return LHS == RHS;
1717 return KeyTy(LHS) == KeyTy(RHS);
1720 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1721 assert(!Ty->isOpaque());
1722 NonOpaqueStructTypes.insert(Ty);
1725 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1726 assert(!Ty->isOpaque());
1727 NonOpaqueStructTypes.insert(Ty);
1728 bool Removed = OpaqueStructTypes.erase(Ty);
1729 (void)Removed;
1730 assert(Removed);
1733 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1734 assert(Ty->isOpaque());
1735 OpaqueStructTypes.insert(Ty);
1738 StructType *
1739 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1740 bool IsPacked) {
1741 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1742 auto I = NonOpaqueStructTypes.find_as(Key);
1743 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1746 bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1747 if (Ty->isOpaque())
1748 return OpaqueStructTypes.count(Ty);
1749 auto I = NonOpaqueStructTypes.find(Ty);
1750 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1753 IRMover::IRMover(Module &M) : Composite(M) {
1754 TypeFinder StructTypes;
1755 StructTypes.run(M, /* OnlyNamed */ false);
1756 for (StructType *Ty : StructTypes) {
1757 if (Ty->isOpaque())
1758 IdentifiedStructTypes.addOpaque(Ty);
1759 else
1760 IdentifiedStructTypes.addNonOpaque(Ty);
1762 // Self-map metadatas in the destination module. This is needed when
1763 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1764 // destination module may be reached from the source module.
1765 for (const auto *MD : StructTypes.getVisitedMetadata()) {
1766 SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1770 Error IRMover::move(std::unique_ptr<Module> Src,
1771 ArrayRef<GlobalValue *> ValuesToLink,
1772 LazyCallback AddLazyFor, bool IsPerformingImport) {
1773 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1774 std::move(Src), ValuesToLink, std::move(AddLazyFor),
1775 IsPerformingImport);
1776 Error E = TheIRLinker.run();
1777 Composite.dropTriviallyDeadConstantArrays();
1778 return E;