LLVM 19.0.0git
IRMover.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
8
10#include "LinkDiagnosticInfo.h"
11#include "llvm/ADT/SetVector.h"
14#include "llvm/IR/AutoUpgrade.h"
15#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
20#include "llvm/IR/GlobalValue.h"
21#include "llvm/IR/Instruction.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/PseudoProbe.h"
26#include "llvm/IR/TypeFinder.h"
28#include "llvm/Support/Error.h"
29#include "llvm/Support/Path.h"
32#include <optional>
33#include <utility>
34using namespace llvm;
35
36//===----------------------------------------------------------------------===//
37// TypeMap implementation.
38//===----------------------------------------------------------------------===//
39
40namespace {
41class TypeMapTy : public ValueMapTypeRemapper {
42 /// This is a mapping from a source type to a destination type to use.
43 DenseMap<Type *, Type *> MappedTypes;
44
45 /// When checking to see if two subgraphs are isomorphic, we speculatively
46 /// add types to MappedTypes, but keep track of them here in case we need to
47 /// roll back.
48 SmallVector<Type *, 16> SpeculativeTypes;
49
50 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
51
52 /// This is a list of non-opaque structs in the source module that are mapped
53 /// to an opaque struct in the destination module.
54 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
55
56 /// This is the set of opaque types in the destination modules who are
57 /// getting a body from the source module.
58 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
59
60public:
61 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
62 : DstStructTypesSet(DstStructTypesSet) {}
63
64 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
65 /// Indicate that the specified type in the destination module is conceptually
66 /// equivalent to the specified type in the source module.
67 void addTypeMapping(Type *DstTy, Type *SrcTy);
68
69 /// Produce a body for an opaque type in the dest module from a type
70 /// definition in the source module.
71 void linkDefinedTypeBodies();
72
73 /// Return the mapped type to use for the specified input type from the
74 /// source module.
75 Type *get(Type *SrcTy);
76 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
77
78 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
79
81 return cast<FunctionType>(get((Type *)T));
82 }
83
84private:
85 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
86
87 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
88};
89}
90
91void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
92 assert(SpeculativeTypes.empty());
93 assert(SpeculativeDstOpaqueTypes.empty());
94
95 // Check to see if these types are recursively isomorphic and establish a
96 // mapping between them if so.
97 if (!areTypesIsomorphic(DstTy, SrcTy)) {
98 // Oops, they aren't isomorphic. Just discard this request by rolling out
99 // any speculative mappings we've established.
100 for (Type *Ty : SpeculativeTypes)
101 MappedTypes.erase(Ty);
102
103 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
104 SpeculativeDstOpaqueTypes.size());
105 for (StructType *Ty : SpeculativeDstOpaqueTypes)
106 DstResolvedOpaqueTypes.erase(Ty);
107 } else {
108 // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
109 // and all its descendants to lower amount of renaming in LLVM context
110 // Renaming occurs because we load all source modules to the same context
111 // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
112 // As a result we may get several different types in the destination
113 // module, which are in fact the same.
114 for (Type *Ty : SpeculativeTypes)
115 if (auto *STy = dyn_cast<StructType>(Ty))
116 if (STy->hasName())
117 STy->setName("");
118 }
119 SpeculativeTypes.clear();
120 SpeculativeDstOpaqueTypes.clear();
121}
122
123/// Recursively walk this pair of types, returning true if they are isomorphic,
124/// false if they are not.
125bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
126 // Two types with differing kinds are clearly not isomorphic.
127 if (DstTy->getTypeID() != SrcTy->getTypeID())
128 return false;
129
130 // If we have an entry in the MappedTypes table, then we have our answer.
131 Type *&Entry = MappedTypes[SrcTy];
132 if (Entry)
133 return Entry == DstTy;
134
135 // Two identical types are clearly isomorphic. Remember this
136 // non-speculatively.
137 if (DstTy == SrcTy) {
138 Entry = DstTy;
139 return true;
140 }
141
142 // Okay, we have two types with identical kinds that we haven't seen before.
143
144 // If this is an opaque struct type, special case it.
145 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
146 // Mapping an opaque type to any struct, just keep the dest struct.
147 if (SSTy->isOpaque()) {
148 Entry = DstTy;
149 SpeculativeTypes.push_back(SrcTy);
150 return true;
151 }
152
153 // Mapping a non-opaque source type to an opaque dest. If this is the first
154 // type that we're mapping onto this destination type then we succeed. Keep
155 // the dest, but fill it in later. If this is the second (different) type
156 // that we're trying to map onto the same opaque type then we fail.
157 if (cast<StructType>(DstTy)->isOpaque()) {
158 // We can only map one source type onto the opaque destination type.
159 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
160 return false;
161 SrcDefinitionsToResolve.push_back(SSTy);
162 SpeculativeTypes.push_back(SrcTy);
163 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
164 Entry = DstTy;
165 return true;
166 }
167 }
168
169 // If the number of subtypes disagree between the two types, then we fail.
170 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
171 return false;
172
173 // Fail if any of the extra properties (e.g. array size) of the type disagree.
174 if (isa<IntegerType>(DstTy))
175 return false; // bitwidth disagrees.
176 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
177 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
178 return false;
179 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
180 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
181 return false;
182 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
183 StructType *SSTy = cast<StructType>(SrcTy);
184 if (DSTy->isLiteral() != SSTy->isLiteral() ||
185 DSTy->isPacked() != SSTy->isPacked())
186 return false;
187 } else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
188 if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
189 return false;
190 } else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
191 if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
192 return false;
193 }
194
195 // Otherwise, we speculate that these two types will line up and recursively
196 // check the subelements.
197 Entry = DstTy;
198 SpeculativeTypes.push_back(SrcTy);
199
200 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
201 if (!areTypesIsomorphic(DstTy->getContainedType(I),
202 SrcTy->getContainedType(I)))
203 return false;
204
205 // If everything seems to have lined up, then everything is great.
206 return true;
207}
208
209void TypeMapTy::linkDefinedTypeBodies() {
211 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
212 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
213 assert(DstSTy->isOpaque());
214
215 // Map the body of the source type over to a new body for the dest type.
216 Elements.resize(SrcSTy->getNumElements());
217 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
218 Elements[I] = get(SrcSTy->getElementType(I));
219
220 DstSTy->setBody(Elements, SrcSTy->isPacked());
221 DstStructTypesSet.switchToNonOpaque(DstSTy);
222 }
223 SrcDefinitionsToResolve.clear();
224 DstResolvedOpaqueTypes.clear();
225}
226
227void TypeMapTy::finishType(StructType *DTy, StructType *STy,
228 ArrayRef<Type *> ETypes) {
229 DTy->setBody(ETypes, STy->isPacked());
230
231 // Steal STy's name.
232 if (STy->hasName()) {
233 SmallString<16> TmpName = STy->getName();
234 STy->setName("");
235 DTy->setName(TmpName);
236 }
237
238 DstStructTypesSet.addNonOpaque(DTy);
239}
240
241Type *TypeMapTy::get(Type *Ty) {
243 return get(Ty, Visited);
244}
245
246Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
247 // If we already have an entry for this type, return it.
248 Type **Entry = &MappedTypes[Ty];
249 if (*Entry)
250 return *Entry;
251
252 // These are types that LLVM itself will unique.
253 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
254
255 if (!IsUniqued) {
256#ifndef NDEBUG
257 for (auto &Pair : MappedTypes) {
258 assert(!(Pair.first != Ty && Pair.second == Ty) &&
259 "mapping to a source type");
260 }
261#endif
262
263 if (!Visited.insert(cast<StructType>(Ty)).second) {
265 return *Entry = DTy;
266 }
267 }
268
269 // If this is not a recursive type, then just map all of the elements and
270 // then rebuild the type from inside out.
271 SmallVector<Type *, 4> ElementTypes;
272
273 // If there are no element types to map, then the type is itself. This is
274 // true for the anonymous {} struct, things like 'float', integers, etc.
275 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
276 return *Entry = Ty;
277
278 // Remap all of the elements, keeping track of whether any of them change.
279 bool AnyChange = false;
280 ElementTypes.resize(Ty->getNumContainedTypes());
281 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
282 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
283 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
284 }
285
286 // If we found our type while recursively processing stuff, just use it.
287 Entry = &MappedTypes[Ty];
288 if (*Entry) {
289 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
290 if (DTy->isOpaque()) {
291 auto *STy = cast<StructType>(Ty);
292 finishType(DTy, STy, ElementTypes);
293 }
294 }
295 return *Entry;
296 }
297
298 // If all of the element types mapped directly over and the type is not
299 // a named struct, then the type is usable as-is.
300 if (!AnyChange && IsUniqued)
301 return *Entry = Ty;
302
303 // Otherwise, rebuild a modified type.
304 switch (Ty->getTypeID()) {
305 default:
306 llvm_unreachable("unknown derived type to remap");
307 case Type::ArrayTyID:
308 return *Entry = ArrayType::get(ElementTypes[0],
309 cast<ArrayType>(Ty)->getNumElements());
312 return *Entry = VectorType::get(ElementTypes[0],
313 cast<VectorType>(Ty)->getElementCount());
315 return *Entry = PointerType::get(ElementTypes[0],
316 cast<PointerType>(Ty)->getAddressSpace());
318 return *Entry = FunctionType::get(ElementTypes[0],
319 ArrayRef(ElementTypes).slice(1),
320 cast<FunctionType>(Ty)->isVarArg());
321 case Type::StructTyID: {
322 auto *STy = cast<StructType>(Ty);
323 bool IsPacked = STy->isPacked();
324 if (IsUniqued)
325 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
326
327 // If the type is opaque, we can just use it directly.
328 if (STy->isOpaque()) {
329 DstStructTypesSet.addOpaque(STy);
330 return *Entry = Ty;
331 }
332
333 if (StructType *OldT =
334 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
335 STy->setName("");
336 return *Entry = OldT;
337 }
338
339 if (!AnyChange) {
340 DstStructTypesSet.addNonOpaque(STy);
341 return *Entry = Ty;
342 }
343
345 finishType(DTy, STy, ElementTypes);
346 return *Entry = DTy;
347 }
348 }
349}
350
352 const Twine &Msg)
353 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
354void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
355
356//===----------------------------------------------------------------------===//
357// IRLinker implementation.
358//===----------------------------------------------------------------------===//
359
360namespace {
361class IRLinker;
362
363/// Creates prototypes for functions that are lazily linked on the fly. This
364/// speeds up linking for modules with many/ lazily linked functions of which
365/// few get used.
366class GlobalValueMaterializer final : public ValueMaterializer {
367 IRLinker &TheIRLinker;
368
369public:
370 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
371 Value *materialize(Value *V) override;
372};
373
374class LocalValueMaterializer final : public ValueMaterializer {
375 IRLinker &TheIRLinker;
376
377public:
378 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
379 Value *materialize(Value *V) override;
380};
381
382/// Type of the Metadata map in \a ValueToValueMapTy.
384
385/// This is responsible for keeping track of the state used for moving data
386/// from SrcM to DstM.
387class IRLinker {
388 Module &DstM;
389 std::unique_ptr<Module> SrcM;
390
391 /// See IRMover::move().
392 IRMover::LazyCallback AddLazyFor;
393
394 TypeMapTy TypeMap;
395 GlobalValueMaterializer GValMaterializer;
396 LocalValueMaterializer LValMaterializer;
397
398 /// A metadata map that's shared between IRLinker instances.
399 MDMapT &SharedMDs;
400
401 /// Mapping of values from what they used to be in Src, to what they are now
402 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
403 /// due to the use of Value handles which the Linker doesn't actually need,
404 /// but this allows us to reuse the ValueMapper code.
406 ValueToValueMapTy IndirectSymbolValueMap;
407
408 DenseSet<GlobalValue *> ValuesToLink;
409 std::vector<GlobalValue *> Worklist;
410 std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
411
412 /// Set of globals with eagerly copied metadata that may require remapping.
413 /// This remapping is performed after metadata linking.
414 DenseSet<GlobalObject *> UnmappedMetadata;
415
416 void maybeAdd(GlobalValue *GV) {
417 if (ValuesToLink.insert(GV).second)
418 Worklist.push_back(GV);
419 }
420
421 /// Whether we are importing globals for ThinLTO, as opposed to linking the
422 /// source module. If this flag is set, it means that we can rely on some
423 /// other object file to define any non-GlobalValue entities defined by the
424 /// source module. This currently causes us to not link retained types in
425 /// debug info metadata and module inline asm.
426 bool IsPerformingImport;
427
428 /// Set to true when all global value body linking is complete (including
429 /// lazy linking). Used to prevent metadata linking from creating new
430 /// references.
431 bool DoneLinkingBodies = false;
432
433 /// The Error encountered during materialization. We use an Optional here to
434 /// avoid needing to manage an unconsumed success value.
435 std::optional<Error> FoundError;
436 void setError(Error E) {
437 if (E)
438 FoundError = std::move(E);
439 }
440
441 /// Most of the errors produced by this module are inconvertible StringErrors.
442 /// This convenience function lets us return one of those more easily.
443 Error stringErr(const Twine &T) {
444 return make_error<StringError>(T, inconvertibleErrorCode());
445 }
446
447 /// Entry point for mapping values and alternate context for mapping aliases.
448 ValueMapper Mapper;
449 unsigned IndirectSymbolMCID;
450
451 /// Handles cloning of a global values from the source module into
452 /// the destination module, including setting the attributes and visibility.
453 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
454
455 void emitWarning(const Twine &Message) {
456 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
457 }
458
459 /// Given a global in the source module, return the global in the
460 /// destination module that is being linked to, if any.
461 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
462 // If the source has no name it can't link. If it has local linkage,
463 // there is no name match-up going on.
464 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
465 return nullptr;
466
467 // Otherwise see if we have a match in the destination module's symtab.
468 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
469 if (!DGV)
470 return nullptr;
471
472 // If we found a global with the same name in the dest module, but it has
473 // internal linkage, we are really not doing any linkage here.
474 if (DGV->hasLocalLinkage())
475 return nullptr;
476
477 // If we found an intrinsic declaration with mismatching prototypes, we
478 // probably had a nameclash. Don't use that version.
479 if (auto *FDGV = dyn_cast<Function>(DGV))
480 if (FDGV->isIntrinsic())
481 if (const auto *FSrcGV = dyn_cast<Function>(SrcGV))
482 if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
483 return nullptr;
484
485 // Otherwise, we do in fact link to the destination global.
486 return DGV;
487 }
488
489 void computeTypeMapping();
490
491 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
492 const GlobalVariable *SrcGV);
493
494 /// Given the GlobaValue \p SGV in the source module, and the matching
495 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
496 /// into the destination module.
497 ///
498 /// Note this code may call the client-provided \p AddLazyFor.
499 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
500 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
501 bool ForIndirectSymbol);
502
503 Error linkModuleFlagsMetadata();
504
505 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
506 Error linkFunctionBody(Function &Dst, Function &Src);
507 void linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src);
508 void linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src);
509 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
510
511 /// Replace all types in the source AttributeList with the
512 /// corresponding destination type.
513 AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
514
515 /// Functions that take care of cloning a specific global value type
516 /// into the destination module.
517 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
518 Function *copyFunctionProto(const Function *SF);
519 GlobalValue *copyIndirectSymbolProto(const GlobalValue *SGV);
520
521 /// Perform "replace all uses with" operations. These work items need to be
522 /// performed as part of materialization, but we postpone them to happen after
523 /// materialization is done. The materializer called by ValueMapper is not
524 /// expected to delete constants, as ValueMapper is holding pointers to some
525 /// of them, but constant destruction may be indirectly triggered by RAUW.
526 /// Hence, the need to move this out of the materialization call chain.
527 void flushRAUWWorklist();
528
529 /// When importing for ThinLTO, prevent importing of types listed on
530 /// the DICompileUnit that we don't need a copy of in the importing
531 /// module.
532 void prepareCompileUnitsForImport();
533 void linkNamedMDNodes();
534
535 /// Update attributes while linking.
536 void updateAttributes(GlobalValue &GV);
537
538public:
539 IRLinker(Module &DstM, MDMapT &SharedMDs,
540 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
541 ArrayRef<GlobalValue *> ValuesToLink,
542 IRMover::LazyCallback AddLazyFor, bool IsPerformingImport)
543 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
544 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
545 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
547 &TypeMap, &GValMaterializer),
548 IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
549 IndirectSymbolValueMap, &LValMaterializer)) {
550 ValueMap.getMDMap() = std::move(SharedMDs);
551 for (GlobalValue *GV : ValuesToLink)
552 maybeAdd(GV);
553 if (IsPerformingImport)
554 prepareCompileUnitsForImport();
555 }
556 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
557
558 Error run();
559 Value *materialize(Value *V, bool ForIndirectSymbol);
560};
561}
562
563/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
564/// table. This is good for all clients except for us. Go through the trouble
565/// to force this back.
567 // If the global doesn't force its name or if it already has the right name,
568 // there is nothing for us to do.
569 if (GV->hasLocalLinkage() || GV->getName() == Name)
570 return;
571
572 Module *M = GV->getParent();
573
574 // If there is a conflict, rename the conflict.
575 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
576 GV->takeName(ConflictGV);
577 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
578 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
579 } else {
580 GV->setName(Name); // Force the name back
581 }
582}
583
584Value *GlobalValueMaterializer::materialize(Value *SGV) {
585 return TheIRLinker.materialize(SGV, false);
586}
587
588Value *LocalValueMaterializer::materialize(Value *SGV) {
589 return TheIRLinker.materialize(SGV, true);
590}
591
592Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
593 auto *SGV = dyn_cast<GlobalValue>(V);
594 if (!SGV)
595 return nullptr;
596
597 // When linking a global from other modules than source & dest, skip
598 // materializing it because it would be mapped later when its containing
599 // module is linked. Linking it now would potentially pull in many types that
600 // may not be mapped properly.
601 if (SGV->getParent() != &DstM && SGV->getParent() != SrcM.get())
602 return nullptr;
603
604 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
605 if (!NewProto) {
606 setError(NewProto.takeError());
607 return nullptr;
608 }
609 if (!*NewProto)
610 return nullptr;
611
612 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
613 if (!New)
614 return *NewProto;
615
616 // If we already created the body, just return.
617 if (auto *F = dyn_cast<Function>(New)) {
618 if (!F->isDeclaration())
619 return New;
620 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
621 if (V->hasInitializer() || V->hasAppendingLinkage())
622 return New;
623 } else if (auto *GA = dyn_cast<GlobalAlias>(New)) {
624 if (GA->getAliasee())
625 return New;
626 } else if (auto *GI = dyn_cast<GlobalIFunc>(New)) {
627 if (GI->getResolver())
628 return New;
629 } else {
630 llvm_unreachable("Invalid GlobalValue type");
631 }
632
633 // If the global is being linked for an indirect symbol, it may have already
634 // been scheduled to satisfy a regular symbol. Similarly, a global being linked
635 // for a regular symbol may have already been scheduled for an indirect
636 // symbol. Check for these cases by looking in the other value map and
637 // confirming the same value has been scheduled. If there is an entry in the
638 // ValueMap but the value is different, it means that the value already had a
639 // definition in the destination module (linkonce for instance), but we need a
640 // new definition for the indirect symbol ("New" will be different).
641 if ((ForIndirectSymbol && ValueMap.lookup(SGV) == New) ||
642 (!ForIndirectSymbol && IndirectSymbolValueMap.lookup(SGV) == New))
643 return New;
644
645 if (ForIndirectSymbol || shouldLink(New, *SGV))
646 setError(linkGlobalValueBody(*New, *SGV));
647
648 updateAttributes(*New);
649 return New;
650}
651
652/// Loop through the global variables in the src module and merge them into the
653/// dest module.
654GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
655 // No linking to be performed or linking from the source: simply create an
656 // identical version of the symbol over in the dest module... the
657 // initializer will be filled in later by LinkGlobalInits.
658 GlobalVariable *NewDGV =
659 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
661 /*init*/ nullptr, SGVar->getName(),
662 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
663 SGVar->getAddressSpace());
664 NewDGV->setAlignment(SGVar->getAlign());
665 NewDGV->copyAttributesFrom(SGVar);
666 return NewDGV;
667}
668
669AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
670 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
671 for (int AttrIdx = Attribute::FirstTypeAttr;
672 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
673 Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
674 if (Attrs.hasAttributeAtIndex(i, TypedAttr)) {
675 if (Type *Ty =
676 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
677 Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
678 TypeMap.get(Ty));
679 break;
680 }
681 }
682 }
683 }
684 return Attrs;
685}
686
687/// Link the function in the source module into the destination module if
688/// needed, setting up mapping information.
689Function *IRLinker::copyFunctionProto(const Function *SF) {
690 // If there is no linkage to be performed or we are linking from the source,
691 // bring SF over.
692 auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
694 SF->getAddressSpace(), SF->getName(), &DstM);
695 F->copyAttributesFrom(SF);
696 F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
697 F->IsNewDbgInfoFormat = SF->IsNewDbgInfoFormat;
698 return F;
699}
700
701/// Set up prototypes for any indirect symbols that come over from the source
702/// module.
703GlobalValue *IRLinker::copyIndirectSymbolProto(const GlobalValue *SGV) {
704 // If there is no linkage to be performed or we're linking from the source,
705 // bring over SGA.
706 auto *Ty = TypeMap.get(SGV->getValueType());
707
708 if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
709 auto *DGA = GlobalAlias::create(Ty, SGV->getAddressSpace(),
711 SGV->getName(), &DstM);
712 DGA->copyAttributesFrom(GA);
713 return DGA;
714 }
715
716 if (auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
717 auto *DGI = GlobalIFunc::create(Ty, SGV->getAddressSpace(),
719 SGV->getName(), nullptr, &DstM);
720 DGI->copyAttributesFrom(GI);
721 return DGI;
722 }
723
724 llvm_unreachable("Invalid source global value type");
725}
726
727GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
728 bool ForDefinition) {
729 GlobalValue *NewGV;
730 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
731 NewGV = copyGlobalVariableProto(SGVar);
732 } else if (auto *SF = dyn_cast<Function>(SGV)) {
733 NewGV = copyFunctionProto(SF);
734 } else {
735 if (ForDefinition)
736 NewGV = copyIndirectSymbolProto(SGV);
737 else if (SGV->getValueType()->isFunctionTy())
738 NewGV =
739 Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
741 SGV->getName(), &DstM);
742 else
743 NewGV =
744 new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
745 /*isConstant*/ false, GlobalValue::ExternalLinkage,
746 /*init*/ nullptr, SGV->getName(),
747 /*insertbefore*/ nullptr,
748 SGV->getThreadLocalMode(), SGV->getAddressSpace());
749 }
750
751 if (ForDefinition)
752 NewGV->setLinkage(SGV->getLinkage());
753 else if (SGV->hasExternalWeakLinkage())
755
756 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
757 // Metadata for global variables and function declarations is copied eagerly.
758 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration()) {
759 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
760 if (SGV->isDeclaration() && NewGO->hasMetadata())
761 UnmappedMetadata.insert(NewGO);
762 }
763 }
764
765 // Remove these copied constants in case this stays a declaration, since
766 // they point to the source module. If the def is linked the values will
767 // be mapped in during linkFunctionBody.
768 if (auto *NewF = dyn_cast<Function>(NewGV)) {
769 NewF->setPersonalityFn(nullptr);
770 NewF->setPrefixData(nullptr);
771 NewF->setPrologueData(nullptr);
772 }
773
774 return NewGV;
775}
776
778 size_t DotPos = Name.rfind('.');
779 return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
780 !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
781 ? Name
782 : Name.substr(0, DotPos);
783}
784
785/// Loop over all of the linked values to compute type mappings. For example,
786/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
787/// types 'Foo' but one got renamed when the module was loaded into the same
788/// LLVMContext.
789void IRLinker::computeTypeMapping() {
790 for (GlobalValue &SGV : SrcM->globals()) {
791 GlobalValue *DGV = getLinkedToGlobal(&SGV);
792 if (!DGV)
793 continue;
794
795 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
796 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
797 continue;
798 }
799
800 // Unify the element type of appending arrays.
801 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
802 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
803 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
804 }
805
806 for (GlobalValue &SGV : *SrcM)
807 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
808 if (DGV->getType() == SGV.getType()) {
809 // If the types of DGV and SGV are the same, it means that DGV is from
810 // the source module and got added to DstM from a shared metadata. We
811 // shouldn't map this type to itself in case the type's components get
812 // remapped to a new type from DstM (for instance, during the loop over
813 // SrcM->getIdentifiedStructTypes() below).
814 continue;
815 }
816
817 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
818 }
819
820 for (GlobalValue &SGV : SrcM->aliases())
821 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
822 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
823
824 // Incorporate types by name, scanning all the types in the source module.
825 // At this point, the destination module may have a type "%foo = { i32 }" for
826 // example. When the source module got loaded into the same LLVMContext, if
827 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
828 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
829 for (StructType *ST : Types) {
830 if (!ST->hasName())
831 continue;
832
833 if (TypeMap.DstStructTypesSet.hasType(ST)) {
834 // This is actually a type from the destination module.
835 // getIdentifiedStructTypes() can have found it by walking debug info
836 // metadata nodes, some of which get linked by name when ODR Type Uniquing
837 // is enabled on the Context, from the source to the destination module.
838 continue;
839 }
840
841 auto STTypePrefix = getTypeNamePrefix(ST->getName());
842 if (STTypePrefix.size() == ST->getName().size())
843 continue;
844
845 // Check to see if the destination module has a struct with the prefix name.
846 StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
847 if (!DST)
848 continue;
849
850 // Don't use it if this actually came from the source module. They're in
851 // the same LLVMContext after all. Also don't use it unless the type is
852 // actually used in the destination module. This can happen in situations
853 // like this:
854 //
855 // Module A Module B
856 // -------- --------
857 // %Z = type { %A } %B = type { %C.1 }
858 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
859 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
860 // %C = type { i8* } %B.3 = type { %C.1 }
861 //
862 // When we link Module B with Module A, the '%B' in Module B is
863 // used. However, that would then use '%C.1'. But when we process '%C.1',
864 // we prefer to take the '%C' version. So we are then left with both
865 // '%C.1' and '%C' being used for the same types. This leads to some
866 // variables using one type and some using the other.
867 if (TypeMap.DstStructTypesSet.hasType(DST))
868 TypeMap.addTypeMapping(DST, ST);
869 }
870
871 // Now that we have discovered all of the type equivalences, get a body for
872 // any 'opaque' types in the dest module that are now resolved.
873 TypeMap.linkDefinedTypeBodies();
874}
875
876static void getArrayElements(const Constant *C,
878 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
879
880 for (unsigned i = 0; i != NumElements; ++i)
881 Dest.push_back(C->getAggregateElement(i));
882}
883
884/// If there were any appending global variables, link them together now.
886IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
887 const GlobalVariable *SrcGV) {
888 // Check that both variables have compatible properties.
889 if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
890 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
891 return stringErr(
892 "Linking globals named '" + SrcGV->getName() +
893 "': can only link appending global with another appending "
894 "global!");
895
896 if (DstGV->isConstant() != SrcGV->isConstant())
897 return stringErr("Appending variables linked with different const'ness!");
898
899 if (DstGV->getAlign() != SrcGV->getAlign())
900 return stringErr(
901 "Appending variables with different alignment need to be linked!");
902
903 if (DstGV->getVisibility() != SrcGV->getVisibility())
904 return stringErr(
905 "Appending variables with different visibility need to be linked!");
906
907 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
908 return stringErr(
909 "Appending variables with different unnamed_addr need to be linked!");
910
911 if (DstGV->getSection() != SrcGV->getSection())
912 return stringErr(
913 "Appending variables with different section name need to be linked!");
914
915 if (DstGV->getAddressSpace() != SrcGV->getAddressSpace())
916 return stringErr("Appending variables with different address spaces need "
917 "to be linked!");
918 }
919
920 // Do not need to do anything if source is a declaration.
921 if (SrcGV->isDeclaration())
922 return DstGV;
923
924 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
925 ->getElementType();
926
927 // FIXME: This upgrade is done during linking to support the C API. Once the
928 // old form is deprecated, we should move this upgrade to
929 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
930 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
931 StringRef Name = SrcGV->getName();
932 bool IsNewStructor = false;
933 bool IsOldStructor = false;
934 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
935 if (cast<StructType>(EltTy)->getNumElements() == 3)
936 IsNewStructor = true;
937 else
938 IsOldStructor = true;
939 }
940
941 PointerType *VoidPtrTy = PointerType::get(SrcGV->getContext(), 0);
942 if (IsOldStructor) {
943 auto &ST = *cast<StructType>(EltTy);
944 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
945 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
946 }
947
948 uint64_t DstNumElements = 0;
949 if (DstGV && !DstGV->isDeclaration()) {
950 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
951 DstNumElements = DstTy->getNumElements();
952
953 // Check to see that they two arrays agree on type.
954 if (EltTy != DstTy->getElementType())
955 return stringErr("Appending variables with different element types!");
956 }
957
958 SmallVector<Constant *, 16> SrcElements;
959 getArrayElements(SrcGV->getInitializer(), SrcElements);
960
961 if (IsNewStructor) {
962 erase_if(SrcElements, [this](Constant *E) {
963 auto *Key =
964 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
965 if (!Key)
966 return false;
967 GlobalValue *DGV = getLinkedToGlobal(Key);
968 return !shouldLink(DGV, *Key);
969 });
970 }
971 uint64_t NewSize = DstNumElements + SrcElements.size();
972 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
973
974 // Create the new global variable.
976 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
977 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
978 SrcGV->getAddressSpace());
979
980 NG->copyAttributesFrom(SrcGV);
981 forceRenaming(NG, SrcGV->getName());
982
983 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
984
986 *NG,
987 (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
988 IsOldStructor, SrcElements);
989
990 // Replace any uses of the two global variables with uses of the new
991 // global.
992 if (DstGV) {
993 RAUWWorklist.push_back(std::make_pair(DstGV, NG));
994 }
995
996 return Ret;
997}
998
999bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
1000 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
1001 return true;
1002
1003 if (DGV && !DGV->isDeclarationForLinker())
1004 return false;
1005
1006 if (SGV.isDeclaration() || DoneLinkingBodies)
1007 return false;
1008
1009 // Callback to the client to give a chance to lazily add the Global to the
1010 // list of value to link.
1011 bool LazilyAdded = false;
1012 if (AddLazyFor)
1013 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
1014 maybeAdd(&GV);
1015 LazilyAdded = true;
1016 });
1017 return LazilyAdded;
1018}
1019
1020Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
1021 bool ForIndirectSymbol) {
1022 GlobalValue *DGV = getLinkedToGlobal(SGV);
1023
1024 bool ShouldLink = shouldLink(DGV, *SGV);
1025
1026 // just missing from map
1027 if (ShouldLink) {
1028 auto I = ValueMap.find(SGV);
1029 if (I != ValueMap.end())
1030 return cast<Constant>(I->second);
1031
1032 I = IndirectSymbolValueMap.find(SGV);
1033 if (I != IndirectSymbolValueMap.end())
1034 return cast<Constant>(I->second);
1035 }
1036
1037 if (!ShouldLink && ForIndirectSymbol)
1038 DGV = nullptr;
1039
1040 // Handle the ultra special appending linkage case first.
1041 if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
1042 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1043 cast<GlobalVariable>(SGV));
1044
1045 bool NeedsRenaming = false;
1046 GlobalValue *NewGV;
1047 if (DGV && !ShouldLink) {
1048 NewGV = DGV;
1049 } else {
1050 // If we are done linking global value bodies (i.e. we are performing
1051 // metadata linking), don't link in the global value due to this
1052 // reference, simply map it to null.
1053 if (DoneLinkingBodies)
1054 return nullptr;
1055
1056 NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1057 if (ShouldLink || !ForIndirectSymbol)
1058 NeedsRenaming = true;
1059 }
1060
1061 // Overloaded intrinsics have overloaded types names as part of their
1062 // names. If we renamed overloaded types we should rename the intrinsic
1063 // as well.
1064 if (Function *F = dyn_cast<Function>(NewGV))
1065 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
1066 // Note: remangleIntrinsicFunction does not copy metadata and as such
1067 // F should not occur in the set of objects with unmapped metadata.
1068 // If this assertion fails then remangleIntrinsicFunction needs updating.
1069 assert(!UnmappedMetadata.count(F) && "intrinsic has unmapped metadata");
1070 NewGV->eraseFromParent();
1071 NewGV = *Remangled;
1072 NeedsRenaming = false;
1073 }
1074
1075 if (NeedsRenaming)
1076 forceRenaming(NewGV, SGV->getName());
1077
1078 if (ShouldLink || ForIndirectSymbol) {
1079 if (const Comdat *SC = SGV->getComdat()) {
1080 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1081 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1082 DC->setSelectionKind(SC->getSelectionKind());
1083 GO->setComdat(DC);
1084 }
1085 }
1086 }
1087
1088 if (!ShouldLink && ForIndirectSymbol)
1090
1091 Constant *C = NewGV;
1092 // Only create a bitcast if necessary. In particular, with
1093 // DebugTypeODRUniquing we may reach metadata in the destination module
1094 // containing a GV from the source module, in which case SGV will be
1095 // the same as DGV and NewGV, and TypeMap.get() will assert since it
1096 // assumes it is being invoked on a type in the source module.
1097 if (DGV && NewGV != SGV) {
1099 NewGV, TypeMap.get(SGV->getType()));
1100 }
1101
1102 if (DGV && NewGV != DGV) {
1103 // Schedule "replace all uses with" to happen after materializing is
1104 // done. It is not safe to do it now, since ValueMapper may be holding
1105 // pointers to constants that will get deleted if RAUW runs.
1106 RAUWWorklist.push_back(std::make_pair(
1107 DGV,
1109 }
1110
1111 return C;
1112}
1113
1114/// Update the initializers in the Dest module now that all globals that may be
1115/// referenced are in Dest.
1116void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
1117 // Figure out what the initializer looks like in the dest module.
1118 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
1119}
1120
1121/// Copy the source function over into the dest function and fix up references
1122/// to values. At this point we know that Dest is an external function, and
1123/// that Src is not.
1124Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1125 assert(Dst.isDeclaration() && !Src.isDeclaration());
1126
1127 // Materialize if needed.
1128 if (Error Err = Src.materialize())
1129 return Err;
1130
1131 // Link in the operands without remapping.
1132 if (Src.hasPrefixData())
1133 Dst.setPrefixData(Src.getPrefixData());
1134 if (Src.hasPrologueData())
1135 Dst.setPrologueData(Src.getPrologueData());
1136 if (Src.hasPersonalityFn())
1137 Dst.setPersonalityFn(Src.getPersonalityFn());
1138 assert(Src.IsNewDbgInfoFormat == Dst.IsNewDbgInfoFormat);
1139
1140 // Copy over the metadata attachments without remapping.
1141 Dst.copyMetadata(&Src, 0);
1142
1143 // Steal arguments and splice the body of Src into Dst.
1144 Dst.stealArgumentListFrom(Src);
1145 Dst.splice(Dst.end(), &Src);
1146
1147 // Everything has been moved over. Remap it.
1148 Mapper.scheduleRemapFunction(Dst);
1149 return Error::success();
1150}
1151
1152void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
1153 Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
1154}
1155
1156void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
1157 Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
1158}
1159
1160Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1161 if (auto *F = dyn_cast<Function>(&Src))
1162 return linkFunctionBody(cast<Function>(Dst), *F);
1163 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1164 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
1165 return Error::success();
1166 }
1167 if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
1168 linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
1169 return Error::success();
1170 }
1171 linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
1172 return Error::success();
1173}
1174
1175void IRLinker::flushRAUWWorklist() {
1176 for (const auto &Elem : RAUWWorklist) {
1177 GlobalValue *Old;
1178 Value *New;
1179 std::tie(Old, New) = Elem;
1180
1181 Old->replaceAllUsesWith(New);
1182 Old->eraseFromParent();
1183 }
1184 RAUWWorklist.clear();
1185}
1186
1187void IRLinker::prepareCompileUnitsForImport() {
1188 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
1189 if (!SrcCompileUnits)
1190 return;
1191 // When importing for ThinLTO, prevent importing of types listed on
1192 // the DICompileUnit that we don't need a copy of in the importing
1193 // module. They will be emitted by the originating module.
1194 for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) {
1195 auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I));
1196 assert(CU && "Expected valid compile unit");
1197 // Enums, macros, and retained types don't need to be listed on the
1198 // imported DICompileUnit. This means they will only be imported
1199 // if reached from the mapped IR.
1200 CU->replaceEnumTypes(nullptr);
1201 CU->replaceMacros(nullptr);
1202 CU->replaceRetainedTypes(nullptr);
1203
1204 // The original definition (or at least its debug info - if the variable is
1205 // internalized and optimized away) will remain in the source module, so
1206 // there's no need to import them.
1207 // If LLVM ever does more advanced optimizations on global variables
1208 // (removing/localizing write operations, for instance) that can track
1209 // through debug info, this decision may need to be revisited - but do so
1210 // with care when it comes to debug info size. Emitting small CUs containing
1211 // only a few imported entities into every destination module may be very
1212 // size inefficient.
1213 CU->replaceGlobalVariables(nullptr);
1214
1215 CU->replaceImportedEntities(nullptr);
1216 }
1217}
1218
1219/// Insert all of the named MDNodes in Src into the Dest module.
1220void IRLinker::linkNamedMDNodes() {
1221 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1222 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1223 // Don't link module flags here. Do them separately.
1224 if (&NMD == SrcModFlags)
1225 continue;
1226 // Don't import pseudo probe descriptors here for thinLTO. They will be
1227 // emitted by the originating module.
1228 if (IsPerformingImport && NMD.getName() == PseudoProbeDescMetadataName) {
1229 if (!DstM.getNamedMetadata(NMD.getName()))
1230 emitWarning("Pseudo-probe ignored: source module '" +
1231 SrcM->getModuleIdentifier() +
1232 "' is compiled with -fpseudo-probe-for-profiling while "
1233 "destination module '" +
1234 DstM.getModuleIdentifier() + "' is not\n");
1235 continue;
1236 }
1237 // The stats are computed per module and will all be merged in the binary.
1238 // Importing the metadata will cause duplication of the stats.
1239 if (IsPerformingImport && NMD.getName() == "llvm.stats")
1240 continue;
1241
1242 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1243 // Add Src elements into Dest node.
1244 for (const MDNode *Op : NMD.operands())
1245 DestNMD->addOperand(Mapper.mapMDNode(*Op));
1246 }
1247}
1248
1249/// Merge the linker flags in Src into the Dest module.
1250Error IRLinker::linkModuleFlagsMetadata() {
1251 // If the source module has no module flags, we are done.
1252 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1253 if (!SrcModFlags)
1254 return Error::success();
1255
1256 // Check for module flag for updates before do anything.
1257 UpgradeModuleFlags(*SrcM);
1258
1259 // If the destination module doesn't have module flags yet, then just copy
1260 // over the source module's flags.
1261 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1262 if (DstModFlags->getNumOperands() == 0) {
1263 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1264 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1265
1266 return Error::success();
1267 }
1268
1269 // First build a map of the existing module flags and requirements.
1271 SmallSetVector<MDNode *, 16> Requirements;
1273 DenseSet<MDString *> SeenMin;
1274 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1275 MDNode *Op = DstModFlags->getOperand(I);
1276 uint64_t Behavior =
1277 mdconst::extract<ConstantInt>(Op->getOperand(0))->getZExtValue();
1278 MDString *ID = cast<MDString>(Op->getOperand(1));
1279
1280 if (Behavior == Module::Require) {
1281 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1282 } else {
1283 if (Behavior == Module::Min)
1284 Mins.push_back(I);
1285 Flags[ID] = std::make_pair(Op, I);
1286 }
1287 }
1288
1289 // Merge in the flags from the source module, and also collect its set of
1290 // requirements.
1291 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1292 MDNode *SrcOp = SrcModFlags->getOperand(I);
1293 ConstantInt *SrcBehavior =
1294 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1295 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1296 MDNode *DstOp;
1297 unsigned DstIndex;
1298 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1299 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1300 SeenMin.insert(ID);
1301
1302 // If this is a requirement, add it and continue.
1303 if (SrcBehaviorValue == Module::Require) {
1304 // If the destination module does not already have this requirement, add
1305 // it.
1306 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1307 DstModFlags->addOperand(SrcOp);
1308 }
1309 continue;
1310 }
1311
1312 // If there is no existing flag with this ID, just add it.
1313 if (!DstOp) {
1314 if (SrcBehaviorValue == Module::Min) {
1315 Mins.push_back(DstModFlags->getNumOperands());
1316 SeenMin.erase(ID);
1317 }
1318 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1319 DstModFlags->addOperand(SrcOp);
1320 continue;
1321 }
1322
1323 // Otherwise, perform a merge.
1324 ConstantInt *DstBehavior =
1325 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1326 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1327
1328 auto overrideDstValue = [&]() {
1329 DstModFlags->setOperand(DstIndex, SrcOp);
1330 Flags[ID].first = SrcOp;
1331 };
1332
1333 // If either flag has override behavior, handle it first.
1334 if (DstBehaviorValue == Module::Override) {
1335 // Diagnose inconsistent flags which both have override behavior.
1336 if (SrcBehaviorValue == Module::Override &&
1337 SrcOp->getOperand(2) != DstOp->getOperand(2))
1338 return stringErr("linking module flags '" + ID->getString() +
1339 "': IDs have conflicting override values in '" +
1340 SrcM->getModuleIdentifier() + "' and '" +
1341 DstM.getModuleIdentifier() + "'");
1342 continue;
1343 } else if (SrcBehaviorValue == Module::Override) {
1344 // Update the destination flag to that of the source.
1345 overrideDstValue();
1346 continue;
1347 }
1348
1349 // Diagnose inconsistent merge behavior types.
1350 if (SrcBehaviorValue != DstBehaviorValue) {
1351 bool MinAndWarn = (SrcBehaviorValue == Module::Min &&
1352 DstBehaviorValue == Module::Warning) ||
1353 (DstBehaviorValue == Module::Min &&
1354 SrcBehaviorValue == Module::Warning);
1355 bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
1356 DstBehaviorValue == Module::Warning) ||
1357 (DstBehaviorValue == Module::Max &&
1358 SrcBehaviorValue == Module::Warning);
1359 if (!(MaxAndWarn || MinAndWarn))
1360 return stringErr("linking module flags '" + ID->getString() +
1361 "': IDs have conflicting behaviors in '" +
1362 SrcM->getModuleIdentifier() + "' and '" +
1363 DstM.getModuleIdentifier() + "'");
1364 }
1365
1366 auto ensureDistinctOp = [&](MDNode *DstValue) {
1367 assert(isa<MDTuple>(DstValue) &&
1368 "Expected MDTuple when appending module flags");
1369 if (DstValue->isDistinct())
1370 return dyn_cast<MDTuple>(DstValue);
1371 ArrayRef<MDOperand> DstOperands = DstValue->operands();
1373 DstM.getContext(),
1374 SmallVector<Metadata *, 4>(DstOperands.begin(), DstOperands.end()));
1375 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1376 MDNode *Flag = MDTuple::getDistinct(DstM.getContext(), FlagOps);
1377 DstModFlags->setOperand(DstIndex, Flag);
1378 Flags[ID].first = Flag;
1379 return New;
1380 };
1381
1382 // Emit a warning if the values differ and either source or destination
1383 // request Warning behavior.
1384 if ((DstBehaviorValue == Module::Warning ||
1385 SrcBehaviorValue == Module::Warning) &&
1386 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1387 std::string Str;
1389 << "linking module flags '" << ID->getString()
1390 << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
1391 << "' from " << SrcM->getModuleIdentifier() << " with '"
1392 << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
1393 << ')';
1394 emitWarning(Str);
1395 }
1396
1397 // Choose the minimum if either source or destination request Min behavior.
1398 if (DstBehaviorValue == Module::Min || SrcBehaviorValue == Module::Min) {
1399 ConstantInt *DstValue =
1400 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1401 ConstantInt *SrcValue =
1402 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1403
1404 // The resulting flag should have a Min behavior, and contain the minimum
1405 // value from between the source and destination values.
1406 Metadata *FlagOps[] = {
1407 (DstBehaviorValue != Module::Min ? SrcOp : DstOp)->getOperand(0), ID,
1408 (SrcValue->getZExtValue() < DstValue->getZExtValue() ? SrcOp : DstOp)
1409 ->getOperand(2)};
1410 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1411 DstModFlags->setOperand(DstIndex, Flag);
1412 Flags[ID].first = Flag;
1413 continue;
1414 }
1415
1416 // Choose the maximum if either source or destination request Max behavior.
1417 if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
1418 ConstantInt *DstValue =
1419 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1420 ConstantInt *SrcValue =
1421 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1422
1423 // The resulting flag should have a Max behavior, and contain the maximum
1424 // value from between the source and destination values.
1425 Metadata *FlagOps[] = {
1426 (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
1427 (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
1428 ->getOperand(2)};
1429 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1430 DstModFlags->setOperand(DstIndex, Flag);
1431 Flags[ID].first = Flag;
1432 continue;
1433 }
1434
1435 // Perform the merge for standard behavior types.
1436 switch (SrcBehaviorValue) {
1437 case Module::Require:
1438 case Module::Override:
1439 llvm_unreachable("not possible");
1440 case Module::Error: {
1441 // Emit an error if the values differ.
1442 if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1443 return stringErr("linking module flags '" + ID->getString() +
1444 "': IDs have conflicting values in '" +
1445 SrcM->getModuleIdentifier() + "' and '" +
1446 DstM.getModuleIdentifier() + "'");
1447 continue;
1448 }
1449 case Module::Warning: {
1450 break;
1451 }
1452 case Module::Max: {
1453 break;
1454 }
1455 case Module::Append: {
1456 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1457 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1458 for (const auto &O : SrcValue->operands())
1459 DstValue->push_back(O);
1460 break;
1461 }
1462 case Module::AppendUnique: {
1464 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1465 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1466 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1467 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1468 for (auto I = DstValue->getNumOperands(); I < Elts.size(); I++)
1469 DstValue->push_back(Elts[I]);
1470 break;
1471 }
1472 }
1473
1474 }
1475
1476 // For the Min behavior, set the value to 0 if either module does not have the
1477 // flag.
1478 for (auto Idx : Mins) {
1479 MDNode *Op = DstModFlags->getOperand(Idx);
1480 MDString *ID = cast<MDString>(Op->getOperand(1));
1481 if (!SeenMin.count(ID)) {
1482 ConstantInt *V = mdconst::extract<ConstantInt>(Op->getOperand(2));
1483 Metadata *FlagOps[] = {
1484 Op->getOperand(0), ID,
1485 ConstantAsMetadata::get(ConstantInt::get(V->getType(), 0))};
1486 DstModFlags->setOperand(Idx, MDNode::get(DstM.getContext(), FlagOps));
1487 }
1488 }
1489
1490 // Check all of the requirements.
1491 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1492 MDNode *Requirement = Requirements[I];
1493 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1494 Metadata *ReqValue = Requirement->getOperand(1);
1495
1496 MDNode *Op = Flags[Flag].first;
1497 if (!Op || Op->getOperand(2) != ReqValue)
1498 return stringErr("linking module flags '" + Flag->getString() +
1499 "': does not have the required value");
1500 }
1501 return Error::success();
1502}
1503
1504/// Return InlineAsm adjusted with target-specific directives if required.
1505/// For ARM and Thumb, we have to add directives to select the appropriate ISA
1506/// to support mixing module-level inline assembly from ARM and Thumb modules.
1507static std::string adjustInlineAsm(const std::string &InlineAsm,
1508 const Triple &Triple) {
1510 return ".text\n.balign 2\n.thumb\n" + InlineAsm;
1512 return ".text\n.balign 4\n.arm\n" + InlineAsm;
1513 return InlineAsm;
1514}
1515
1516void IRLinker::updateAttributes(GlobalValue &GV) {
1517 /// Remove nocallback attribute while linking, because nocallback attribute
1518 /// indicates that the function is only allowed to jump back into caller's
1519 /// module only by a return or an exception. When modules are linked, this
1520 /// property cannot be guaranteed anymore. For example, the nocallback
1521 /// function may contain a call to another module. But if we merge its caller
1522 /// and callee module here, and not the module containing the nocallback
1523 /// function definition itself, the nocallback property will be violated
1524 /// (since the nocallback function will call back into the newly merged module
1525 /// containing both its caller and callee). This could happen if the module
1526 /// containing the nocallback function definition is native code, so it does
1527 /// not participate in the LTO link. Note if the nocallback function does
1528 /// participate in the LTO link, and thus ends up in the merged module
1529 /// containing its caller and callee, removing the attribute doesn't hurt as
1530 /// it has no effect on definitions in the same module.
1531 if (auto *F = dyn_cast<Function>(&GV)) {
1532 if (!F->isIntrinsic())
1533 F->removeFnAttr(llvm::Attribute::NoCallback);
1534
1535 // Remove nocallback attribute when it is on a call-site.
1536 for (BasicBlock &BB : *F)
1537 for (Instruction &I : BB)
1538 if (CallBase *CI = dyn_cast<CallBase>(&I))
1539 CI->removeFnAttr(Attribute::NoCallback);
1540 }
1541}
1542
1543Error IRLinker::run() {
1544 // Ensure metadata materialized before value mapping.
1545 if (SrcM->getMaterializer())
1546 if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1547 return Err;
1548
1549 DstM.IsNewDbgInfoFormat = SrcM->IsNewDbgInfoFormat;
1550
1551 // Inherit the target data from the source module if the destination module
1552 // doesn't have one already.
1553 if (DstM.getDataLayout().isDefault())
1554 DstM.setDataLayout(SrcM->getDataLayout());
1555
1556 // Copy the target triple from the source to dest if the dest's is empty.
1557 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1558 DstM.setTargetTriple(SrcM->getTargetTriple());
1559
1560 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1561
1562 // During CUDA compilation we have to link with the bitcode supplied with
1563 // CUDA. libdevice bitcode either has no data layout set (pre-CUDA-11), or has
1564 // the layout that is different from the one used by LLVM/clang (it does not
1565 // include i128). Issuing a warning is not very helpful as there's not much
1566 // the user can do about it.
1567 bool EnableDLWarning = true;
1568 bool EnableTripleWarning = true;
1569 if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
1570 std::string ModuleId = SrcM->getModuleIdentifier();
1571 StringRef FileName = llvm::sys::path::filename(ModuleId);
1572 bool SrcIsLibDevice =
1573 FileName.starts_with("libdevice") && FileName.ends_with(".10.bc");
1574 bool SrcHasLibDeviceDL =
1575 (SrcM->getDataLayoutStr().empty() ||
1576 SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
1577 // libdevice bitcode uses nvptx64-nvidia-gpulibs or just
1578 // 'nvptx-unknown-unknown' triple (before CUDA-10.x) and is compatible with
1579 // all NVPTX variants.
1580 bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
1581 SrcTriple.getOSName() == "gpulibs") ||
1582 (SrcTriple.getVendorName() == "unknown" &&
1583 SrcTriple.getOSName() == "unknown");
1584 EnableTripleWarning = !(SrcIsLibDevice && SrcHasLibDeviceTriple);
1585 EnableDLWarning = !(SrcIsLibDevice && SrcHasLibDeviceDL);
1586 }
1587
1588 if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
1589 emitWarning("Linking two modules of different data layouts: '" +
1590 SrcM->getModuleIdentifier() + "' is '" +
1591 SrcM->getDataLayoutStr() + "' whereas '" +
1592 DstM.getModuleIdentifier() + "' is '" +
1593 DstM.getDataLayoutStr() + "'\n");
1594 }
1595
1596 if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
1597 !SrcTriple.isCompatibleWith(DstTriple))
1598 emitWarning("Linking two modules of different target triples: '" +
1599 SrcM->getModuleIdentifier() + "' is '" +
1600 SrcM->getTargetTriple() + "' whereas '" +
1601 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1602 "'\n");
1603
1604 DstM.setTargetTriple(SrcTriple.merge(DstTriple));
1605
1606 // Loop over all of the linked values to compute type mappings.
1607 computeTypeMapping();
1608
1609 std::reverse(Worklist.begin(), Worklist.end());
1610 while (!Worklist.empty()) {
1611 GlobalValue *GV = Worklist.back();
1612 Worklist.pop_back();
1613
1614 // Already mapped.
1615 if (ValueMap.find(GV) != ValueMap.end() ||
1616 IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
1617 continue;
1618
1619 assert(!GV->isDeclaration());
1620 Mapper.mapValue(*GV);
1621 if (FoundError)
1622 return std::move(*FoundError);
1623 flushRAUWWorklist();
1624 }
1625
1626 // Note that we are done linking global value bodies. This prevents
1627 // metadata linking from creating new references.
1628 DoneLinkingBodies = true;
1630
1631 // Remap all of the named MDNodes in Src into the DstM module. We do this
1632 // after linking GlobalValues so that MDNodes that reference GlobalValues
1633 // are properly remapped.
1634 linkNamedMDNodes();
1635
1636 // Clean up any global objects with potentially unmapped metadata.
1637 // Specifically declarations which did not become definitions.
1638 for (GlobalObject *NGO : UnmappedMetadata) {
1639 if (NGO->isDeclaration())
1640 Mapper.remapGlobalObjectMetadata(*NGO);
1641 }
1642
1643 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1644 // Append the module inline asm string.
1645 DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
1646 SrcTriple));
1647 } else if (IsPerformingImport) {
1648 // Import any symver directives for symbols in DstM.
1650 [&](StringRef Name, StringRef Alias) {
1651 if (DstM.getNamedValue(Name)) {
1652 SmallString<256> S(".symver ");
1653 S += Name;
1654 S += ", ";
1655 S += Alias;
1656 DstM.appendModuleInlineAsm(S);
1657 }
1658 });
1659 }
1660
1661 // Reorder the globals just added to the destination module to match their
1662 // original order in the source module.
1663 for (GlobalVariable &GV : SrcM->globals()) {
1664 if (GV.hasAppendingLinkage())
1665 continue;
1666 Value *NewValue = Mapper.mapValue(GV);
1667 if (NewValue) {
1668 auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
1669 if (NewGV) {
1670 NewGV->removeFromParent();
1671 DstM.insertGlobalVariable(NewGV);
1672 }
1673 }
1674 }
1675
1676 // Merge the module flags into the DstM module.
1677 return linkModuleFlagsMetadata();
1678}
1679
1681 : ETypes(E), IsPacked(P) {}
1682
1684 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1685
1687 return IsPacked == That.IsPacked && ETypes == That.ETypes;
1688}
1689
1691 return !this->operator==(That);
1692}
1693
1694StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1696}
1697
1698StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1700}
1701
1702unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1703 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1704 Key.IsPacked);
1705}
1706
1707unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1708 return getHashValue(KeyTy(ST));
1709}
1710
1711bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1712 const StructType *RHS) {
1713 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1714 return false;
1715 return LHS == KeyTy(RHS);
1716}
1717
1718bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1719 const StructType *RHS) {
1720 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1721 return LHS == RHS;
1722 return KeyTy(LHS) == KeyTy(RHS);
1723}
1724
1726 assert(!Ty->isOpaque());
1727 NonOpaqueStructTypes.insert(Ty);
1728}
1729
1731 assert(!Ty->isOpaque());
1732 NonOpaqueStructTypes.insert(Ty);
1733 bool Removed = OpaqueStructTypes.erase(Ty);
1734 (void)Removed;
1735 assert(Removed);
1736}
1737
1739 assert(Ty->isOpaque());
1740 OpaqueStructTypes.insert(Ty);
1741}
1742
1743StructType *
1745 bool IsPacked) {
1746 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1747 auto I = NonOpaqueStructTypes.find_as(Key);
1748 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1749}
1750
1752 if (Ty->isOpaque())
1753 return OpaqueStructTypes.count(Ty);
1754 auto I = NonOpaqueStructTypes.find(Ty);
1755 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1756}
1757
1758IRMover::IRMover(Module &M) : Composite(M) {
1759 TypeFinder StructTypes;
1760 StructTypes.run(M, /* OnlyNamed */ false);
1761 for (StructType *Ty : StructTypes) {
1762 if (Ty->isOpaque())
1763 IdentifiedStructTypes.addOpaque(Ty);
1764 else
1765 IdentifiedStructTypes.addNonOpaque(Ty);
1766 }
1767 // Self-map metadatas in the destination module. This is needed when
1768 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1769 // destination module may be reached from the source module.
1770 for (const auto *MD : StructTypes.getVisitedMetadata()) {
1771 SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1772 }
1773}
1774
1775Error IRMover::move(std::unique_ptr<Module> Src,
1776 ArrayRef<GlobalValue *> ValuesToLink,
1777 LazyCallback AddLazyFor, bool IsPerformingImport) {
1778 if (getModule().IsNewDbgInfoFormat)
1779 Src->convertToNewDbgValues();
1780 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1781 std::move(Src), ValuesToLink, std::move(AddLazyFor),
1782 IsPerformingImport);
1783 Error E = TheIRLinker.run();
1785 return E;
1786}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
static void forceRenaming(GlobalValue *GV, StringRef Name)
The LLVM SymbolTable class autorenames globals that conflict in the symbol table.
Definition: IRMover.cpp:566
static void getArrayElements(const Constant *C, SmallVectorImpl< Constant * > &Dest)
Definition: IRMover.cpp:876
static std::string adjustInlineAsm(const std::string &InlineAsm, const Triple &Triple)
Return InlineAsm adjusted with target-specific directives if required.
Definition: IRMover.cpp:1507
static StringRef getTypeNamePrefix(StringRef Name)
Definition: IRMover.cpp:777
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
iterator begin() const
Definition: ArrayRef.h:153
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:84
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1457
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:47
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2087
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2140
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:153
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an Operation in the Expression.
bool isDefault() const
Test if the DataLayout was constructed from an empty string.
Definition: DataLayout.h:251
bool erase(const KeyT &Val)
Definition: DenseMap.h:329
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
This is the base abstract class for diagnostic reporting in the backend.
Interface for custom diagnostic printing.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:162
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:200
bool IsNewDbgInfoFormat
Is this function using intrinsics to record the position of debugging information,...
Definition: Function.h:106
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:518
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:575
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:118
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:80
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:128
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:274
LinkageTypes getLinkage() const
Definition: GlobalValue.h:545
bool hasLocalLinkage() const
Definition: GlobalValue.h:527
const Comdat * getComdat() const
Definition: Globals.cpp:184
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:528
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:536
bool isDeclarationForLinker() const
Definition: GlobalValue.h:617
unsigned getAddressSpace() const
Definition: GlobalValue.h:205
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:86
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:215
bool hasAppendingLinkage() const
Definition: GlobalValue.h:524
void removeFromParent()
This method unlinks 'this' from the containing module, but does not delete it.
Definition: Globals.cpp:74
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
Type * getValueType() const
Definition: GlobalValue.h:296
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:482
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void switchToNonOpaque(StructType *Ty)
Definition: IRMover.cpp:1730
StructType * findNonOpaque(ArrayRef< Type * > ETypes, bool IsPacked)
Definition: IRMover.cpp:1744
IRMover(Module &M)
Definition: IRMover.cpp:1758
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
Definition: IRMover.cpp:1775
Module & getModule()
Definition: IRMover.h:81
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg)
Definition: IRMover.cpp:351
void print(DiagnosticPrinter &DP) const override
Print using the given DP a user-friendly message.
Definition: IRMover.cpp:354
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1426
op_iterator op_end() const
Definition: Metadata.h:1422
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1434
op_iterator op_begin() const
Definition: Metadata.h:1418
A single uniqued string.
Definition: Metadata.h:720
Tuple of metadata.
Definition: Metadata.h:1470
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition: Metadata.h:1509
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition: Metadata.h:1527
Root of the metadata hierarchy.
Definition: Metadata.h:62
static void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
@ AppendUnique
Appends the two values, which are required to be metadata nodes.
Definition: Module.h:144
@ Override
Uses the specified value, regardless of the behavior or value of the other module.
Definition: Module.h:136
@ Warning
Emits a warning if two values disagree.
Definition: Module.h:122
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition: Module.h:118
@ Min
Takes the min of the two values, which are required to be integers.
Definition: Module.h:150
@ Append
Appends the two values, which are required to be metadata nodes.
Definition: Module.h:139
@ Max
Takes the max of the two values, which are required to be integers.
Definition: Module.h:147
@ Require
Adds a requirement that another module flag be present and have a specified value after linking is pe...
Definition: Module.h:131
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:295
bool IsNewDbgInfoFormat
Is this Module using intrinsics to record the position of debugging information, or non-intrinsic rec...
Definition: Module.h:219
void dropTriviallyDeadConstantArrays()
Destroy ConstantArrays in LLVMContext if they are not used.
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:260
NamedMDNode * getOrInsertModuleFlagsMetadata()
Returns the NamedMDNode in the module that represents module-level flags.
Definition: Module.cpp:351
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:291
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:261
void setDataLayout(StringRef Desc)
Set the data layout.
Definition: Module.cpp:401
void insertGlobalVariable(GlobalVariable *GV)
Insert global variable GV at the end of the global variable list and take ownership.
Definition: Module.h:584
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition: Module.cpp:133
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition: Module.cpp:269
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:589
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:287
const std::string & getDataLayoutStr() const
Get the data layout string for the module's target platform.
Definition: Module.h:282
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
Definition: Module.h:346
void setTargetTriple(StringRef T)
Set the target triple.
Definition: Module.h:334
A tuple of MDNodes.
Definition: Metadata.h:1729
void setOperand(unsigned I, MDNode *New)
Definition: Metadata.cpp:1387
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1379
unsigned getNumOperands() const
Definition: Metadata.cpp:1375
void addOperand(MDNode *M)
Definition: Metadata.cpp:1385
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false.
Definition: SmallPtrSet.h:356
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void resize(size_type N)
Definition: SmallVector.h:651
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:271
static constexpr size_t npos
Definition: StringRef.h:52
Class to represent struct types.
Definition: DerivedTypes.h:216
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:373
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
Definition: Type.cpp:445
static StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
Definition: Type.cpp:632
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:513
bool isPacked() const
Definition: DerivedTypes.h:278
void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
Definition: Type.cpp:462
bool hasName() const
Return true if this is a named struct that has a non-empty name.
Definition: DerivedTypes.h:304
bool isLiteral() const
Return true if this type is uniqued by structural equivalence, false if it is a struct definition.
Definition: DerivedTypes.h:282
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Definition: DerivedTypes.h:286
StringRef getName() const
Return the name for this struct type if it has an identity.
Definition: Type.cpp:590
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:361
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
Definition: TypeFinder.h:31
DenseSet< const MDNode * > & getVisitedMetadata()
Definition: TypeFinder.h:63
void run(const Module &M, bool onlyNamed)
Definition: TypeFinder.cpp:34
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
@ FunctionTyID
Functions.
Definition: Type.h:72
@ ArrayTyID
Arrays.
Definition: Type.h:75
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:77
@ StructTyID
Structures.
Definition: Type.h:74
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:76
@ PointerTyID
Pointers.
Definition: Type.h:73
unsigned getNumContainedTypes() const
Return the number of types in the derived type.
Definition: Type.h:383
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:246
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:137
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition: Type.h:377
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition: ValueMapper.h:41
virtual Type * remapType(Type *SrcTy)=0
The client should implement this method if they want to remap types while mapping values.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:164
std::optional< MDMapT > & getMDMap()
Definition: ValueMap.h:119
iterator find(const KeyT &Val)
Definition: ValueMap.h:155
iterator end()
Definition: ValueMap.h:135
Context for (re-)mapping values (and metadata).
Definition: ValueMapper.h:149
MDNode * mapMDNode(const MDNode &N)
void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver, unsigned MappingContextID=0)
void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
void remapGlobalObjectMetadata(GlobalObject &GO)
Value * mapValue(const Value &V)
void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:54
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:693
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
bool erase(const ValueT &V)
Definition: DenseSet.h:101
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:97
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
unique_function is a type-erasing functor similar to std::function.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Key
PAL metadata keys.
AddressSpace getAddressSpace(T *V)
Definition: AVR.h:65
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
std::optional< Function * > remangleIntrinsicFunction(Function *F)
Definition: Function.cpp:1740
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:148
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:579
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:90
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
@ DK_Linker
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:94
@ RF_NullMapMissingGlobalValues
Any global values not in value map are mapped to null instead of mapping to self.
Definition: ValueMapper.h:104
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
Definition: ValueMapper.h:100
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1858
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Warning
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2031
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:613
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:491
constexpr const char * PseudoProbeDescMetadataName
Definition: PseudoProbe.h:25
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:50
KeyTy(ArrayRef< Type * > E, bool P)
Definition: IRMover.cpp:1680
bool operator==(const KeyTy &that) const
Definition: IRMover.cpp:1686
bool operator!=(const KeyTy &that) const
Definition: IRMover.cpp:1690