blob: 15a46a2d0420f1d368a1b31a8f9ba4a2e6e0dc81 [file] [log] [blame]
Rafael Espindolacaabe222015-12-10 14:19:35 +00001//===- lib/Linker/IRMover.cpp ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Linker/IRMover.h"
11#include "LinkDiagnosticInfo.h"
12#include "llvm/ADT/SetVector.h"
13#include "llvm/ADT/SmallString.h"
14#include "llvm/ADT/Triple.h"
15#include "llvm/IR/Constants.h"
Teresa Johnson0e7c82c2015-12-18 17:51:37 +000016#include "llvm/IR/DebugInfo.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000017#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnsone5a61912015-12-17 17:14:09 +000018#include "llvm/IR/GVMaterializer.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000019#include "llvm/IR/Intrinsics.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000020#include "llvm/IR/TypeFinder.h"
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +000021#include "llvm/Support/Error.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000022#include "llvm/Transforms/Utils/Cloning.h"
Benjamin Kramer82de7d32016-05-27 14:27:24 +000023#include <utility>
Rafael Espindolacaabe222015-12-10 14:19:35 +000024using namespace llvm;
25
26//===----------------------------------------------------------------------===//
27// TypeMap implementation.
28//===----------------------------------------------------------------------===//
29
30namespace {
31class TypeMapTy : public ValueMapTypeRemapper {
32 /// This is a mapping from a source type to a destination type to use.
33 DenseMap<Type *, Type *> MappedTypes;
34
35 /// When checking to see if two subgraphs are isomorphic, we speculatively
36 /// add types to MappedTypes, but keep track of them here in case we need to
37 /// roll back.
38 SmallVector<Type *, 16> SpeculativeTypes;
39
40 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
41
42 /// This is a list of non-opaque structs in the source module that are mapped
43 /// to an opaque struct in the destination module.
44 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
45
46 /// This is the set of opaque types in the destination modules who are
47 /// getting a body from the source module.
48 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
49
50public:
51 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
52 : DstStructTypesSet(DstStructTypesSet) {}
53
54 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
55 /// Indicate that the specified type in the destination module is conceptually
56 /// equivalent to the specified type in the source module.
57 void addTypeMapping(Type *DstTy, Type *SrcTy);
58
59 /// Produce a body for an opaque type in the dest module from a type
60 /// definition in the source module.
61 void linkDefinedTypeBodies();
62
63 /// Return the mapped type to use for the specified input type from the
64 /// source module.
65 Type *get(Type *SrcTy);
66 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
67
68 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
69
70 FunctionType *get(FunctionType *T) {
71 return cast<FunctionType>(get((Type *)T));
72 }
73
74private:
75 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
76
77 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
78};
79}
80
81void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
82 assert(SpeculativeTypes.empty());
83 assert(SpeculativeDstOpaqueTypes.empty());
84
85 // Check to see if these types are recursively isomorphic and establish a
86 // mapping between them if so.
87 if (!areTypesIsomorphic(DstTy, SrcTy)) {
88 // Oops, they aren't isomorphic. Just discard this request by rolling out
89 // any speculative mappings we've established.
90 for (Type *Ty : SpeculativeTypes)
91 MappedTypes.erase(Ty);
92
93 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
94 SpeculativeDstOpaqueTypes.size());
95 for (StructType *Ty : SpeculativeDstOpaqueTypes)
96 DstResolvedOpaqueTypes.erase(Ty);
97 } else {
98 for (Type *Ty : SpeculativeTypes)
99 if (auto *STy = dyn_cast<StructType>(Ty))
100 if (STy->hasName())
101 STy->setName("");
102 }
103 SpeculativeTypes.clear();
104 SpeculativeDstOpaqueTypes.clear();
105}
106
107/// Recursively walk this pair of types, returning true if they are isomorphic,
108/// false if they are not.
109bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
110 // Two types with differing kinds are clearly not isomorphic.
111 if (DstTy->getTypeID() != SrcTy->getTypeID())
112 return false;
113
114 // If we have an entry in the MappedTypes table, then we have our answer.
115 Type *&Entry = MappedTypes[SrcTy];
116 if (Entry)
117 return Entry == DstTy;
118
119 // Two identical types are clearly isomorphic. Remember this
120 // non-speculatively.
121 if (DstTy == SrcTy) {
122 Entry = DstTy;
123 return true;
124 }
125
126 // Okay, we have two types with identical kinds that we haven't seen before.
127
128 // If this is an opaque struct type, special case it.
129 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
130 // Mapping an opaque type to any struct, just keep the dest struct.
131 if (SSTy->isOpaque()) {
132 Entry = DstTy;
133 SpeculativeTypes.push_back(SrcTy);
134 return true;
135 }
136
137 // Mapping a non-opaque source type to an opaque dest. If this is the first
138 // type that we're mapping onto this destination type then we succeed. Keep
139 // the dest, but fill it in later. If this is the second (different) type
140 // that we're trying to map onto the same opaque type then we fail.
141 if (cast<StructType>(DstTy)->isOpaque()) {
142 // We can only map one source type onto the opaque destination type.
143 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
144 return false;
145 SrcDefinitionsToResolve.push_back(SSTy);
146 SpeculativeTypes.push_back(SrcTy);
147 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
148 Entry = DstTy;
149 return true;
150 }
151 }
152
153 // If the number of subtypes disagree between the two types, then we fail.
154 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
155 return false;
156
157 // Fail if any of the extra properties (e.g. array size) of the type disagree.
158 if (isa<IntegerType>(DstTy))
159 return false; // bitwidth disagrees.
160 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
161 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
162 return false;
163
164 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
165 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
166 return false;
167 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
168 StructType *SSTy = cast<StructType>(SrcTy);
169 if (DSTy->isLiteral() != SSTy->isLiteral() ||
170 DSTy->isPacked() != SSTy->isPacked())
171 return false;
Peter Collingbournebc070522016-12-02 03:20:58 +0000172 } else if (auto *DSeqTy = dyn_cast<SequentialType>(DstTy)) {
173 if (DSeqTy->getNumElements() !=
174 cast<SequentialType>(SrcTy)->getNumElements())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000175 return false;
176 }
177
178 // Otherwise, we speculate that these two types will line up and recursively
179 // check the subelements.
180 Entry = DstTy;
181 SpeculativeTypes.push_back(SrcTy);
182
183 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
184 if (!areTypesIsomorphic(DstTy->getContainedType(I),
185 SrcTy->getContainedType(I)))
186 return false;
187
188 // If everything seems to have lined up, then everything is great.
189 return true;
190}
191
192void TypeMapTy::linkDefinedTypeBodies() {
193 SmallVector<Type *, 16> Elements;
194 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
195 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
196 assert(DstSTy->isOpaque());
197
198 // Map the body of the source type over to a new body for the dest type.
199 Elements.resize(SrcSTy->getNumElements());
200 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
201 Elements[I] = get(SrcSTy->getElementType(I));
202
203 DstSTy->setBody(Elements, SrcSTy->isPacked());
204 DstStructTypesSet.switchToNonOpaque(DstSTy);
205 }
206 SrcDefinitionsToResolve.clear();
207 DstResolvedOpaqueTypes.clear();
208}
209
210void TypeMapTy::finishType(StructType *DTy, StructType *STy,
211 ArrayRef<Type *> ETypes) {
212 DTy->setBody(ETypes, STy->isPacked());
213
214 // Steal STy's name.
215 if (STy->hasName()) {
216 SmallString<16> TmpName = STy->getName();
217 STy->setName("");
218 DTy->setName(TmpName);
219 }
220
221 DstStructTypesSet.addNonOpaque(DTy);
222}
223
224Type *TypeMapTy::get(Type *Ty) {
225 SmallPtrSet<StructType *, 8> Visited;
226 return get(Ty, Visited);
227}
228
229Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
230 // If we already have an entry for this type, return it.
231 Type **Entry = &MappedTypes[Ty];
232 if (*Entry)
233 return *Entry;
234
235 // These are types that LLVM itself will unique.
236 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
237
238#ifndef NDEBUG
239 if (!IsUniqued) {
240 for (auto &Pair : MappedTypes) {
241 assert(!(Pair.first != Ty && Pair.second == Ty) &&
242 "mapping to a source type");
243 }
244 }
245#endif
246
247 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
248 StructType *DTy = StructType::create(Ty->getContext());
249 return *Entry = DTy;
250 }
251
252 // If this is not a recursive type, then just map all of the elements and
253 // then rebuild the type from inside out.
254 SmallVector<Type *, 4> ElementTypes;
255
256 // If there are no element types to map, then the type is itself. This is
257 // true for the anonymous {} struct, things like 'float', integers, etc.
258 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
259 return *Entry = Ty;
260
261 // Remap all of the elements, keeping track of whether any of them change.
262 bool AnyChange = false;
263 ElementTypes.resize(Ty->getNumContainedTypes());
264 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
265 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
266 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
267 }
268
269 // If we found our type while recursively processing stuff, just use it.
270 Entry = &MappedTypes[Ty];
271 if (*Entry) {
272 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
273 if (DTy->isOpaque()) {
274 auto *STy = cast<StructType>(Ty);
275 finishType(DTy, STy, ElementTypes);
276 }
277 }
278 return *Entry;
279 }
280
281 // If all of the element types mapped directly over and the type is not
Hans Wennborg2d55d672016-10-19 20:10:03 +0000282 // a named struct, then the type is usable as-is.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000283 if (!AnyChange && IsUniqued)
284 return *Entry = Ty;
285
286 // Otherwise, rebuild a modified type.
287 switch (Ty->getTypeID()) {
288 default:
289 llvm_unreachable("unknown derived type to remap");
290 case Type::ArrayTyID:
291 return *Entry = ArrayType::get(ElementTypes[0],
292 cast<ArrayType>(Ty)->getNumElements());
293 case Type::VectorTyID:
294 return *Entry = VectorType::get(ElementTypes[0],
295 cast<VectorType>(Ty)->getNumElements());
296 case Type::PointerTyID:
297 return *Entry = PointerType::get(ElementTypes[0],
298 cast<PointerType>(Ty)->getAddressSpace());
299 case Type::FunctionTyID:
300 return *Entry = FunctionType::get(ElementTypes[0],
301 makeArrayRef(ElementTypes).slice(1),
302 cast<FunctionType>(Ty)->isVarArg());
303 case Type::StructTyID: {
304 auto *STy = cast<StructType>(Ty);
305 bool IsPacked = STy->isPacked();
306 if (IsUniqued)
307 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
308
309 // If the type is opaque, we can just use it directly.
310 if (STy->isOpaque()) {
311 DstStructTypesSet.addOpaque(STy);
312 return *Entry = Ty;
313 }
314
315 if (StructType *OldT =
316 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
317 STy->setName("");
318 return *Entry = OldT;
319 }
320
321 if (!AnyChange) {
322 DstStructTypesSet.addNonOpaque(STy);
323 return *Entry = Ty;
324 }
325
326 StructType *DTy = StructType::create(Ty->getContext());
327 finishType(DTy, STy, ElementTypes);
328 return *Entry = DTy;
329 }
330 }
331}
332
333LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
334 const Twine &Msg)
335 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
336void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
337
338//===----------------------------------------------------------------------===//
Teresa Johnsonbef54362015-12-18 19:28:59 +0000339// IRLinker implementation.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000340//===----------------------------------------------------------------------===//
341
342namespace {
343class IRLinker;
344
345/// Creates prototypes for functions that are lazily linked on the fly. This
346/// speeds up linking for modules with many/ lazily linked functions of which
347/// few get used.
348class GlobalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000349 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000350
351public:
Mehdi Amini33661072016-03-11 22:19:06 +0000352 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000353 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000354};
355
356class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000357 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000358
359public:
Mehdi Amini33661072016-03-11 22:19:06 +0000360 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000361 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000362};
363
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000364/// Type of the Metadata map in \a ValueToValueMapTy.
365typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
366
Rafael Espindolacaabe222015-12-10 14:19:35 +0000367/// This is responsible for keeping track of the state used for moving data
368/// from SrcM to DstM.
369class IRLinker {
370 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000371 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000372
Mehdi Amini33661072016-03-11 22:19:06 +0000373 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000374 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
375
376 TypeMapTy TypeMap;
377 GlobalValueMaterializer GValMaterializer;
378 LocalValueMaterializer LValMaterializer;
379
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000380 /// A metadata map that's shared between IRLinker instances.
381 MDMapT &SharedMDs;
382
Rafael Espindolacaabe222015-12-10 14:19:35 +0000383 /// Mapping of values from what they used to be in Src, to what they are now
384 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
385 /// due to the use of Value handles which the Linker doesn't actually need,
386 /// but this allows us to reuse the ValueMapper code.
387 ValueToValueMapTy ValueMap;
388 ValueToValueMapTy AliasValueMap;
389
390 DenseSet<GlobalValue *> ValuesToLink;
391 std::vector<GlobalValue *> Worklist;
392
393 void maybeAdd(GlobalValue *GV) {
394 if (ValuesToLink.insert(GV).second)
395 Worklist.push_back(GV);
396 }
397
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000398 /// Whether we are importing globals for ThinLTO, as opposed to linking the
399 /// source module. If this flag is set, it means that we can rely on some
400 /// other object file to define any non-GlobalValue entities defined by the
401 /// source module. This currently causes us to not link retained types in
402 /// debug info metadata and module inline asm.
403 bool IsPerformingImport;
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000404
Rafael Espindolacaabe222015-12-10 14:19:35 +0000405 /// Set to true when all global value body linking is complete (including
406 /// lazy linking). Used to prevent metadata linking from creating new
407 /// references.
408 bool DoneLinkingBodies = false;
409
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000410 /// The Error encountered during materialization. We use an Optional here to
411 /// avoid needing to manage an unconsumed success value.
412 Optional<Error> FoundError;
413 void setError(Error E) {
414 if (E)
415 FoundError = std::move(E);
416 }
417
418 /// Most of the errors produced by this module are inconvertible StringErrors.
419 /// This convenience function lets us return one of those more easily.
420 Error stringErr(const Twine &T) {
421 return make_error<StringError>(T, inconvertibleErrorCode());
422 }
Rafael Espindolacaabe222015-12-10 14:19:35 +0000423
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000424 /// Entry point for mapping values and alternate context for mapping aliases.
425 ValueMapper Mapper;
426 unsigned AliasMCID;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000427
Rafael Espindolacaabe222015-12-10 14:19:35 +0000428 /// Handles cloning of a global values from the source module into
429 /// the destination module, including setting the attributes and visibility.
430 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
431
Rafael Espindolacaabe222015-12-10 14:19:35 +0000432 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000433 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000434 }
435
436 /// Given a global in the source module, return the global in the
437 /// destination module that is being linked to, if any.
438 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
439 // If the source has no name it can't link. If it has local linkage,
440 // there is no name match-up going on.
441 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
442 return nullptr;
443
444 // Otherwise see if we have a match in the destination module's symtab.
445 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
446 if (!DGV)
447 return nullptr;
448
449 // If we found a global with the same name in the dest module, but it has
450 // internal linkage, we are really not doing any linkage here.
451 if (DGV->hasLocalLinkage())
452 return nullptr;
453
454 // Otherwise, we do in fact link to the destination global.
455 return DGV;
456 }
457
458 void computeTypeMapping();
459
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000460 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
461 const GlobalVariable *SrcGV);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000462
Mehdi Amini33661072016-03-11 22:19:06 +0000463 /// Given the GlobaValue \p SGV in the source module, and the matching
464 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
465 /// into the destination module.
466 ///
467 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000468 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000469 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000470
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000471 Error linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000472
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000473 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000474 Error linkFunctionBody(Function &Dst, Function &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000475 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000476 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000477
478 /// Functions that take care of cloning a specific global value type
479 /// into the destination module.
480 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
481 Function *copyFunctionProto(const Function *SF);
482 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
483
Teresa Johnson040cc162016-12-12 16:09:30 +0000484 /// When importing for ThinLTO, prevent importing of types listed on
485 /// the DICompileUnit that we don't need a copy of in the importing
486 /// module.
487 void prepareCompileUnitsForImport();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000488 void linkNamedMDNodes();
489
490public:
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000491 IRLinker(Module &DstM, MDMapT &SharedMDs,
492 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
493 ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000494 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000495 bool IsPerformingImport)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000496 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
497 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000498 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000499 Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
500 &GValMaterializer),
501 AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
502 &LValMaterializer)) {
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000503 ValueMap.getMDMap() = std::move(SharedMDs);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000504 for (GlobalValue *GV : ValuesToLink)
505 maybeAdd(GV);
Teresa Johnson040cc162016-12-12 16:09:30 +0000506 if (IsPerformingImport)
507 prepareCompileUnitsForImport();
Teresa Johnsoncc428572015-12-30 19:32:24 +0000508 }
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000509 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Teresa Johnsoncc428572015-12-30 19:32:24 +0000510
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000511 Error run();
Mehdi Amini53a66722016-05-25 21:01:51 +0000512 Value *materialize(Value *V, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000513};
514}
515
516/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
517/// table. This is good for all clients except for us. Go through the trouble
518/// to force this back.
519static void forceRenaming(GlobalValue *GV, StringRef Name) {
520 // If the global doesn't force its name or if it already has the right name,
521 // there is nothing for us to do.
522 if (GV->hasLocalLinkage() || GV->getName() == Name)
523 return;
524
525 Module *M = GV->getParent();
526
527 // If there is a conflict, rename the conflict.
528 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
529 GV->takeName(ConflictGV);
530 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
531 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
532 } else {
533 GV->setName(Name); // Force the name back
534 }
535}
536
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000537Value *GlobalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000538 return TheIRLinker.materialize(SGV, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000539}
540
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000541Value *LocalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000542 return TheIRLinker.materialize(SGV, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000543}
544
Mehdi Amini53a66722016-05-25 21:01:51 +0000545Value *IRLinker::materialize(Value *V, bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000546 auto *SGV = dyn_cast<GlobalValue>(V);
547 if (!SGV)
548 return nullptr;
549
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000550 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
551 if (!NewProto) {
552 setError(NewProto.takeError());
553 return nullptr;
554 }
555 if (!*NewProto)
556 return nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000557
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000558 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
Mehdi Amini53a66722016-05-25 21:01:51 +0000559 if (!New)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000560 return *NewProto;
Mehdi Amini53a66722016-05-25 21:01:51 +0000561
Rafael Espindolacaabe222015-12-10 14:19:35 +0000562 // If we already created the body, just return.
563 if (auto *F = dyn_cast<Function>(New)) {
564 if (!F->isDeclaration())
Mehdi Amini53a66722016-05-25 21:01:51 +0000565 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000566 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000567 if (V->hasInitializer() || V->hasAppendingLinkage())
Mehdi Amini53a66722016-05-25 21:01:51 +0000568 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000569 } else {
570 auto *A = cast<GlobalAlias>(New);
571 if (A->getAliasee())
Mehdi Amini53a66722016-05-25 21:01:51 +0000572 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000573 }
574
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000575 // When linking a global for an alias, it will always be linked. However we
Adrian Prantl1f9ac962016-11-14 17:26:32 +0000576 // need to check if it was not already scheduled to satisfy a reference from a
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000577 // regular global value initializer. We know if it has been schedule if the
578 // "New" GlobalValue that is mapped here for the alias is the same as the one
579 // already mapped. If there is an entry in the ValueMap but the value is
580 // different, it means that the value already had a definition in the
581 // destination module (linkonce for instance), but we need a new definition
582 // for the alias ("New" will be different.
Mehdi Amini53a66722016-05-25 21:01:51 +0000583 if (ForAlias && ValueMap.lookup(SGV) == New)
584 return New;
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000585
Mehdi Amini53a66722016-05-25 21:01:51 +0000586 if (ForAlias || shouldLink(New, *SGV))
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000587 setError(linkGlobalValueBody(*New, *SGV));
Mehdi Amini53a66722016-05-25 21:01:51 +0000588
589 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000590}
591
592/// Loop through the global variables in the src module and merge them into the
593/// dest module.
594GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
595 // No linking to be performed or linking from the source: simply create an
596 // identical version of the symbol over in the dest module... the
597 // initializer will be filled in later by LinkGlobalInits.
598 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000599 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000600 SGVar->isConstant(), GlobalValue::ExternalLinkage,
601 /*init*/ nullptr, SGVar->getName(),
602 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
603 SGVar->getType()->getAddressSpace());
604 NewDGV->setAlignment(SGVar->getAlignment());
605 return NewDGV;
606}
607
608/// Link the function in the source module into the destination module if
609/// needed, setting up mapping information.
610Function *IRLinker::copyFunctionProto(const Function *SF) {
611 // If there is no linkage to be performed or we are linking from the source,
612 // bring SF over.
613 return Function::Create(TypeMap.get(SF->getFunctionType()),
614 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
615}
616
617/// Set up prototypes for any aliases that come over from the source module.
618GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
619 // If there is no linkage to be performed or we're linking from the source,
620 // bring over SGA.
621 auto *Ty = TypeMap.get(SGA->getValueType());
622 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
623 GlobalValue::ExternalLinkage, SGA->getName(),
624 &DstM);
625}
626
627GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
628 bool ForDefinition) {
629 GlobalValue *NewGV;
630 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
631 NewGV = copyGlobalVariableProto(SGVar);
632 } else if (auto *SF = dyn_cast<Function>(SGV)) {
633 NewGV = copyFunctionProto(SF);
634 } else {
635 if (ForDefinition)
636 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
637 else
638 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000639 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000640 /*isConstant*/ false, GlobalValue::ExternalLinkage,
641 /*init*/ nullptr, SGV->getName(),
642 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
643 SGV->getType()->getAddressSpace());
644 }
645
646 if (ForDefinition)
647 NewGV->setLinkage(SGV->getLinkage());
Mehdi Amini113adde2016-04-19 16:11:05 +0000648 else if (SGV->hasExternalWeakLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000649 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
650
651 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000652
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +0000653 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
654 // Metadata for global variables and function declarations is copied eagerly.
655 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000656 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +0000657 }
658
Teresa Johnson5fe40052016-01-12 00:24:24 +0000659 // Remove these copied constants in case this stays a declaration, since
660 // they point to the source module. If the def is linked the values will
661 // be mapped in during linkFunctionBody.
662 if (auto *NewF = dyn_cast<Function>(NewGV)) {
663 NewF->setPersonalityFn(nullptr);
664 NewF->setPrefixData(nullptr);
665 NewF->setPrologueData(nullptr);
666 }
667
Rafael Espindolacaabe222015-12-10 14:19:35 +0000668 return NewGV;
669}
670
671/// Loop over all of the linked values to compute type mappings. For example,
672/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
673/// types 'Foo' but one got renamed when the module was loaded into the same
674/// LLVMContext.
675void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000676 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000677 GlobalValue *DGV = getLinkedToGlobal(&SGV);
678 if (!DGV)
679 continue;
680
681 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
682 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
683 continue;
684 }
685
686 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000687 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
688 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000689 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
690 }
691
Rafael Espindola40358fb2016-02-16 18:50:12 +0000692 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000693 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
694 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
695
Rafael Espindola40358fb2016-02-16 18:50:12 +0000696 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000697 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
698 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
699
700 // Incorporate types by name, scanning all the types in the source module.
701 // At this point, the destination module may have a type "%foo = { i32 }" for
702 // example. When the source module got loaded into the same LLVMContext, if
703 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000704 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000705 for (StructType *ST : Types) {
706 if (!ST->hasName())
707 continue;
708
Hans Wennborgaeacdc22016-11-18 17:33:05 +0000709 if (TypeMap.DstStructTypesSet.hasType(ST)) {
710 // This is actually a type from the destination module.
711 // getIdentifiedStructTypes() can have found it by walking debug info
712 // metadata nodes, some of which get linked by name when ODR Type Uniquing
713 // is enabled on the Context, from the source to the destination module.
714 continue;
715 }
716
Rafael Espindolacaabe222015-12-10 14:19:35 +0000717 // Check to see if there is a dot in the name followed by a digit.
718 size_t DotPos = ST->getName().rfind('.');
719 if (DotPos == 0 || DotPos == StringRef::npos ||
720 ST->getName().back() == '.' ||
721 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
722 continue;
723
724 // Check to see if the destination module has a struct with the prefix name.
725 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
726 if (!DST)
727 continue;
728
729 // Don't use it if this actually came from the source module. They're in
730 // the same LLVMContext after all. Also don't use it unless the type is
731 // actually used in the destination module. This can happen in situations
732 // like this:
733 //
734 // Module A Module B
735 // -------- --------
736 // %Z = type { %A } %B = type { %C.1 }
737 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
738 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
739 // %C = type { i8* } %B.3 = type { %C.1 }
740 //
741 // When we link Module B with Module A, the '%B' in Module B is
742 // used. However, that would then use '%C.1'. But when we process '%C.1',
743 // we prefer to take the '%C' version. So we are then left with both
744 // '%C.1' and '%C' being used for the same types. This leads to some
745 // variables using one type and some using the other.
746 if (TypeMap.DstStructTypesSet.hasType(DST))
747 TypeMap.addTypeMapping(DST, ST);
748 }
749
750 // Now that we have discovered all of the type equivalences, get a body for
751 // any 'opaque' types in the dest module that are now resolved.
752 TypeMap.linkDefinedTypeBodies();
753}
754
755static void getArrayElements(const Constant *C,
756 SmallVectorImpl<Constant *> &Dest) {
757 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
758
759 for (unsigned i = 0; i != NumElements; ++i)
760 Dest.push_back(C->getAggregateElement(i));
761}
762
763/// If there were any appending global variables, link them together now.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000764Expected<Constant *>
765IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
766 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000767 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000768 ->getElementType();
769
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000770 // FIXME: This upgrade is done during linking to support the C API. Once the
771 // old form is deprecated, we should move this upgrade to
772 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
773 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000774 StringRef Name = SrcGV->getName();
775 bool IsNewStructor = false;
776 bool IsOldStructor = false;
777 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
778 if (cast<StructType>(EltTy)->getNumElements() == 3)
779 IsNewStructor = true;
780 else
781 IsOldStructor = true;
782 }
783
784 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
785 if (IsOldStructor) {
786 auto &ST = *cast<StructType>(EltTy);
787 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
788 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
789 }
790
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000791 uint64_t DstNumElements = 0;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000792 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000793 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000794 DstNumElements = DstTy->getNumElements();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000795
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000796 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
797 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000798 "Linking globals named '" + SrcGV->getName() +
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000799 "': can only link appending global with another appending "
800 "global!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000801
802 // Check to see that they two arrays agree on type.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000803 if (EltTy != DstTy->getElementType())
804 return stringErr("Appending variables with different element types!");
805 if (DstGV->isConstant() != SrcGV->isConstant())
806 return stringErr("Appending variables linked with different const'ness!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000807
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000808 if (DstGV->getAlignment() != SrcGV->getAlignment())
809 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000810 "Appending variables with different alignment need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000811
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000812 if (DstGV->getVisibility() != SrcGV->getVisibility())
813 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000814 "Appending variables with different visibility need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000815
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000816 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000817 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000818 "Appending variables with different unnamed_addr need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000819
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000820 if (DstGV->getSection() != SrcGV->getSection())
821 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000822 "Appending variables with different section name need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000823 }
824
Rafael Espindolacaabe222015-12-10 14:19:35 +0000825 SmallVector<Constant *, 16> SrcElements;
826 getArrayElements(SrcGV->getInitializer(), SrcElements);
827
Justin Bogner375f71e2016-08-15 22:41:42 +0000828 if (IsNewStructor) {
829 auto It = remove_if(SrcElements, [this](Constant *E) {
830 auto *Key =
831 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
832 if (!Key)
833 return false;
834 GlobalValue *DGV = getLinkedToGlobal(Key);
835 return !shouldLink(DGV, *Key);
836 });
837 SrcElements.erase(It, SrcElements.end());
838 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000839 uint64_t NewSize = DstNumElements + SrcElements.size();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000840 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
841
842 // Create the new global variable.
843 GlobalVariable *NG = new GlobalVariable(
844 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
845 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
846 SrcGV->getType()->getAddressSpace());
847
848 NG->copyAttributesFrom(SrcGV);
849 forceRenaming(NG, SrcGV->getName());
850
851 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
852
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000853 Mapper.scheduleMapAppendingVariable(*NG,
854 DstGV ? DstGV->getInitializer() : nullptr,
855 IsOldStructor, SrcElements);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000856
857 // Replace any uses of the two global variables with uses of the new
858 // global.
859 if (DstGV) {
860 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
861 DstGV->eraseFromParent();
862 }
863
864 return Ret;
865}
866
Rafael Espindolacaabe222015-12-10 14:19:35 +0000867bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
Davide Italiano95339652016-06-07 14:55:04 +0000868 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000869 return true;
870
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000871 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000872 return false;
873
Davide Italiano95339652016-06-07 14:55:04 +0000874 if (SGV.isDeclaration() || DoneLinkingBodies)
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000875 return false;
Mehdi Amini33661072016-03-11 22:19:06 +0000876
877 // Callback to the client to give a chance to lazily add the Global to the
878 // list of value to link.
879 bool LazilyAdded = false;
880 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
881 maybeAdd(&GV);
882 LazilyAdded = true;
883 });
884 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000885}
886
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000887Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
888 bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000889 GlobalValue *DGV = getLinkedToGlobal(SGV);
890
891 bool ShouldLink = shouldLink(DGV, *SGV);
892
893 // just missing from map
894 if (ShouldLink) {
895 auto I = ValueMap.find(SGV);
896 if (I != ValueMap.end())
897 return cast<Constant>(I->second);
898
899 I = AliasValueMap.find(SGV);
900 if (I != AliasValueMap.end())
901 return cast<Constant>(I->second);
902 }
903
Mehdi Amini33661072016-03-11 22:19:06 +0000904 if (!ShouldLink && ForAlias)
905 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000906
907 // Handle the ultra special appending linkage case first.
908 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
909 if (SGV->hasAppendingLinkage())
910 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
911 cast<GlobalVariable>(SGV));
912
913 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000914 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000915 NewGV = DGV;
916 } else {
917 // If we are done linking global value bodies (i.e. we are performing
918 // metadata linking), don't link in the global value due to this
919 // reference, simply map it to null.
920 if (DoneLinkingBodies)
921 return nullptr;
922
923 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +0000924 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000925 forceRenaming(NewGV, SGV->getName());
926 }
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000927
928 // Overloaded intrinsics have overloaded types names as part of their
929 // names. If we renamed overloaded types we should rename the intrinsic
930 // as well.
931 if (Function *F = dyn_cast<Function>(NewGV))
932 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F))
933 NewGV = Remangled.getValue();
934
Rafael Espindolacaabe222015-12-10 14:19:35 +0000935 if (ShouldLink || ForAlias) {
936 if (const Comdat *SC = SGV->getComdat()) {
937 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
938 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
939 DC->setSelectionKind(SC->getSelectionKind());
940 GO->setComdat(DC);
941 }
942 }
943 }
944
945 if (!ShouldLink && ForAlias)
946 NewGV->setLinkage(GlobalValue::InternalLinkage);
947
948 Constant *C = NewGV;
949 if (DGV)
950 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
951
952 if (DGV && NewGV != DGV) {
953 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
954 DGV->eraseFromParent();
955 }
956
957 return C;
958}
959
960/// Update the initializers in the Dest module now that all globals that may be
961/// referenced are in Dest.
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000962void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000963 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000964 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000965}
966
967/// Copy the source function over into the dest function and fix up references
968/// to values. At this point we know that Dest is an external function, and
969/// that Src is not.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000970Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000971 assert(Dst.isDeclaration() && !Src.isDeclaration());
972
973 // Materialize if needed.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000974 if (Error Err = Src.materialize())
975 return Err;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000976
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000977 // Link in the operands without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000978 if (Src.hasPrefixData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000979 Dst.setPrefixData(Src.getPrefixData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000980 if (Src.hasPrologueData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000981 Dst.setPrologueData(Src.getPrologueData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000982 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000983 Dst.setPersonalityFn(Src.getPersonalityFn());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000984
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000985 // Copy over the metadata attachments without remapping.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000986 Dst.copyMetadata(&Src, 0);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000987
Duncan P. N. Exon Smithbdfc9842016-04-06 06:38:15 +0000988 // Steal arguments and splice the body of Src into Dst.
989 Dst.stealArgumentListFrom(Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000990 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
991
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000992 // Everything has been moved over. Remap it.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000993 Mapper.scheduleRemapFunction(Dst);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000994 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000995}
996
997void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000998 Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000999}
1000
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001001Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001002 if (auto *F = dyn_cast<Function>(&Src))
1003 return linkFunctionBody(cast<Function>(Dst), *F);
1004 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001005 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001006 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001007 }
1008 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001009 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001010}
1011
Teresa Johnson040cc162016-12-12 16:09:30 +00001012void IRLinker::prepareCompileUnitsForImport() {
1013 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
1014 if (!SrcCompileUnits)
1015 return;
1016 // When importing for ThinLTO, prevent importing of types listed on
1017 // the DICompileUnit that we don't need a copy of in the importing
1018 // module. They will be emitted by the originating module.
1019 for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) {
1020 auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I));
1021 assert(CU && "Expected valid compile unit");
1022 // Enums, macros, and retained types don't need to be listed on the
1023 // imported DICompileUnit. This means they will only be imported
1024 // if reached from the mapped IR. Do this by setting their value map
1025 // entries to nullptr, which will automatically prevent their importing
1026 // when reached from the DICompileUnit during metadata mapping.
1027 ValueMap.MD()[CU->getRawEnumTypes()].reset(nullptr);
1028 ValueMap.MD()[CU->getRawMacros()].reset(nullptr);
1029 ValueMap.MD()[CU->getRawRetainedTypes()].reset(nullptr);
1030 // If we ever start importing global variable defs, we'll need to
1031 // add their DIGlobalVariable to the globals list on the imported
1032 // DICompileUnit. Confirm none are imported, and then we can
1033 // map the list of global variables to nullptr.
1034 assert(none_of(
1035 ValuesToLink,
1036 [](const GlobalValue *GV) { return isa<GlobalVariable>(GV); }) &&
1037 "Unexpected importing of a GlobalVariable definition");
1038 ValueMap.MD()[CU->getRawGlobalVariables()].reset(nullptr);
1039
1040 // Imported entities only need to be mapped in if they have local
1041 // scope, as those might correspond to an imported entity inside a
1042 // function being imported (any locally scoped imported entities that
1043 // don't end up referenced by an imported function will not be emitted
1044 // into the object). Imported entities not in a local scope
1045 // (e.g. on the namespace) only need to be emitted by the originating
1046 // module. Create a list of the locally scoped imported entities, and
1047 // replace the source CUs imported entity list with the new list, so
1048 // only those are mapped in.
1049 // FIXME: Locally-scoped imported entities could be moved to the
1050 // functions they are local to instead of listing them on the CU, and
1051 // we would naturally only link in those needed by function importing.
1052 SmallVector<TrackingMDNodeRef, 4> AllImportedModules;
1053 bool ReplaceImportedEntities = false;
1054 for (auto *IE : CU->getImportedEntities()) {
1055 DIScope *Scope = IE->getScope();
1056 assert(Scope && "Invalid Scope encoding!");
1057 if (isa<DILocalScope>(Scope))
1058 AllImportedModules.emplace_back(IE);
1059 else
1060 ReplaceImportedEntities = true;
1061 }
1062 if (ReplaceImportedEntities) {
1063 if (!AllImportedModules.empty())
1064 CU->replaceImportedEntities(MDTuple::get(
1065 CU->getContext(),
1066 SmallVector<Metadata *, 16>(AllImportedModules.begin(),
1067 AllImportedModules.end())));
1068 else
1069 // If there were no local scope imported entities, we can map
1070 // the whole list to nullptr.
1071 ValueMap.MD()[CU->getRawImportedEntities()].reset(nullptr);
1072 }
1073 }
1074}
1075
Rafael Espindolacaabe222015-12-10 14:19:35 +00001076/// Insert all of the named MDNodes in Src into the Dest module.
1077void IRLinker::linkNamedMDNodes() {
Rafael Espindola40358fb2016-02-16 18:50:12 +00001078 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1079 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001080 // Don't link module flags here. Do them separately.
1081 if (&NMD == SrcModFlags)
1082 continue;
1083 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1084 // Add Src elements into Dest node.
Duncan P. N. Exon Smith8a15dab2016-04-15 23:32:44 +00001085 for (const MDNode *Op : NMD.operands())
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001086 DestNMD->addOperand(Mapper.mapMDNode(*Op));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001087 }
1088}
1089
1090/// Merge the linker flags in Src into the Dest module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001091Error IRLinker::linkModuleFlagsMetadata() {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001092 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001093 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001094 if (!SrcModFlags)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001095 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001096
1097 // If the destination module doesn't have module flags yet, then just copy
1098 // over the source module's flags.
1099 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1100 if (DstModFlags->getNumOperands() == 0) {
1101 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1102 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1103
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001104 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001105 }
1106
1107 // First build a map of the existing module flags and requirements.
1108 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1109 SmallSetVector<MDNode *, 16> Requirements;
1110 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1111 MDNode *Op = DstModFlags->getOperand(I);
1112 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1113 MDString *ID = cast<MDString>(Op->getOperand(1));
1114
1115 if (Behavior->getZExtValue() == Module::Require) {
1116 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1117 } else {
1118 Flags[ID] = std::make_pair(Op, I);
1119 }
1120 }
1121
1122 // Merge in the flags from the source module, and also collect its set of
1123 // requirements.
1124 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1125 MDNode *SrcOp = SrcModFlags->getOperand(I);
1126 ConstantInt *SrcBehavior =
1127 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1128 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1129 MDNode *DstOp;
1130 unsigned DstIndex;
1131 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1132 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1133
1134 // If this is a requirement, add it and continue.
1135 if (SrcBehaviorValue == Module::Require) {
1136 // If the destination module does not already have this requirement, add
1137 // it.
1138 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1139 DstModFlags->addOperand(SrcOp);
1140 }
1141 continue;
1142 }
1143
1144 // If there is no existing flag with this ID, just add it.
1145 if (!DstOp) {
1146 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1147 DstModFlags->addOperand(SrcOp);
1148 continue;
1149 }
1150
1151 // Otherwise, perform a merge.
1152 ConstantInt *DstBehavior =
1153 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1154 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1155
1156 // If either flag has override behavior, handle it first.
1157 if (DstBehaviorValue == Module::Override) {
1158 // Diagnose inconsistent flags which both have override behavior.
1159 if (SrcBehaviorValue == Module::Override &&
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001160 SrcOp->getOperand(2) != DstOp->getOperand(2))
1161 return stringErr("linking module flags '" + ID->getString() +
1162 "': IDs have conflicting override values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001163 continue;
1164 } else if (SrcBehaviorValue == Module::Override) {
1165 // Update the destination flag to that of the source.
1166 DstModFlags->setOperand(DstIndex, SrcOp);
1167 Flags[ID].first = SrcOp;
1168 continue;
1169 }
1170
1171 // Diagnose inconsistent merge behavior types.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001172 if (SrcBehaviorValue != DstBehaviorValue)
1173 return stringErr("linking module flags '" + ID->getString() +
1174 "': IDs have conflicting behaviors");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001175
1176 auto replaceDstValue = [&](MDNode *New) {
1177 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1178 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1179 DstModFlags->setOperand(DstIndex, Flag);
1180 Flags[ID].first = Flag;
1181 };
1182
1183 // Perform the merge for standard behavior types.
1184 switch (SrcBehaviorValue) {
1185 case Module::Require:
1186 case Module::Override:
1187 llvm_unreachable("not possible");
1188 case Module::Error: {
1189 // Emit an error if the values differ.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001190 if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1191 return stringErr("linking module flags '" + ID->getString() +
1192 "': IDs have conflicting values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001193 continue;
1194 }
1195 case Module::Warning: {
1196 // Emit a warning if the values differ.
1197 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1198 emitWarning("linking module flags '" + ID->getString() +
1199 "': IDs have conflicting values");
1200 }
1201 continue;
1202 }
1203 case Module::Append: {
1204 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1205 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1206 SmallVector<Metadata *, 8> MDs;
1207 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1208 MDs.append(DstValue->op_begin(), DstValue->op_end());
1209 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1210
1211 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1212 break;
1213 }
1214 case Module::AppendUnique: {
1215 SmallSetVector<Metadata *, 16> Elts;
1216 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1217 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1218 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1219 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1220
1221 replaceDstValue(MDNode::get(DstM.getContext(),
1222 makeArrayRef(Elts.begin(), Elts.end())));
1223 break;
1224 }
1225 }
1226 }
1227
1228 // Check all of the requirements.
1229 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1230 MDNode *Requirement = Requirements[I];
1231 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1232 Metadata *ReqValue = Requirement->getOperand(1);
1233
1234 MDNode *Op = Flags[Flag].first;
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001235 if (!Op || Op->getOperand(2) != ReqValue)
1236 return stringErr("linking module flags '" + Flag->getString() +
1237 "': does not have the required value");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001238 }
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001239 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001240}
1241
1242// This function returns true if the triples match.
1243static bool triplesMatch(const Triple &T0, const Triple &T1) {
1244 // If vendor is apple, ignore the version number.
1245 if (T0.getVendor() == Triple::Apple)
1246 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1247 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1248
1249 return T0 == T1;
1250}
1251
1252// This function returns the merged triple.
1253static std::string mergeTriples(const Triple &SrcTriple,
1254 const Triple &DstTriple) {
1255 // If vendor is apple, pick the triple with the larger version number.
1256 if (SrcTriple.getVendor() == Triple::Apple)
1257 if (DstTriple.isOSVersionLT(SrcTriple))
1258 return SrcTriple.str();
1259
1260 return DstTriple.str();
1261}
1262
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001263Error IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001264 // Ensure metadata materialized before value mapping.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001265 if (SrcM->getMaterializer())
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001266 if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1267 return Err;
Teresa Johnson0556e222016-03-10 18:47:03 +00001268
Rafael Espindolacaabe222015-12-10 14:19:35 +00001269 // Inherit the target data from the source module if the destination module
1270 // doesn't have one already.
1271 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001272 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001273
Rafael Espindola40358fb2016-02-16 18:50:12 +00001274 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001275 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001276 SrcM->getModuleIdentifier() + "' is '" +
1277 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001278 DstM.getModuleIdentifier() + "' is '" +
1279 DstM.getDataLayoutStr() + "'\n");
1280 }
1281
1282 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001283 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1284 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001285
Rafael Espindola40358fb2016-02-16 18:50:12 +00001286 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001287
Rafael Espindola40358fb2016-02-16 18:50:12 +00001288 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001289 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001290 SrcM->getModuleIdentifier() + "' is '" +
1291 SrcM->getTargetTriple() + "' whereas '" +
1292 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1293 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001294
1295 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1296
1297 // Append the module inline asm string.
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +00001298 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001299 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001300 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001301 else
1302 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001303 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001304 }
1305
1306 // Loop over all of the linked values to compute type mappings.
1307 computeTypeMapping();
1308
1309 std::reverse(Worklist.begin(), Worklist.end());
1310 while (!Worklist.empty()) {
1311 GlobalValue *GV = Worklist.back();
1312 Worklist.pop_back();
1313
1314 // Already mapped.
1315 if (ValueMap.find(GV) != ValueMap.end() ||
1316 AliasValueMap.find(GV) != AliasValueMap.end())
1317 continue;
1318
1319 assert(!GV->isDeclaration());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001320 Mapper.mapValue(*GV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001321 if (FoundError)
1322 return std::move(*FoundError);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001323 }
1324
1325 // Note that we are done linking global value bodies. This prevents
1326 // metadata linking from creating new references.
1327 DoneLinkingBodies = true;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001328 Mapper.addFlags(RF_NullMapMissingGlobalValues);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001329
1330 // Remap all of the named MDNodes in Src into the DstM module. We do this
1331 // after linking GlobalValues so that MDNodes that reference GlobalValues
1332 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001333 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001334
Teresa Johnsonb703c772016-03-29 18:24:19 +00001335 // Merge the module flags into the DstM module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001336 return linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001337}
1338
1339IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1340 : ETypes(E), IsPacked(P) {}
1341
1342IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1343 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1344
1345bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
Davide Italiano95339652016-06-07 14:55:04 +00001346 return IsPacked == That.IsPacked && ETypes == That.ETypes;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001347}
1348
1349bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1350 return !this->operator==(That);
1351}
1352
1353StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1354 return DenseMapInfo<StructType *>::getEmptyKey();
1355}
1356
1357StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1358 return DenseMapInfo<StructType *>::getTombstoneKey();
1359}
1360
1361unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1362 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1363 Key.IsPacked);
1364}
1365
1366unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1367 return getHashValue(KeyTy(ST));
1368}
1369
1370bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1371 const StructType *RHS) {
1372 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1373 return false;
1374 return LHS == KeyTy(RHS);
1375}
1376
1377bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1378 const StructType *RHS) {
Davide Italiano95339652016-06-07 14:55:04 +00001379 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1380 return LHS == RHS;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001381 return KeyTy(LHS) == KeyTy(RHS);
1382}
1383
1384void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1385 assert(!Ty->isOpaque());
1386 NonOpaqueStructTypes.insert(Ty);
1387}
1388
1389void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1390 assert(!Ty->isOpaque());
1391 NonOpaqueStructTypes.insert(Ty);
1392 bool Removed = OpaqueStructTypes.erase(Ty);
1393 (void)Removed;
1394 assert(Removed);
1395}
1396
1397void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1398 assert(Ty->isOpaque());
1399 OpaqueStructTypes.insert(Ty);
1400}
1401
1402StructType *
1403IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1404 bool IsPacked) {
1405 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1406 auto I = NonOpaqueStructTypes.find_as(Key);
Davide Italiano95339652016-06-07 14:55:04 +00001407 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001408}
1409
1410bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1411 if (Ty->isOpaque())
1412 return OpaqueStructTypes.count(Ty);
1413 auto I = NonOpaqueStructTypes.find(Ty);
Davide Italiano95339652016-06-07 14:55:04 +00001414 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001415}
1416
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001417IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001418 TypeFinder StructTypes;
Mehdi Aminifec21582016-11-19 18:44:16 +00001419 StructTypes.run(M, /* OnlyNamed */ false);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001420 for (StructType *Ty : StructTypes) {
1421 if (Ty->isOpaque())
1422 IdentifiedStructTypes.addOpaque(Ty);
1423 else
1424 IdentifiedStructTypes.addNonOpaque(Ty);
1425 }
Mehdi Aminiebb34342016-09-03 21:12:33 +00001426 // Self-map metadatas in the destination module. This is needed when
1427 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1428 // destination module may be reached from the source module.
1429 for (auto *MD : StructTypes.getVisitedMetadata()) {
1430 SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1431 }
Rafael Espindolacaabe222015-12-10 14:19:35 +00001432}
1433
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001434Error IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001435 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnson4b9b3792016-10-12 18:39:29 +00001436 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +00001437 bool IsPerformingImport) {
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +00001438 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
Teresa Johnson4b9b3792016-10-12 18:39:29 +00001439 std::move(Src), ValuesToLink, std::move(AddLazyFor),
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +00001440 IsPerformingImport);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001441 Error E = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001442 Composite.dropTriviallyDeadConstantArrays();
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001443 return E;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001444}