1 //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Linker/IRMover.h"
10 #include "LinkDiagnosticInfo.h"
11 #include "llvm/ADT/SetVector.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/IR/Constants.h"
15 #include "llvm/IR/DebugInfo.h"
16 #include "llvm/IR/DiagnosticPrinter.h"
17 #include "llvm/IR/GVMaterializer.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/TypeFinder.h"
20 #include "llvm/Support/Error.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
25 //===----------------------------------------------------------------------===//
26 // TypeMap implementation.
27 //===----------------------------------------------------------------------===//
30 class TypeMapTy
: public ValueMapTypeRemapper
{
31 /// This is a mapping from a source type to a destination type to use.
32 DenseMap
<Type
*, Type
*> MappedTypes
;
34 /// When checking to see if two subgraphs are isomorphic, we speculatively
35 /// add types to MappedTypes, but keep track of them here in case we need to
37 SmallVector
<Type
*, 16> SpeculativeTypes
;
39 SmallVector
<StructType
*, 16> SpeculativeDstOpaqueTypes
;
41 /// This is a list of non-opaque structs in the source module that are mapped
42 /// to an opaque struct in the destination module.
43 SmallVector
<StructType
*, 16> SrcDefinitionsToResolve
;
45 /// This is the set of opaque types in the destination modules who are
46 /// getting a body from the source module.
47 SmallPtrSet
<StructType
*, 16> DstResolvedOpaqueTypes
;
50 TypeMapTy(IRMover::IdentifiedStructTypeSet
&DstStructTypesSet
)
51 : DstStructTypesSet(DstStructTypesSet
) {}
53 IRMover::IdentifiedStructTypeSet
&DstStructTypesSet
;
54 /// Indicate that the specified type in the destination module is conceptually
55 /// equivalent to the specified type in the source module.
56 void addTypeMapping(Type
*DstTy
, Type
*SrcTy
);
58 /// Produce a body for an opaque type in the dest module from a type
59 /// definition in the source module.
60 void linkDefinedTypeBodies();
62 /// Return the mapped type to use for the specified input type from the
64 Type
*get(Type
*SrcTy
);
65 Type
*get(Type
*SrcTy
, SmallPtrSet
<StructType
*, 8> &Visited
);
67 void finishType(StructType
*DTy
, StructType
*STy
, ArrayRef
<Type
*> ETypes
);
69 FunctionType
*get(FunctionType
*T
) {
70 return cast
<FunctionType
>(get((Type
*)T
));
74 Type
*remapType(Type
*SrcTy
) override
{ return get(SrcTy
); }
76 bool areTypesIsomorphic(Type
*DstTy
, Type
*SrcTy
);
80 void TypeMapTy::addTypeMapping(Type
*DstTy
, Type
*SrcTy
) {
81 assert(SpeculativeTypes
.empty());
82 assert(SpeculativeDstOpaqueTypes
.empty());
84 // Check to see if these types are recursively isomorphic and establish a
85 // mapping between them if so.
86 if (!areTypesIsomorphic(DstTy
, SrcTy
)) {
87 // Oops, they aren't isomorphic. Just discard this request by rolling out
88 // any speculative mappings we've established.
89 for (Type
*Ty
: SpeculativeTypes
)
90 MappedTypes
.erase(Ty
);
92 SrcDefinitionsToResolve
.resize(SrcDefinitionsToResolve
.size() -
93 SpeculativeDstOpaqueTypes
.size());
94 for (StructType
*Ty
: SpeculativeDstOpaqueTypes
)
95 DstResolvedOpaqueTypes
.erase(Ty
);
97 // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
98 // and all its descendants to lower amount of renaming in LLVM context
99 // Renaming occurs because we load all source modules to the same context
100 // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
101 // As a result we may get several different types in the destination
102 // module, which are in fact the same.
103 for (Type
*Ty
: SpeculativeTypes
)
104 if (auto *STy
= dyn_cast
<StructType
>(Ty
))
108 SpeculativeTypes
.clear();
109 SpeculativeDstOpaqueTypes
.clear();
112 /// Recursively walk this pair of types, returning true if they are isomorphic,
113 /// false if they are not.
114 bool TypeMapTy::areTypesIsomorphic(Type
*DstTy
, Type
*SrcTy
) {
115 // Two types with differing kinds are clearly not isomorphic.
116 if (DstTy
->getTypeID() != SrcTy
->getTypeID())
119 // If we have an entry in the MappedTypes table, then we have our answer.
120 Type
*&Entry
= MappedTypes
[SrcTy
];
122 return Entry
== DstTy
;
124 // Two identical types are clearly isomorphic. Remember this
125 // non-speculatively.
126 if (DstTy
== SrcTy
) {
131 // Okay, we have two types with identical kinds that we haven't seen before.
133 // If this is an opaque struct type, special case it.
134 if (StructType
*SSTy
= dyn_cast
<StructType
>(SrcTy
)) {
135 // Mapping an opaque type to any struct, just keep the dest struct.
136 if (SSTy
->isOpaque()) {
138 SpeculativeTypes
.push_back(SrcTy
);
142 // Mapping a non-opaque source type to an opaque dest. If this is the first
143 // type that we're mapping onto this destination type then we succeed. Keep
144 // the dest, but fill it in later. If this is the second (different) type
145 // that we're trying to map onto the same opaque type then we fail.
146 if (cast
<StructType
>(DstTy
)->isOpaque()) {
147 // We can only map one source type onto the opaque destination type.
148 if (!DstResolvedOpaqueTypes
.insert(cast
<StructType
>(DstTy
)).second
)
150 SrcDefinitionsToResolve
.push_back(SSTy
);
151 SpeculativeTypes
.push_back(SrcTy
);
152 SpeculativeDstOpaqueTypes
.push_back(cast
<StructType
>(DstTy
));
158 // If the number of subtypes disagree between the two types, then we fail.
159 if (SrcTy
->getNumContainedTypes() != DstTy
->getNumContainedTypes())
162 // Fail if any of the extra properties (e.g. array size) of the type disagree.
163 if (isa
<IntegerType
>(DstTy
))
164 return false; // bitwidth disagrees.
165 if (PointerType
*PT
= dyn_cast
<PointerType
>(DstTy
)) {
166 if (PT
->getAddressSpace() != cast
<PointerType
>(SrcTy
)->getAddressSpace())
168 } else if (FunctionType
*FT
= dyn_cast
<FunctionType
>(DstTy
)) {
169 if (FT
->isVarArg() != cast
<FunctionType
>(SrcTy
)->isVarArg())
171 } else if (StructType
*DSTy
= dyn_cast
<StructType
>(DstTy
)) {
172 StructType
*SSTy
= cast
<StructType
>(SrcTy
);
173 if (DSTy
->isLiteral() != SSTy
->isLiteral() ||
174 DSTy
->isPacked() != SSTy
->isPacked())
176 } else if (auto *DSeqTy
= dyn_cast
<SequentialType
>(DstTy
)) {
177 if (DSeqTy
->getNumElements() !=
178 cast
<SequentialType
>(SrcTy
)->getNumElements())
182 // Otherwise, we speculate that these two types will line up and recursively
183 // check the subelements.
185 SpeculativeTypes
.push_back(SrcTy
);
187 for (unsigned I
= 0, E
= SrcTy
->getNumContainedTypes(); I
!= E
; ++I
)
188 if (!areTypesIsomorphic(DstTy
->getContainedType(I
),
189 SrcTy
->getContainedType(I
)))
192 // If everything seems to have lined up, then everything is great.
196 void TypeMapTy::linkDefinedTypeBodies() {
197 SmallVector
<Type
*, 16> Elements
;
198 for (StructType
*SrcSTy
: SrcDefinitionsToResolve
) {
199 StructType
*DstSTy
= cast
<StructType
>(MappedTypes
[SrcSTy
]);
200 assert(DstSTy
->isOpaque());
202 // Map the body of the source type over to a new body for the dest type.
203 Elements
.resize(SrcSTy
->getNumElements());
204 for (unsigned I
= 0, E
= Elements
.size(); I
!= E
; ++I
)
205 Elements
[I
] = get(SrcSTy
->getElementType(I
));
207 DstSTy
->setBody(Elements
, SrcSTy
->isPacked());
208 DstStructTypesSet
.switchToNonOpaque(DstSTy
);
210 SrcDefinitionsToResolve
.clear();
211 DstResolvedOpaqueTypes
.clear();
214 void TypeMapTy::finishType(StructType
*DTy
, StructType
*STy
,
215 ArrayRef
<Type
*> ETypes
) {
216 DTy
->setBody(ETypes
, STy
->isPacked());
219 if (STy
->hasName()) {
220 SmallString
<16> TmpName
= STy
->getName();
222 DTy
->setName(TmpName
);
225 DstStructTypesSet
.addNonOpaque(DTy
);
228 Type
*TypeMapTy::get(Type
*Ty
) {
229 SmallPtrSet
<StructType
*, 8> Visited
;
230 return get(Ty
, Visited
);
233 Type
*TypeMapTy::get(Type
*Ty
, SmallPtrSet
<StructType
*, 8> &Visited
) {
234 // If we already have an entry for this type, return it.
235 Type
**Entry
= &MappedTypes
[Ty
];
239 // These are types that LLVM itself will unique.
240 bool IsUniqued
= !isa
<StructType
>(Ty
) || cast
<StructType
>(Ty
)->isLiteral();
243 StructType
*STy
= cast
<StructType
>(Ty
);
244 // This is actually a type from the destination module, this can be reached
245 // when this type is loaded in another module, added to DstStructTypesSet,
246 // and then we reach the same type in another module where it has not been
247 // added to MappedTypes. (PR37684)
248 if (STy
->getContext().isODRUniquingDebugTypes() && !STy
->isOpaque() &&
249 DstStructTypesSet
.hasType(STy
))
253 for (auto &Pair
: MappedTypes
) {
254 assert(!(Pair
.first
!= Ty
&& Pair
.second
== Ty
) &&
255 "mapping to a source type");
259 if (!Visited
.insert(STy
).second
) {
260 StructType
*DTy
= StructType::create(Ty
->getContext());
265 // If this is not a recursive type, then just map all of the elements and
266 // then rebuild the type from inside out.
267 SmallVector
<Type
*, 4> ElementTypes
;
269 // If there are no element types to map, then the type is itself. This is
270 // true for the anonymous {} struct, things like 'float', integers, etc.
271 if (Ty
->getNumContainedTypes() == 0 && IsUniqued
)
274 // Remap all of the elements, keeping track of whether any of them change.
275 bool AnyChange
= false;
276 ElementTypes
.resize(Ty
->getNumContainedTypes());
277 for (unsigned I
= 0, E
= Ty
->getNumContainedTypes(); I
!= E
; ++I
) {
278 ElementTypes
[I
] = get(Ty
->getContainedType(I
), Visited
);
279 AnyChange
|= ElementTypes
[I
] != Ty
->getContainedType(I
);
282 // If we found our type while recursively processing stuff, just use it.
283 Entry
= &MappedTypes
[Ty
];
285 if (auto *DTy
= dyn_cast
<StructType
>(*Entry
)) {
286 if (DTy
->isOpaque()) {
287 auto *STy
= cast
<StructType
>(Ty
);
288 finishType(DTy
, STy
, ElementTypes
);
294 // If all of the element types mapped directly over and the type is not
295 // a named struct, then the type is usable as-is.
296 if (!AnyChange
&& IsUniqued
)
299 // Otherwise, rebuild a modified type.
300 switch (Ty
->getTypeID()) {
302 llvm_unreachable("unknown derived type to remap");
303 case Type::ArrayTyID
:
304 return *Entry
= ArrayType::get(ElementTypes
[0],
305 cast
<ArrayType
>(Ty
)->getNumElements());
306 case Type::VectorTyID
:
307 return *Entry
= VectorType::get(ElementTypes
[0],
308 cast
<VectorType
>(Ty
)->getNumElements());
309 case Type::PointerTyID
:
310 return *Entry
= PointerType::get(ElementTypes
[0],
311 cast
<PointerType
>(Ty
)->getAddressSpace());
312 case Type::FunctionTyID
:
313 return *Entry
= FunctionType::get(ElementTypes
[0],
314 makeArrayRef(ElementTypes
).slice(1),
315 cast
<FunctionType
>(Ty
)->isVarArg());
316 case Type::StructTyID
: {
317 auto *STy
= cast
<StructType
>(Ty
);
318 bool IsPacked
= STy
->isPacked();
320 return *Entry
= StructType::get(Ty
->getContext(), ElementTypes
, IsPacked
);
322 // If the type is opaque, we can just use it directly.
323 if (STy
->isOpaque()) {
324 DstStructTypesSet
.addOpaque(STy
);
328 if (StructType
*OldT
=
329 DstStructTypesSet
.findNonOpaque(ElementTypes
, IsPacked
)) {
331 return *Entry
= OldT
;
335 DstStructTypesSet
.addNonOpaque(STy
);
339 StructType
*DTy
= StructType::create(Ty
->getContext());
340 finishType(DTy
, STy
, ElementTypes
);
346 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity
,
348 : DiagnosticInfo(DK_Linker
, Severity
), Msg(Msg
) {}
349 void LinkDiagnosticInfo::print(DiagnosticPrinter
&DP
) const { DP
<< Msg
; }
351 //===----------------------------------------------------------------------===//
352 // IRLinker implementation.
353 //===----------------------------------------------------------------------===//
358 /// Creates prototypes for functions that are lazily linked on the fly. This
359 /// speeds up linking for modules with many/ lazily linked functions of which
361 class GlobalValueMaterializer final
: public ValueMaterializer
{
362 IRLinker
&TheIRLinker
;
365 GlobalValueMaterializer(IRLinker
&TheIRLinker
) : TheIRLinker(TheIRLinker
) {}
366 Value
*materialize(Value
*V
) override
;
369 class LocalValueMaterializer final
: public ValueMaterializer
{
370 IRLinker
&TheIRLinker
;
373 LocalValueMaterializer(IRLinker
&TheIRLinker
) : TheIRLinker(TheIRLinker
) {}
374 Value
*materialize(Value
*V
) override
;
377 /// Type of the Metadata map in \a ValueToValueMapTy.
378 typedef DenseMap
<const Metadata
*, TrackingMDRef
> MDMapT
;
380 /// This is responsible for keeping track of the state used for moving data
381 /// from SrcM to DstM.
384 std::unique_ptr
<Module
> SrcM
;
386 /// See IRMover::move().
387 std::function
<void(GlobalValue
&, IRMover::ValueAdder
)> AddLazyFor
;
390 GlobalValueMaterializer GValMaterializer
;
391 LocalValueMaterializer LValMaterializer
;
393 /// A metadata map that's shared between IRLinker instances.
396 /// Mapping of values from what they used to be in Src, to what they are now
397 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
398 /// due to the use of Value handles which the Linker doesn't actually need,
399 /// but this allows us to reuse the ValueMapper code.
400 ValueToValueMapTy ValueMap
;
401 ValueToValueMapTy AliasValueMap
;
403 DenseSet
<GlobalValue
*> ValuesToLink
;
404 std::vector
<GlobalValue
*> Worklist
;
405 std::vector
<std::pair
<GlobalValue
*, Value
*>> RAUWWorklist
;
407 void maybeAdd(GlobalValue
*GV
) {
408 if (ValuesToLink
.insert(GV
).second
)
409 Worklist
.push_back(GV
);
412 /// Whether we are importing globals for ThinLTO, as opposed to linking the
413 /// source module. If this flag is set, it means that we can rely on some
414 /// other object file to define any non-GlobalValue entities defined by the
415 /// source module. This currently causes us to not link retained types in
416 /// debug info metadata and module inline asm.
417 bool IsPerformingImport
;
419 /// Set to true when all global value body linking is complete (including
420 /// lazy linking). Used to prevent metadata linking from creating new
422 bool DoneLinkingBodies
= false;
424 /// The Error encountered during materialization. We use an Optional here to
425 /// avoid needing to manage an unconsumed success value.
426 Optional
<Error
> FoundError
;
427 void setError(Error E
) {
429 FoundError
= std::move(E
);
432 /// Most of the errors produced by this module are inconvertible StringErrors.
433 /// This convenience function lets us return one of those more easily.
434 Error
stringErr(const Twine
&T
) {
435 return make_error
<StringError
>(T
, inconvertibleErrorCode());
438 /// Entry point for mapping values and alternate context for mapping aliases.
442 /// Handles cloning of a global values from the source module into
443 /// the destination module, including setting the attributes and visibility.
444 GlobalValue
*copyGlobalValueProto(const GlobalValue
*SGV
, bool ForDefinition
);
446 void emitWarning(const Twine
&Message
) {
447 SrcM
->getContext().diagnose(LinkDiagnosticInfo(DS_Warning
, Message
));
450 /// Given a global in the source module, return the global in the
451 /// destination module that is being linked to, if any.
452 GlobalValue
*getLinkedToGlobal(const GlobalValue
*SrcGV
) {
453 // If the source has no name it can't link. If it has local linkage,
454 // there is no name match-up going on.
455 if (!SrcGV
->hasName() || SrcGV
->hasLocalLinkage())
458 // Otherwise see if we have a match in the destination module's symtab.
459 GlobalValue
*DGV
= DstM
.getNamedValue(SrcGV
->getName());
463 // If we found a global with the same name in the dest module, but it has
464 // internal linkage, we are really not doing any linkage here.
465 if (DGV
->hasLocalLinkage())
468 // Otherwise, we do in fact link to the destination global.
472 void computeTypeMapping();
474 Expected
<Constant
*> linkAppendingVarProto(GlobalVariable
*DstGV
,
475 const GlobalVariable
*SrcGV
);
477 /// Given the GlobaValue \p SGV in the source module, and the matching
478 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
479 /// into the destination module.
481 /// Note this code may call the client-provided \p AddLazyFor.
482 bool shouldLink(GlobalValue
*DGV
, GlobalValue
&SGV
);
483 Expected
<Constant
*> linkGlobalValueProto(GlobalValue
*GV
, bool ForAlias
);
485 Error
linkModuleFlagsMetadata();
487 void linkGlobalVariable(GlobalVariable
&Dst
, GlobalVariable
&Src
);
488 Error
linkFunctionBody(Function
&Dst
, Function
&Src
);
489 void linkAliasBody(GlobalAlias
&Dst
, GlobalAlias
&Src
);
490 Error
linkGlobalValueBody(GlobalValue
&Dst
, GlobalValue
&Src
);
492 /// Functions that take care of cloning a specific global value type
493 /// into the destination module.
494 GlobalVariable
*copyGlobalVariableProto(const GlobalVariable
*SGVar
);
495 Function
*copyFunctionProto(const Function
*SF
);
496 GlobalValue
*copyGlobalAliasProto(const GlobalAlias
*SGA
);
498 /// Perform "replace all uses with" operations. These work items need to be
499 /// performed as part of materialization, but we postpone them to happen after
500 /// materialization is done. The materializer called by ValueMapper is not
501 /// expected to delete constants, as ValueMapper is holding pointers to some
502 /// of them, but constant destruction may be indirectly triggered by RAUW.
503 /// Hence, the need to move this out of the materialization call chain.
504 void flushRAUWWorklist();
506 /// When importing for ThinLTO, prevent importing of types listed on
507 /// the DICompileUnit that we don't need a copy of in the importing
509 void prepareCompileUnitsForImport();
510 void linkNamedMDNodes();
513 IRLinker(Module
&DstM
, MDMapT
&SharedMDs
,
514 IRMover::IdentifiedStructTypeSet
&Set
, std::unique_ptr
<Module
> SrcM
,
515 ArrayRef
<GlobalValue
*> ValuesToLink
,
516 std::function
<void(GlobalValue
&, IRMover::ValueAdder
)> AddLazyFor
,
517 bool IsPerformingImport
)
518 : DstM(DstM
), SrcM(std::move(SrcM
)), AddLazyFor(std::move(AddLazyFor
)),
519 TypeMap(Set
), GValMaterializer(*this), LValMaterializer(*this),
520 SharedMDs(SharedMDs
), IsPerformingImport(IsPerformingImport
),
521 Mapper(ValueMap
, RF_MoveDistinctMDs
| RF_IgnoreMissingLocals
, &TypeMap
,
523 AliasMCID(Mapper
.registerAlternateMappingContext(AliasValueMap
,
524 &LValMaterializer
)) {
525 ValueMap
.getMDMap() = std::move(SharedMDs
);
526 for (GlobalValue
*GV
: ValuesToLink
)
528 if (IsPerformingImport
)
529 prepareCompileUnitsForImport();
531 ~IRLinker() { SharedMDs
= std::move(*ValueMap
.getMDMap()); }
534 Value
*materialize(Value
*V
, bool ForAlias
);
538 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
539 /// table. This is good for all clients except for us. Go through the trouble
540 /// to force this back.
541 static void forceRenaming(GlobalValue
*GV
, StringRef Name
) {
542 // If the global doesn't force its name or if it already has the right name,
543 // there is nothing for us to do.
544 if (GV
->hasLocalLinkage() || GV
->getName() == Name
)
547 Module
*M
= GV
->getParent();
549 // If there is a conflict, rename the conflict.
550 if (GlobalValue
*ConflictGV
= M
->getNamedValue(Name
)) {
551 GV
->takeName(ConflictGV
);
552 ConflictGV
->setName(Name
); // This will cause ConflictGV to get renamed
553 assert(ConflictGV
->getName() != Name
&& "forceRenaming didn't work");
555 GV
->setName(Name
); // Force the name back
559 Value
*GlobalValueMaterializer::materialize(Value
*SGV
) {
560 return TheIRLinker
.materialize(SGV
, false);
563 Value
*LocalValueMaterializer::materialize(Value
*SGV
) {
564 return TheIRLinker
.materialize(SGV
, true);
567 Value
*IRLinker::materialize(Value
*V
, bool ForAlias
) {
568 auto *SGV
= dyn_cast
<GlobalValue
>(V
);
572 Expected
<Constant
*> NewProto
= linkGlobalValueProto(SGV
, ForAlias
);
574 setError(NewProto
.takeError());
580 GlobalValue
*New
= dyn_cast
<GlobalValue
>(*NewProto
);
584 // If we already created the body, just return.
585 if (auto *F
= dyn_cast
<Function
>(New
)) {
586 if (!F
->isDeclaration())
588 } else if (auto *V
= dyn_cast
<GlobalVariable
>(New
)) {
589 if (V
->hasInitializer() || V
->hasAppendingLinkage())
592 auto *A
= cast
<GlobalAlias
>(New
);
597 // When linking a global for an alias, it will always be linked. However we
598 // need to check if it was not already scheduled to satisfy a reference from a
599 // regular global value initializer. We know if it has been schedule if the
600 // "New" GlobalValue that is mapped here for the alias is the same as the one
601 // already mapped. If there is an entry in the ValueMap but the value is
602 // different, it means that the value already had a definition in the
603 // destination module (linkonce for instance), but we need a new definition
604 // for the alias ("New" will be different.
605 if (ForAlias
&& ValueMap
.lookup(SGV
) == New
)
608 if (ForAlias
|| shouldLink(New
, *SGV
))
609 setError(linkGlobalValueBody(*New
, *SGV
));
614 /// Loop through the global variables in the src module and merge them into the
616 GlobalVariable
*IRLinker::copyGlobalVariableProto(const GlobalVariable
*SGVar
) {
617 // No linking to be performed or linking from the source: simply create an
618 // identical version of the symbol over in the dest module... the
619 // initializer will be filled in later by LinkGlobalInits.
620 GlobalVariable
*NewDGV
=
621 new GlobalVariable(DstM
, TypeMap
.get(SGVar
->getValueType()),
622 SGVar
->isConstant(), GlobalValue::ExternalLinkage
,
623 /*init*/ nullptr, SGVar
->getName(),
624 /*insertbefore*/ nullptr, SGVar
->getThreadLocalMode(),
625 SGVar
->getType()->getAddressSpace());
626 NewDGV
->setAlignment(SGVar
->getAlignment());
627 NewDGV
->copyAttributesFrom(SGVar
);
631 /// Link the function in the source module into the destination module if
632 /// needed, setting up mapping information.
633 Function
*IRLinker::copyFunctionProto(const Function
*SF
) {
634 // If there is no linkage to be performed or we are linking from the source,
637 Function::Create(TypeMap
.get(SF
->getFunctionType()),
638 GlobalValue::ExternalLinkage
, SF
->getName(), &DstM
);
639 F
->copyAttributesFrom(SF
);
643 /// Set up prototypes for any aliases that come over from the source module.
644 GlobalValue
*IRLinker::copyGlobalAliasProto(const GlobalAlias
*SGA
) {
645 // If there is no linkage to be performed or we're linking from the source,
647 auto *Ty
= TypeMap
.get(SGA
->getValueType());
649 GlobalAlias::create(Ty
, SGA
->getType()->getPointerAddressSpace(),
650 GlobalValue::ExternalLinkage
, SGA
->getName(), &DstM
);
651 GA
->copyAttributesFrom(SGA
);
655 GlobalValue
*IRLinker::copyGlobalValueProto(const GlobalValue
*SGV
,
656 bool ForDefinition
) {
658 if (auto *SGVar
= dyn_cast
<GlobalVariable
>(SGV
)) {
659 NewGV
= copyGlobalVariableProto(SGVar
);
660 } else if (auto *SF
= dyn_cast
<Function
>(SGV
)) {
661 NewGV
= copyFunctionProto(SF
);
664 NewGV
= copyGlobalAliasProto(cast
<GlobalAlias
>(SGV
));
665 else if (SGV
->getValueType()->isFunctionTy())
667 Function::Create(cast
<FunctionType
>(TypeMap
.get(SGV
->getValueType())),
668 GlobalValue::ExternalLinkage
, SGV
->getName(), &DstM
);
670 NewGV
= new GlobalVariable(
671 DstM
, TypeMap
.get(SGV
->getValueType()),
672 /*isConstant*/ false, GlobalValue::ExternalLinkage
,
673 /*init*/ nullptr, SGV
->getName(),
674 /*insertbefore*/ nullptr, SGV
->getThreadLocalMode(),
675 SGV
->getType()->getAddressSpace());
679 NewGV
->setLinkage(SGV
->getLinkage());
680 else if (SGV
->hasExternalWeakLinkage())
681 NewGV
->setLinkage(GlobalValue::ExternalWeakLinkage
);
683 if (auto *NewGO
= dyn_cast
<GlobalObject
>(NewGV
)) {
684 // Metadata for global variables and function declarations is copied eagerly.
685 if (isa
<GlobalVariable
>(SGV
) || SGV
->isDeclaration())
686 NewGO
->copyMetadata(cast
<GlobalObject
>(SGV
), 0);
689 // Remove these copied constants in case this stays a declaration, since
690 // they point to the source module. If the def is linked the values will
691 // be mapped in during linkFunctionBody.
692 if (auto *NewF
= dyn_cast
<Function
>(NewGV
)) {
693 NewF
->setPersonalityFn(nullptr);
694 NewF
->setPrefixData(nullptr);
695 NewF
->setPrologueData(nullptr);
701 static StringRef
getTypeNamePrefix(StringRef Name
) {
702 size_t DotPos
= Name
.rfind('.');
703 return (DotPos
== 0 || DotPos
== StringRef::npos
|| Name
.back() == '.' ||
704 !isdigit(static_cast<unsigned char>(Name
[DotPos
+ 1])))
706 : Name
.substr(0, DotPos
);
709 /// Loop over all of the linked values to compute type mappings. For example,
710 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
711 /// types 'Foo' but one got renamed when the module was loaded into the same
713 void IRLinker::computeTypeMapping() {
714 for (GlobalValue
&SGV
: SrcM
->globals()) {
715 GlobalValue
*DGV
= getLinkedToGlobal(&SGV
);
719 if (!DGV
->hasAppendingLinkage() || !SGV
.hasAppendingLinkage()) {
720 TypeMap
.addTypeMapping(DGV
->getType(), SGV
.getType());
724 // Unify the element type of appending arrays.
725 ArrayType
*DAT
= cast
<ArrayType
>(DGV
->getValueType());
726 ArrayType
*SAT
= cast
<ArrayType
>(SGV
.getValueType());
727 TypeMap
.addTypeMapping(DAT
->getElementType(), SAT
->getElementType());
730 for (GlobalValue
&SGV
: *SrcM
)
731 if (GlobalValue
*DGV
= getLinkedToGlobal(&SGV
))
732 TypeMap
.addTypeMapping(DGV
->getType(), SGV
.getType());
734 for (GlobalValue
&SGV
: SrcM
->aliases())
735 if (GlobalValue
*DGV
= getLinkedToGlobal(&SGV
))
736 TypeMap
.addTypeMapping(DGV
->getType(), SGV
.getType());
738 // Incorporate types by name, scanning all the types in the source module.
739 // At this point, the destination module may have a type "%foo = { i32 }" for
740 // example. When the source module got loaded into the same LLVMContext, if
741 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
742 std::vector
<StructType
*> Types
= SrcM
->getIdentifiedStructTypes();
743 for (StructType
*ST
: Types
) {
747 if (TypeMap
.DstStructTypesSet
.hasType(ST
)) {
748 // This is actually a type from the destination module.
749 // getIdentifiedStructTypes() can have found it by walking debug info
750 // metadata nodes, some of which get linked by name when ODR Type Uniquing
751 // is enabled on the Context, from the source to the destination module.
755 auto STTypePrefix
= getTypeNamePrefix(ST
->getName());
756 if (STTypePrefix
.size()== ST
->getName().size())
759 // Check to see if the destination module has a struct with the prefix name.
760 StructType
*DST
= DstM
.getTypeByName(STTypePrefix
);
764 // Don't use it if this actually came from the source module. They're in
765 // the same LLVMContext after all. Also don't use it unless the type is
766 // actually used in the destination module. This can happen in situations
771 // %Z = type { %A } %B = type { %C.1 }
772 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
773 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
774 // %C = type { i8* } %B.3 = type { %C.1 }
776 // When we link Module B with Module A, the '%B' in Module B is
777 // used. However, that would then use '%C.1'. But when we process '%C.1',
778 // we prefer to take the '%C' version. So we are then left with both
779 // '%C.1' and '%C' being used for the same types. This leads to some
780 // variables using one type and some using the other.
781 if (TypeMap
.DstStructTypesSet
.hasType(DST
))
782 TypeMap
.addTypeMapping(DST
, ST
);
785 // Now that we have discovered all of the type equivalences, get a body for
786 // any 'opaque' types in the dest module that are now resolved.
787 TypeMap
.linkDefinedTypeBodies();
790 static void getArrayElements(const Constant
*C
,
791 SmallVectorImpl
<Constant
*> &Dest
) {
792 unsigned NumElements
= cast
<ArrayType
>(C
->getType())->getNumElements();
794 for (unsigned i
= 0; i
!= NumElements
; ++i
)
795 Dest
.push_back(C
->getAggregateElement(i
));
798 /// If there were any appending global variables, link them together now.
800 IRLinker::linkAppendingVarProto(GlobalVariable
*DstGV
,
801 const GlobalVariable
*SrcGV
) {
802 Type
*EltTy
= cast
<ArrayType
>(TypeMap
.get(SrcGV
->getValueType()))
805 // FIXME: This upgrade is done during linking to support the C API. Once the
806 // old form is deprecated, we should move this upgrade to
807 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
808 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
809 StringRef Name
= SrcGV
->getName();
810 bool IsNewStructor
= false;
811 bool IsOldStructor
= false;
812 if (Name
== "llvm.global_ctors" || Name
== "llvm.global_dtors") {
813 if (cast
<StructType
>(EltTy
)->getNumElements() == 3)
814 IsNewStructor
= true;
816 IsOldStructor
= true;
819 PointerType
*VoidPtrTy
= Type::getInt8Ty(SrcGV
->getContext())->getPointerTo();
821 auto &ST
= *cast
<StructType
>(EltTy
);
822 Type
*Tys
[3] = {ST
.getElementType(0), ST
.getElementType(1), VoidPtrTy
};
823 EltTy
= StructType::get(SrcGV
->getContext(), Tys
, false);
826 uint64_t DstNumElements
= 0;
828 ArrayType
*DstTy
= cast
<ArrayType
>(DstGV
->getValueType());
829 DstNumElements
= DstTy
->getNumElements();
831 if (!SrcGV
->hasAppendingLinkage() || !DstGV
->hasAppendingLinkage())
833 "Linking globals named '" + SrcGV
->getName() +
834 "': can only link appending global with another appending "
837 // Check to see that they two arrays agree on type.
838 if (EltTy
!= DstTy
->getElementType())
839 return stringErr("Appending variables with different element types!");
840 if (DstGV
->isConstant() != SrcGV
->isConstant())
841 return stringErr("Appending variables linked with different const'ness!");
843 if (DstGV
->getAlignment() != SrcGV
->getAlignment())
845 "Appending variables with different alignment need to be linked!");
847 if (DstGV
->getVisibility() != SrcGV
->getVisibility())
849 "Appending variables with different visibility need to be linked!");
851 if (DstGV
->hasGlobalUnnamedAddr() != SrcGV
->hasGlobalUnnamedAddr())
853 "Appending variables with different unnamed_addr need to be linked!");
855 if (DstGV
->getSection() != SrcGV
->getSection())
857 "Appending variables with different section name need to be linked!");
860 SmallVector
<Constant
*, 16> SrcElements
;
861 getArrayElements(SrcGV
->getInitializer(), SrcElements
);
864 auto It
= remove_if(SrcElements
, [this](Constant
*E
) {
866 dyn_cast
<GlobalValue
>(E
->getAggregateElement(2)->stripPointerCasts());
869 GlobalValue
*DGV
= getLinkedToGlobal(Key
);
870 return !shouldLink(DGV
, *Key
);
872 SrcElements
.erase(It
, SrcElements
.end());
874 uint64_t NewSize
= DstNumElements
+ SrcElements
.size();
875 ArrayType
*NewType
= ArrayType::get(EltTy
, NewSize
);
877 // Create the new global variable.
878 GlobalVariable
*NG
= new GlobalVariable(
879 DstM
, NewType
, SrcGV
->isConstant(), SrcGV
->getLinkage(),
880 /*init*/ nullptr, /*name*/ "", DstGV
, SrcGV
->getThreadLocalMode(),
881 SrcGV
->getType()->getAddressSpace());
883 NG
->copyAttributesFrom(SrcGV
);
884 forceRenaming(NG
, SrcGV
->getName());
886 Constant
*Ret
= ConstantExpr::getBitCast(NG
, TypeMap
.get(SrcGV
->getType()));
888 Mapper
.scheduleMapAppendingVariable(*NG
,
889 DstGV
? DstGV
->getInitializer() : nullptr,
890 IsOldStructor
, SrcElements
);
892 // Replace any uses of the two global variables with uses of the new
895 RAUWWorklist
.push_back(
896 std::make_pair(DstGV
, ConstantExpr::getBitCast(NG
, DstGV
->getType())));
902 bool IRLinker::shouldLink(GlobalValue
*DGV
, GlobalValue
&SGV
) {
903 if (ValuesToLink
.count(&SGV
) || SGV
.hasLocalLinkage())
906 if (DGV
&& !DGV
->isDeclarationForLinker())
909 if (SGV
.isDeclaration() || DoneLinkingBodies
)
912 // Callback to the client to give a chance to lazily add the Global to the
913 // list of value to link.
914 bool LazilyAdded
= false;
915 AddLazyFor(SGV
, [this, &LazilyAdded
](GlobalValue
&GV
) {
922 Expected
<Constant
*> IRLinker::linkGlobalValueProto(GlobalValue
*SGV
,
924 GlobalValue
*DGV
= getLinkedToGlobal(SGV
);
926 bool ShouldLink
= shouldLink(DGV
, *SGV
);
928 // just missing from map
930 auto I
= ValueMap
.find(SGV
);
931 if (I
!= ValueMap
.end())
932 return cast
<Constant
>(I
->second
);
934 I
= AliasValueMap
.find(SGV
);
935 if (I
!= AliasValueMap
.end())
936 return cast
<Constant
>(I
->second
);
939 if (!ShouldLink
&& ForAlias
)
942 // Handle the ultra special appending linkage case first.
943 assert(!DGV
|| SGV
->hasAppendingLinkage() == DGV
->hasAppendingLinkage());
944 if (SGV
->hasAppendingLinkage())
945 return linkAppendingVarProto(cast_or_null
<GlobalVariable
>(DGV
),
946 cast
<GlobalVariable
>(SGV
));
949 if (DGV
&& !ShouldLink
) {
952 // If we are done linking global value bodies (i.e. we are performing
953 // metadata linking), don't link in the global value due to this
954 // reference, simply map it to null.
955 if (DoneLinkingBodies
)
958 NewGV
= copyGlobalValueProto(SGV
, ShouldLink
|| ForAlias
);
959 if (ShouldLink
|| !ForAlias
)
960 forceRenaming(NewGV
, SGV
->getName());
963 // Overloaded intrinsics have overloaded types names as part of their
964 // names. If we renamed overloaded types we should rename the intrinsic
966 if (Function
*F
= dyn_cast
<Function
>(NewGV
))
967 if (auto Remangled
= Intrinsic::remangleIntrinsicFunction(F
))
968 NewGV
= Remangled
.getValue();
970 if (ShouldLink
|| ForAlias
) {
971 if (const Comdat
*SC
= SGV
->getComdat()) {
972 if (auto *GO
= dyn_cast
<GlobalObject
>(NewGV
)) {
973 Comdat
*DC
= DstM
.getOrInsertComdat(SC
->getName());
974 DC
->setSelectionKind(SC
->getSelectionKind());
980 if (!ShouldLink
&& ForAlias
)
981 NewGV
->setLinkage(GlobalValue::InternalLinkage
);
984 // Only create a bitcast if necessary. In particular, with
985 // DebugTypeODRUniquing we may reach metadata in the destination module
986 // containing a GV from the source module, in which case SGV will be
987 // the same as DGV and NewGV, and TypeMap.get() will assert since it
988 // assumes it is being invoked on a type in the source module.
989 if (DGV
&& NewGV
!= SGV
) {
990 C
= ConstantExpr::getPointerBitCastOrAddrSpaceCast(
991 NewGV
, TypeMap
.get(SGV
->getType()));
994 if (DGV
&& NewGV
!= DGV
) {
995 // Schedule "replace all uses with" to happen after materializing is
996 // done. It is not safe to do it now, since ValueMapper may be holding
997 // pointers to constants that will get deleted if RAUW runs.
998 RAUWWorklist
.push_back(std::make_pair(
1000 ConstantExpr::getPointerBitCastOrAddrSpaceCast(NewGV
, DGV
->getType())));
1006 /// Update the initializers in the Dest module now that all globals that may be
1007 /// referenced are in Dest.
1008 void IRLinker::linkGlobalVariable(GlobalVariable
&Dst
, GlobalVariable
&Src
) {
1009 // Figure out what the initializer looks like in the dest module.
1010 Mapper
.scheduleMapGlobalInitializer(Dst
, *Src
.getInitializer());
1013 /// Copy the source function over into the dest function and fix up references
1014 /// to values. At this point we know that Dest is an external function, and
1015 /// that Src is not.
1016 Error
IRLinker::linkFunctionBody(Function
&Dst
, Function
&Src
) {
1017 assert(Dst
.isDeclaration() && !Src
.isDeclaration());
1019 // Materialize if needed.
1020 if (Error Err
= Src
.materialize())
1023 // Link in the operands without remapping.
1024 if (Src
.hasPrefixData())
1025 Dst
.setPrefixData(Src
.getPrefixData());
1026 if (Src
.hasPrologueData())
1027 Dst
.setPrologueData(Src
.getPrologueData());
1028 if (Src
.hasPersonalityFn())
1029 Dst
.setPersonalityFn(Src
.getPersonalityFn());
1031 // Copy over the metadata attachments without remapping.
1032 Dst
.copyMetadata(&Src
, 0);
1034 // Steal arguments and splice the body of Src into Dst.
1035 Dst
.stealArgumentListFrom(Src
);
1036 Dst
.getBasicBlockList().splice(Dst
.end(), Src
.getBasicBlockList());
1038 // Everything has been moved over. Remap it.
1039 Mapper
.scheduleRemapFunction(Dst
);
1040 return Error::success();
1043 void IRLinker::linkAliasBody(GlobalAlias
&Dst
, GlobalAlias
&Src
) {
1044 Mapper
.scheduleMapGlobalAliasee(Dst
, *Src
.getAliasee(), AliasMCID
);
1047 Error
IRLinker::linkGlobalValueBody(GlobalValue
&Dst
, GlobalValue
&Src
) {
1048 if (auto *F
= dyn_cast
<Function
>(&Src
))
1049 return linkFunctionBody(cast
<Function
>(Dst
), *F
);
1050 if (auto *GVar
= dyn_cast
<GlobalVariable
>(&Src
)) {
1051 linkGlobalVariable(cast
<GlobalVariable
>(Dst
), *GVar
);
1052 return Error::success();
1054 linkAliasBody(cast
<GlobalAlias
>(Dst
), cast
<GlobalAlias
>(Src
));
1055 return Error::success();
1058 void IRLinker::flushRAUWWorklist() {
1059 for (const auto Elem
: RAUWWorklist
) {
1062 std::tie(Old
, New
) = Elem
;
1064 Old
->replaceAllUsesWith(New
);
1065 Old
->eraseFromParent();
1067 RAUWWorklist
.clear();
1070 void IRLinker::prepareCompileUnitsForImport() {
1071 NamedMDNode
*SrcCompileUnits
= SrcM
->getNamedMetadata("llvm.dbg.cu");
1072 if (!SrcCompileUnits
)
1074 // When importing for ThinLTO, prevent importing of types listed on
1075 // the DICompileUnit that we don't need a copy of in the importing
1076 // module. They will be emitted by the originating module.
1077 for (unsigned I
= 0, E
= SrcCompileUnits
->getNumOperands(); I
!= E
; ++I
) {
1078 auto *CU
= cast
<DICompileUnit
>(SrcCompileUnits
->getOperand(I
));
1079 assert(CU
&& "Expected valid compile unit");
1080 // Enums, macros, and retained types don't need to be listed on the
1081 // imported DICompileUnit. This means they will only be imported
1082 // if reached from the mapped IR. Do this by setting their value map
1083 // entries to nullptr, which will automatically prevent their importing
1084 // when reached from the DICompileUnit during metadata mapping.
1085 ValueMap
.MD()[CU
->getRawEnumTypes()].reset(nullptr);
1086 ValueMap
.MD()[CU
->getRawMacros()].reset(nullptr);
1087 ValueMap
.MD()[CU
->getRawRetainedTypes()].reset(nullptr);
1088 // The original definition (or at least its debug info - if the variable is
1089 // internalized an optimized away) will remain in the source module, so
1090 // there's no need to import them.
1091 // If LLVM ever does more advanced optimizations on global variables
1092 // (removing/localizing write operations, for instance) that can track
1093 // through debug info, this decision may need to be revisited - but do so
1094 // with care when it comes to debug info size. Emitting small CUs containing
1095 // only a few imported entities into every destination module may be very
1096 // size inefficient.
1097 ValueMap
.MD()[CU
->getRawGlobalVariables()].reset(nullptr);
1099 // Imported entities only need to be mapped in if they have local
1100 // scope, as those might correspond to an imported entity inside a
1101 // function being imported (any locally scoped imported entities that
1102 // don't end up referenced by an imported function will not be emitted
1103 // into the object). Imported entities not in a local scope
1104 // (e.g. on the namespace) only need to be emitted by the originating
1105 // module. Create a list of the locally scoped imported entities, and
1106 // replace the source CUs imported entity list with the new list, so
1107 // only those are mapped in.
1108 // FIXME: Locally-scoped imported entities could be moved to the
1109 // functions they are local to instead of listing them on the CU, and
1110 // we would naturally only link in those needed by function importing.
1111 SmallVector
<TrackingMDNodeRef
, 4> AllImportedModules
;
1112 bool ReplaceImportedEntities
= false;
1113 for (auto *IE
: CU
->getImportedEntities()) {
1114 DIScope
*Scope
= IE
->getScope();
1115 assert(Scope
&& "Invalid Scope encoding!");
1116 if (isa
<DILocalScope
>(Scope
))
1117 AllImportedModules
.emplace_back(IE
);
1119 ReplaceImportedEntities
= true;
1121 if (ReplaceImportedEntities
) {
1122 if (!AllImportedModules
.empty())
1123 CU
->replaceImportedEntities(MDTuple::get(
1125 SmallVector
<Metadata
*, 16>(AllImportedModules
.begin(),
1126 AllImportedModules
.end())));
1128 // If there were no local scope imported entities, we can map
1129 // the whole list to nullptr.
1130 ValueMap
.MD()[CU
->getRawImportedEntities()].reset(nullptr);
1135 /// Insert all of the named MDNodes in Src into the Dest module.
1136 void IRLinker::linkNamedMDNodes() {
1137 const NamedMDNode
*SrcModFlags
= SrcM
->getModuleFlagsMetadata();
1138 for (const NamedMDNode
&NMD
: SrcM
->named_metadata()) {
1139 // Don't link module flags here. Do them separately.
1140 if (&NMD
== SrcModFlags
)
1142 NamedMDNode
*DestNMD
= DstM
.getOrInsertNamedMetadata(NMD
.getName());
1143 // Add Src elements into Dest node.
1144 for (const MDNode
*Op
: NMD
.operands())
1145 DestNMD
->addOperand(Mapper
.mapMDNode(*Op
));
1149 /// Merge the linker flags in Src into the Dest module.
1150 Error
IRLinker::linkModuleFlagsMetadata() {
1151 // If the source module has no module flags, we are done.
1152 const NamedMDNode
*SrcModFlags
= SrcM
->getModuleFlagsMetadata();
1154 return Error::success();
1156 // If the destination module doesn't have module flags yet, then just copy
1157 // over the source module's flags.
1158 NamedMDNode
*DstModFlags
= DstM
.getOrInsertModuleFlagsMetadata();
1159 if (DstModFlags
->getNumOperands() == 0) {
1160 for (unsigned I
= 0, E
= SrcModFlags
->getNumOperands(); I
!= E
; ++I
)
1161 DstModFlags
->addOperand(SrcModFlags
->getOperand(I
));
1163 return Error::success();
1166 // First build a map of the existing module flags and requirements.
1167 DenseMap
<MDString
*, std::pair
<MDNode
*, unsigned>> Flags
;
1168 SmallSetVector
<MDNode
*, 16> Requirements
;
1169 for (unsigned I
= 0, E
= DstModFlags
->getNumOperands(); I
!= E
; ++I
) {
1170 MDNode
*Op
= DstModFlags
->getOperand(I
);
1171 ConstantInt
*Behavior
= mdconst::extract
<ConstantInt
>(Op
->getOperand(0));
1172 MDString
*ID
= cast
<MDString
>(Op
->getOperand(1));
1174 if (Behavior
->getZExtValue() == Module::Require
) {
1175 Requirements
.insert(cast
<MDNode
>(Op
->getOperand(2)));
1177 Flags
[ID
] = std::make_pair(Op
, I
);
1181 // Merge in the flags from the source module, and also collect its set of
1183 for (unsigned I
= 0, E
= SrcModFlags
->getNumOperands(); I
!= E
; ++I
) {
1184 MDNode
*SrcOp
= SrcModFlags
->getOperand(I
);
1185 ConstantInt
*SrcBehavior
=
1186 mdconst::extract
<ConstantInt
>(SrcOp
->getOperand(0));
1187 MDString
*ID
= cast
<MDString
>(SrcOp
->getOperand(1));
1190 std::tie(DstOp
, DstIndex
) = Flags
.lookup(ID
);
1191 unsigned SrcBehaviorValue
= SrcBehavior
->getZExtValue();
1193 // If this is a requirement, add it and continue.
1194 if (SrcBehaviorValue
== Module::Require
) {
1195 // If the destination module does not already have this requirement, add
1197 if (Requirements
.insert(cast
<MDNode
>(SrcOp
->getOperand(2)))) {
1198 DstModFlags
->addOperand(SrcOp
);
1203 // If there is no existing flag with this ID, just add it.
1205 Flags
[ID
] = std::make_pair(SrcOp
, DstModFlags
->getNumOperands());
1206 DstModFlags
->addOperand(SrcOp
);
1210 // Otherwise, perform a merge.
1211 ConstantInt
*DstBehavior
=
1212 mdconst::extract
<ConstantInt
>(DstOp
->getOperand(0));
1213 unsigned DstBehaviorValue
= DstBehavior
->getZExtValue();
1215 auto overrideDstValue
= [&]() {
1216 DstModFlags
->setOperand(DstIndex
, SrcOp
);
1217 Flags
[ID
].first
= SrcOp
;
1220 // If either flag has override behavior, handle it first.
1221 if (DstBehaviorValue
== Module::Override
) {
1222 // Diagnose inconsistent flags which both have override behavior.
1223 if (SrcBehaviorValue
== Module::Override
&&
1224 SrcOp
->getOperand(2) != DstOp
->getOperand(2))
1225 return stringErr("linking module flags '" + ID
->getString() +
1226 "': IDs have conflicting override values");
1228 } else if (SrcBehaviorValue
== Module::Override
) {
1229 // Update the destination flag to that of the source.
1234 // Diagnose inconsistent merge behavior types.
1235 if (SrcBehaviorValue
!= DstBehaviorValue
)
1236 return stringErr("linking module flags '" + ID
->getString() +
1237 "': IDs have conflicting behaviors");
1239 auto replaceDstValue
= [&](MDNode
*New
) {
1240 Metadata
*FlagOps
[] = {DstOp
->getOperand(0), ID
, New
};
1241 MDNode
*Flag
= MDNode::get(DstM
.getContext(), FlagOps
);
1242 DstModFlags
->setOperand(DstIndex
, Flag
);
1243 Flags
[ID
].first
= Flag
;
1246 // Perform the merge for standard behavior types.
1247 switch (SrcBehaviorValue
) {
1248 case Module::Require
:
1249 case Module::Override
:
1250 llvm_unreachable("not possible");
1251 case Module::Error
: {
1252 // Emit an error if the values differ.
1253 if (SrcOp
->getOperand(2) != DstOp
->getOperand(2))
1254 return stringErr("linking module flags '" + ID
->getString() +
1255 "': IDs have conflicting values");
1258 case Module::Warning
: {
1259 // Emit a warning if the values differ.
1260 if (SrcOp
->getOperand(2) != DstOp
->getOperand(2)) {
1262 raw_string_ostream(str
)
1263 << "linking module flags '" << ID
->getString()
1264 << "': IDs have conflicting values ('" << *SrcOp
->getOperand(2)
1265 << "' from " << SrcM
->getModuleIdentifier() << " with '"
1266 << *DstOp
->getOperand(2) << "' from " << DstM
.getModuleIdentifier()
1273 ConstantInt
*DstValue
=
1274 mdconst::extract
<ConstantInt
>(DstOp
->getOperand(2));
1275 ConstantInt
*SrcValue
=
1276 mdconst::extract
<ConstantInt
>(SrcOp
->getOperand(2));
1277 if (SrcValue
->getZExtValue() > DstValue
->getZExtValue())
1281 case Module::Append
: {
1282 MDNode
*DstValue
= cast
<MDNode
>(DstOp
->getOperand(2));
1283 MDNode
*SrcValue
= cast
<MDNode
>(SrcOp
->getOperand(2));
1284 SmallVector
<Metadata
*, 8> MDs
;
1285 MDs
.reserve(DstValue
->getNumOperands() + SrcValue
->getNumOperands());
1286 MDs
.append(DstValue
->op_begin(), DstValue
->op_end());
1287 MDs
.append(SrcValue
->op_begin(), SrcValue
->op_end());
1289 replaceDstValue(MDNode::get(DstM
.getContext(), MDs
));
1292 case Module::AppendUnique
: {
1293 SmallSetVector
<Metadata
*, 16> Elts
;
1294 MDNode
*DstValue
= cast
<MDNode
>(DstOp
->getOperand(2));
1295 MDNode
*SrcValue
= cast
<MDNode
>(SrcOp
->getOperand(2));
1296 Elts
.insert(DstValue
->op_begin(), DstValue
->op_end());
1297 Elts
.insert(SrcValue
->op_begin(), SrcValue
->op_end());
1299 replaceDstValue(MDNode::get(DstM
.getContext(),
1300 makeArrayRef(Elts
.begin(), Elts
.end())));
1306 // Check all of the requirements.
1307 for (unsigned I
= 0, E
= Requirements
.size(); I
!= E
; ++I
) {
1308 MDNode
*Requirement
= Requirements
[I
];
1309 MDString
*Flag
= cast
<MDString
>(Requirement
->getOperand(0));
1310 Metadata
*ReqValue
= Requirement
->getOperand(1);
1312 MDNode
*Op
= Flags
[Flag
].first
;
1313 if (!Op
|| Op
->getOperand(2) != ReqValue
)
1314 return stringErr("linking module flags '" + Flag
->getString() +
1315 "': does not have the required value");
1317 return Error::success();
1320 /// Return InlineAsm adjusted with target-specific directives if required.
1321 /// For ARM and Thumb, we have to add directives to select the appropriate ISA
1322 /// to support mixing module-level inline assembly from ARM and Thumb modules.
1323 static std::string
adjustInlineAsm(const std::string
&InlineAsm
,
1324 const Triple
&Triple
) {
1325 if (Triple
.getArch() == Triple::thumb
|| Triple
.getArch() == Triple::thumbeb
)
1326 return ".text\n.balign 2\n.thumb\n" + InlineAsm
;
1327 if (Triple
.getArch() == Triple::arm
|| Triple
.getArch() == Triple::armeb
)
1328 return ".text\n.balign 4\n.arm\n" + InlineAsm
;
1332 Error
IRLinker::run() {
1333 // Ensure metadata materialized before value mapping.
1334 if (SrcM
->getMaterializer())
1335 if (Error Err
= SrcM
->getMaterializer()->materializeMetadata())
1338 // Inherit the target data from the source module if the destination module
1339 // doesn't have one already.
1340 if (DstM
.getDataLayout().isDefault())
1341 DstM
.setDataLayout(SrcM
->getDataLayout());
1343 if (SrcM
->getDataLayout() != DstM
.getDataLayout()) {
1344 emitWarning("Linking two modules of different data layouts: '" +
1345 SrcM
->getModuleIdentifier() + "' is '" +
1346 SrcM
->getDataLayoutStr() + "' whereas '" +
1347 DstM
.getModuleIdentifier() + "' is '" +
1348 DstM
.getDataLayoutStr() + "'\n");
1351 // Copy the target triple from the source to dest if the dest's is empty.
1352 if (DstM
.getTargetTriple().empty() && !SrcM
->getTargetTriple().empty())
1353 DstM
.setTargetTriple(SrcM
->getTargetTriple());
1355 Triple
SrcTriple(SrcM
->getTargetTriple()), DstTriple(DstM
.getTargetTriple());
1357 if (!SrcM
->getTargetTriple().empty()&&
1358 !SrcTriple
.isCompatibleWith(DstTriple
))
1359 emitWarning("Linking two modules of different target triples: " +
1360 SrcM
->getModuleIdentifier() + "' is '" +
1361 SrcM
->getTargetTriple() + "' whereas '" +
1362 DstM
.getModuleIdentifier() + "' is '" + DstM
.getTargetTriple() +
1365 DstM
.setTargetTriple(SrcTriple
.merge(DstTriple
));
1367 // Append the module inline asm string.
1368 if (!IsPerformingImport
&& !SrcM
->getModuleInlineAsm().empty()) {
1369 std::string SrcModuleInlineAsm
= adjustInlineAsm(SrcM
->getModuleInlineAsm(),
1371 if (DstM
.getModuleInlineAsm().empty())
1372 DstM
.setModuleInlineAsm(SrcModuleInlineAsm
);
1374 DstM
.setModuleInlineAsm(DstM
.getModuleInlineAsm() + "\n" +
1375 SrcModuleInlineAsm
);
1378 // Loop over all of the linked values to compute type mappings.
1379 computeTypeMapping();
1381 std::reverse(Worklist
.begin(), Worklist
.end());
1382 while (!Worklist
.empty()) {
1383 GlobalValue
*GV
= Worklist
.back();
1384 Worklist
.pop_back();
1387 if (ValueMap
.find(GV
) != ValueMap
.end() ||
1388 AliasValueMap
.find(GV
) != AliasValueMap
.end())
1391 assert(!GV
->isDeclaration());
1392 Mapper
.mapValue(*GV
);
1394 return std::move(*FoundError
);
1395 flushRAUWWorklist();
1398 // Note that we are done linking global value bodies. This prevents
1399 // metadata linking from creating new references.
1400 DoneLinkingBodies
= true;
1401 Mapper
.addFlags(RF_NullMapMissingGlobalValues
);
1403 // Remap all of the named MDNodes in Src into the DstM module. We do this
1404 // after linking GlobalValues so that MDNodes that reference GlobalValues
1405 // are properly remapped.
1408 // Merge the module flags into the DstM module.
1409 return linkModuleFlagsMetadata();
1412 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef
<Type
*> E
, bool P
)
1413 : ETypes(E
), IsPacked(P
) {}
1415 IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType
*ST
)
1416 : ETypes(ST
->elements()), IsPacked(ST
->isPacked()) {}
1418 bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy
&That
) const {
1419 return IsPacked
== That
.IsPacked
&& ETypes
== That
.ETypes
;
1422 bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy
&That
) const {
1423 return !this->operator==(That
);
1426 StructType
*IRMover::StructTypeKeyInfo::getEmptyKey() {
1427 return DenseMapInfo
<StructType
*>::getEmptyKey();
1430 StructType
*IRMover::StructTypeKeyInfo::getTombstoneKey() {
1431 return DenseMapInfo
<StructType
*>::getTombstoneKey();
1434 unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy
&Key
) {
1435 return hash_combine(hash_combine_range(Key
.ETypes
.begin(), Key
.ETypes
.end()),
1439 unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType
*ST
) {
1440 return getHashValue(KeyTy(ST
));
1443 bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy
&LHS
,
1444 const StructType
*RHS
) {
1445 if (RHS
== getEmptyKey() || RHS
== getTombstoneKey())
1447 return LHS
== KeyTy(RHS
);
1450 bool IRMover::StructTypeKeyInfo::isEqual(const StructType
*LHS
,
1451 const StructType
*RHS
) {
1452 if (RHS
== getEmptyKey() || RHS
== getTombstoneKey())
1454 return KeyTy(LHS
) == KeyTy(RHS
);
1457 void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType
*Ty
) {
1458 assert(!Ty
->isOpaque());
1459 NonOpaqueStructTypes
.insert(Ty
);
1462 void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType
*Ty
) {
1463 assert(!Ty
->isOpaque());
1464 NonOpaqueStructTypes
.insert(Ty
);
1465 bool Removed
= OpaqueStructTypes
.erase(Ty
);
1470 void IRMover::IdentifiedStructTypeSet::addOpaque(StructType
*Ty
) {
1471 assert(Ty
->isOpaque());
1472 OpaqueStructTypes
.insert(Ty
);
1476 IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef
<Type
*> ETypes
,
1478 IRMover::StructTypeKeyInfo::KeyTy
Key(ETypes
, IsPacked
);
1479 auto I
= NonOpaqueStructTypes
.find_as(Key
);
1480 return I
== NonOpaqueStructTypes
.end() ? nullptr : *I
;
1483 bool IRMover::IdentifiedStructTypeSet::hasType(StructType
*Ty
) {
1485 return OpaqueStructTypes
.count(Ty
);
1486 auto I
= NonOpaqueStructTypes
.find(Ty
);
1487 return I
== NonOpaqueStructTypes
.end() ? false : *I
== Ty
;
1490 IRMover::IRMover(Module
&M
) : Composite(M
) {
1491 TypeFinder StructTypes
;
1492 StructTypes
.run(M
, /* OnlyNamed */ false);
1493 for (StructType
*Ty
: StructTypes
) {
1495 IdentifiedStructTypes
.addOpaque(Ty
);
1497 IdentifiedStructTypes
.addNonOpaque(Ty
);
1499 // Self-map metadatas in the destination module. This is needed when
1500 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1501 // destination module may be reached from the source module.
1502 for (auto *MD
: StructTypes
.getVisitedMetadata()) {
1503 SharedMDs
[MD
].reset(const_cast<MDNode
*>(MD
));
1507 Error
IRMover::move(
1508 std::unique_ptr
<Module
> Src
, ArrayRef
<GlobalValue
*> ValuesToLink
,
1509 std::function
<void(GlobalValue
&, ValueAdder Add
)> AddLazyFor
,
1510 bool IsPerformingImport
) {
1511 IRLinker
TheIRLinker(Composite
, SharedMDs
, IdentifiedStructTypes
,
1512 std::move(Src
), ValuesToLink
, std::move(AddLazyFor
),
1513 IsPerformingImport
);
1514 Error E
= TheIRLinker
.run();
1515 Composite
.dropTriviallyDeadConstantArrays();