blob: 32fa4c76c28a43b1db975692182290aef2e3ac5d [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"
Rafael Espindolacaabe222015-12-10 14:19:35 +000019#include "llvm/IR/TypeFinder.h"
20#include "llvm/Transforms/Utils/Cloning.h"
21using namespace llvm;
22
23//===----------------------------------------------------------------------===//
24// TypeMap implementation.
25//===----------------------------------------------------------------------===//
26
27namespace {
28class TypeMapTy : public ValueMapTypeRemapper {
29 /// This is a mapping from a source type to a destination type to use.
30 DenseMap<Type *, Type *> MappedTypes;
31
32 /// When checking to see if two subgraphs are isomorphic, we speculatively
33 /// add types to MappedTypes, but keep track of them here in case we need to
34 /// roll back.
35 SmallVector<Type *, 16> SpeculativeTypes;
36
37 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
38
39 /// This is a list of non-opaque structs in the source module that are mapped
40 /// to an opaque struct in the destination module.
41 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
42
43 /// This is the set of opaque types in the destination modules who are
44 /// getting a body from the source module.
45 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
46
47public:
48 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
49 : DstStructTypesSet(DstStructTypesSet) {}
50
51 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
52 /// Indicate that the specified type in the destination module is conceptually
53 /// equivalent to the specified type in the source module.
54 void addTypeMapping(Type *DstTy, Type *SrcTy);
55
56 /// Produce a body for an opaque type in the dest module from a type
57 /// definition in the source module.
58 void linkDefinedTypeBodies();
59
60 /// Return the mapped type to use for the specified input type from the
61 /// source module.
62 Type *get(Type *SrcTy);
63 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
64
65 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
66
67 FunctionType *get(FunctionType *T) {
68 return cast<FunctionType>(get((Type *)T));
69 }
70
71private:
72 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
73
74 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
75};
76}
77
78void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
79 assert(SpeculativeTypes.empty());
80 assert(SpeculativeDstOpaqueTypes.empty());
81
82 // Check to see if these types are recursively isomorphic and establish a
83 // mapping between them if so.
84 if (!areTypesIsomorphic(DstTy, SrcTy)) {
85 // Oops, they aren't isomorphic. Just discard this request by rolling out
86 // any speculative mappings we've established.
87 for (Type *Ty : SpeculativeTypes)
88 MappedTypes.erase(Ty);
89
90 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
91 SpeculativeDstOpaqueTypes.size());
92 for (StructType *Ty : SpeculativeDstOpaqueTypes)
93 DstResolvedOpaqueTypes.erase(Ty);
94 } else {
95 for (Type *Ty : SpeculativeTypes)
96 if (auto *STy = dyn_cast<StructType>(Ty))
97 if (STy->hasName())
98 STy->setName("");
99 }
100 SpeculativeTypes.clear();
101 SpeculativeDstOpaqueTypes.clear();
102}
103
104/// Recursively walk this pair of types, returning true if they are isomorphic,
105/// false if they are not.
106bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
107 // Two types with differing kinds are clearly not isomorphic.
108 if (DstTy->getTypeID() != SrcTy->getTypeID())
109 return false;
110
111 // If we have an entry in the MappedTypes table, then we have our answer.
112 Type *&Entry = MappedTypes[SrcTy];
113 if (Entry)
114 return Entry == DstTy;
115
116 // Two identical types are clearly isomorphic. Remember this
117 // non-speculatively.
118 if (DstTy == SrcTy) {
119 Entry = DstTy;
120 return true;
121 }
122
123 // Okay, we have two types with identical kinds that we haven't seen before.
124
125 // If this is an opaque struct type, special case it.
126 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
127 // Mapping an opaque type to any struct, just keep the dest struct.
128 if (SSTy->isOpaque()) {
129 Entry = DstTy;
130 SpeculativeTypes.push_back(SrcTy);
131 return true;
132 }
133
134 // Mapping a non-opaque source type to an opaque dest. If this is the first
135 // type that we're mapping onto this destination type then we succeed. Keep
136 // the dest, but fill it in later. If this is the second (different) type
137 // that we're trying to map onto the same opaque type then we fail.
138 if (cast<StructType>(DstTy)->isOpaque()) {
139 // We can only map one source type onto the opaque destination type.
140 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
141 return false;
142 SrcDefinitionsToResolve.push_back(SSTy);
143 SpeculativeTypes.push_back(SrcTy);
144 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
145 Entry = DstTy;
146 return true;
147 }
148 }
149
150 // If the number of subtypes disagree between the two types, then we fail.
151 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
152 return false;
153
154 // Fail if any of the extra properties (e.g. array size) of the type disagree.
155 if (isa<IntegerType>(DstTy))
156 return false; // bitwidth disagrees.
157 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
158 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
159 return false;
160
161 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
162 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
163 return false;
164 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
165 StructType *SSTy = cast<StructType>(SrcTy);
166 if (DSTy->isLiteral() != SSTy->isLiteral() ||
167 DSTy->isPacked() != SSTy->isPacked())
168 return false;
169 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
170 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
171 return false;
172 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
173 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
174 return false;
175 }
176
177 // Otherwise, we speculate that these two types will line up and recursively
178 // check the subelements.
179 Entry = DstTy;
180 SpeculativeTypes.push_back(SrcTy);
181
182 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
183 if (!areTypesIsomorphic(DstTy->getContainedType(I),
184 SrcTy->getContainedType(I)))
185 return false;
186
187 // If everything seems to have lined up, then everything is great.
188 return true;
189}
190
191void TypeMapTy::linkDefinedTypeBodies() {
192 SmallVector<Type *, 16> Elements;
193 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
194 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
195 assert(DstSTy->isOpaque());
196
197 // Map the body of the source type over to a new body for the dest type.
198 Elements.resize(SrcSTy->getNumElements());
199 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
200 Elements[I] = get(SrcSTy->getElementType(I));
201
202 DstSTy->setBody(Elements, SrcSTy->isPacked());
203 DstStructTypesSet.switchToNonOpaque(DstSTy);
204 }
205 SrcDefinitionsToResolve.clear();
206 DstResolvedOpaqueTypes.clear();
207}
208
209void TypeMapTy::finishType(StructType *DTy, StructType *STy,
210 ArrayRef<Type *> ETypes) {
211 DTy->setBody(ETypes, STy->isPacked());
212
213 // Steal STy's name.
214 if (STy->hasName()) {
215 SmallString<16> TmpName = STy->getName();
216 STy->setName("");
217 DTy->setName(TmpName);
218 }
219
220 DstStructTypesSet.addNonOpaque(DTy);
221}
222
223Type *TypeMapTy::get(Type *Ty) {
224 SmallPtrSet<StructType *, 8> Visited;
225 return get(Ty, Visited);
226}
227
228Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
229 // If we already have an entry for this type, return it.
230 Type **Entry = &MappedTypes[Ty];
231 if (*Entry)
232 return *Entry;
233
234 // These are types that LLVM itself will unique.
235 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
236
237#ifndef NDEBUG
238 if (!IsUniqued) {
239 for (auto &Pair : MappedTypes) {
240 assert(!(Pair.first != Ty && Pair.second == Ty) &&
241 "mapping to a source type");
242 }
243 }
244#endif
245
246 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
247 StructType *DTy = StructType::create(Ty->getContext());
248 return *Entry = DTy;
249 }
250
251 // If this is not a recursive type, then just map all of the elements and
252 // then rebuild the type from inside out.
253 SmallVector<Type *, 4> ElementTypes;
254
255 // If there are no element types to map, then the type is itself. This is
256 // true for the anonymous {} struct, things like 'float', integers, etc.
257 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
258 return *Entry = Ty;
259
260 // Remap all of the elements, keeping track of whether any of them change.
261 bool AnyChange = false;
262 ElementTypes.resize(Ty->getNumContainedTypes());
263 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
264 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
265 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
266 }
267
268 // If we found our type while recursively processing stuff, just use it.
269 Entry = &MappedTypes[Ty];
270 if (*Entry) {
271 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
272 if (DTy->isOpaque()) {
273 auto *STy = cast<StructType>(Ty);
274 finishType(DTy, STy, ElementTypes);
275 }
276 }
277 return *Entry;
278 }
279
280 // If all of the element types mapped directly over and the type is not
281 // a nomed struct, then the type is usable as-is.
282 if (!AnyChange && IsUniqued)
283 return *Entry = Ty;
284
285 // Otherwise, rebuild a modified type.
286 switch (Ty->getTypeID()) {
287 default:
288 llvm_unreachable("unknown derived type to remap");
289 case Type::ArrayTyID:
290 return *Entry = ArrayType::get(ElementTypes[0],
291 cast<ArrayType>(Ty)->getNumElements());
292 case Type::VectorTyID:
293 return *Entry = VectorType::get(ElementTypes[0],
294 cast<VectorType>(Ty)->getNumElements());
295 case Type::PointerTyID:
296 return *Entry = PointerType::get(ElementTypes[0],
297 cast<PointerType>(Ty)->getAddressSpace());
298 case Type::FunctionTyID:
299 return *Entry = FunctionType::get(ElementTypes[0],
300 makeArrayRef(ElementTypes).slice(1),
301 cast<FunctionType>(Ty)->isVarArg());
302 case Type::StructTyID: {
303 auto *STy = cast<StructType>(Ty);
304 bool IsPacked = STy->isPacked();
305 if (IsUniqued)
306 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
307
308 // If the type is opaque, we can just use it directly.
309 if (STy->isOpaque()) {
310 DstStructTypesSet.addOpaque(STy);
311 return *Entry = Ty;
312 }
313
314 if (StructType *OldT =
315 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
316 STy->setName("");
317 return *Entry = OldT;
318 }
319
320 if (!AnyChange) {
321 DstStructTypesSet.addNonOpaque(STy);
322 return *Entry = Ty;
323 }
324
325 StructType *DTy = StructType::create(Ty->getContext());
326 finishType(DTy, STy, ElementTypes);
327 return *Entry = DTy;
328 }
329 }
330}
331
332LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
333 const Twine &Msg)
334 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
335void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
336
337//===----------------------------------------------------------------------===//
Teresa Johnsonbef54362015-12-18 19:28:59 +0000338// IRLinker implementation.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000339//===----------------------------------------------------------------------===//
340
341namespace {
342class IRLinker;
343
344/// Creates prototypes for functions that are lazily linked on the fly. This
345/// speeds up linking for modules with many/ lazily linked functions of which
346/// few get used.
347class GlobalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000348 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000349
350public:
Mehdi Amini33661072016-03-11 22:19:06 +0000351 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Rafael Espindolacaabe222015-12-10 14:19:35 +0000352 Value *materializeDeclFor(Value *V) override;
353 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000354 Metadata *mapTemporaryMetadata(Metadata *MD) override;
355 void replaceTemporaryMetadata(const Metadata *OrigMD,
356 Metadata *NewMD) override;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000357 bool isMetadataNeeded(Metadata *MD) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000358};
359
360class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000361 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000362
363public:
Mehdi Amini33661072016-03-11 22:19:06 +0000364 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Rafael Espindolacaabe222015-12-10 14:19:35 +0000365 Value *materializeDeclFor(Value *V) override;
366 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000367 Metadata *mapTemporaryMetadata(Metadata *MD) override;
368 void replaceTemporaryMetadata(const Metadata *OrigMD,
369 Metadata *NewMD) override;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000370 bool isMetadataNeeded(Metadata *MD) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000371};
372
373/// This is responsible for keeping track of the state used for moving data
374/// from SrcM to DstM.
375class IRLinker {
376 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000377 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000378
Mehdi Amini33661072016-03-11 22:19:06 +0000379 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000380 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
381
382 TypeMapTy TypeMap;
383 GlobalValueMaterializer GValMaterializer;
384 LocalValueMaterializer LValMaterializer;
385
386 /// Mapping of values from what they used to be in Src, to what they are now
387 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
388 /// due to the use of Value handles which the Linker doesn't actually need,
389 /// but this allows us to reuse the ValueMapper code.
390 ValueToValueMapTy ValueMap;
391 ValueToValueMapTy AliasValueMap;
392
393 DenseSet<GlobalValue *> ValuesToLink;
394 std::vector<GlobalValue *> Worklist;
395
396 void maybeAdd(GlobalValue *GV) {
397 if (ValuesToLink.insert(GV).second)
398 Worklist.push_back(GV);
399 }
400
Rafael Espindolacaabe222015-12-10 14:19:35 +0000401 /// Set to true when all global value body linking is complete (including
402 /// lazy linking). Used to prevent metadata linking from creating new
403 /// references.
404 bool DoneLinkingBodies = false;
405
406 bool HasError = false;
407
Teresa Johnsone5a61912015-12-17 17:14:09 +0000408 /// Flag indicating that we are just linking metadata (after function
409 /// importing).
410 bool IsMetadataLinkingPostpass;
411
412 /// Flags to pass to value mapper invocations.
413 RemapFlags ValueMapperFlags = RF_MoveDistinctMDs;
414
415 /// Association between metadata values created during bitcode parsing and
416 /// the value id. Used to correlate temporary metadata created during
417 /// function importing with the final metadata parsed during the subsequent
418 /// metadata linking postpass.
Teresa Johnson61b406e2015-12-29 23:00:22 +0000419 DenseMap<const Metadata *, unsigned> MetadataToIDs;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000420
421 /// Association between metadata value id and temporary metadata that
422 /// remains unmapped after function importing. Saved during function
423 /// importing and consumed during the metadata linking postpass.
424 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
425
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000426 /// Set of subprogram metadata that does not need to be linked into the
427 /// destination module, because the functions were not imported directly
428 /// or via an inlined body in an imported function.
429 SmallPtrSet<const Metadata *, 16> UnneededSubprograms;
430
Rafael Espindolacaabe222015-12-10 14:19:35 +0000431 /// Handles cloning of a global values from the source module into
432 /// the destination module, including setting the attributes and visibility.
433 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
434
435 /// Helper method for setting a message and returning an error code.
436 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000437 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000438 HasError = true;
439 return true;
440 }
441
442 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000443 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000444 }
445
Teresa Johnsone5a61912015-12-17 17:14:09 +0000446 /// Check whether we should be linking metadata from the source module.
447 bool shouldLinkMetadata() {
448 // ValIDToTempMDMap will be non-null when we are importing or otherwise want
449 // to link metadata lazily, and then when linking the metadata.
450 // We only want to return true for the former case.
451 return ValIDToTempMDMap == nullptr || IsMetadataLinkingPostpass;
452 }
453
Rafael Espindolacaabe222015-12-10 14:19:35 +0000454 /// Given a global in the source module, return the global in the
455 /// destination module that is being linked to, if any.
456 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
457 // If the source has no name it can't link. If it has local linkage,
458 // there is no name match-up going on.
459 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
460 return nullptr;
461
462 // Otherwise see if we have a match in the destination module's symtab.
463 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
464 if (!DGV)
465 return nullptr;
466
467 // If we found a global with the same name in the dest module, but it has
468 // internal linkage, we are really not doing any linkage here.
469 if (DGV->hasLocalLinkage())
470 return nullptr;
471
472 // Otherwise, we do in fact link to the destination global.
473 return DGV;
474 }
475
476 void computeTypeMapping();
477
478 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
479 const GlobalVariable *SrcGV);
480
Mehdi Amini33661072016-03-11 22:19:06 +0000481 /// Given the GlobaValue \p SGV in the source module, and the matching
482 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
483 /// into the destination module.
484 ///
485 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000486 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
487 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
488
489 bool linkModuleFlagsMetadata();
490
491 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
492 bool linkFunctionBody(Function &Dst, Function &Src);
493 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
494 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
495
496 /// Functions that take care of cloning a specific global value type
497 /// into the destination module.
498 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
499 Function *copyFunctionProto(const Function *SF);
500 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
501
502 void linkNamedMDNodes();
503
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000504 /// Populate the UnneededSubprograms set with the DISubprogram metadata
505 /// from the source module that we don't need to link into the dest module,
506 /// because the functions were not imported directly or via an inlined body
507 /// in an imported function.
Rafael Espindola394524d2016-01-21 00:00:53 +0000508 void findNeededSubprograms();
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000509
Teresa Johnson71d12d22016-01-25 22:04:56 +0000510 /// Recursive helper for findNeededSubprograms to locate any DISubprogram
511 /// reached from the given Node, marking any found as needed.
512 void findReachedSubprograms(const MDNode *Node,
513 SmallPtrSet<const MDNode *, 16> &Visited);
514
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000515 /// The value mapper leaves nulls in the list of subprograms for any
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +0000516 /// in the UnneededSubprograms map. Strip those out of the mapped
517 /// compile unit.
518 void stripNullSubprograms(DICompileUnit *CU);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000519
Rafael Espindolacaabe222015-12-10 14:19:35 +0000520public:
Rafael Espindola40358fb2016-02-16 18:50:12 +0000521 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set,
522 std::unique_ptr<Module> SrcM, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000523 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
524 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr,
525 bool IsMetadataLinkingPostpass = false)
Rafael Espindola40358fb2016-02-16 18:50:12 +0000526 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set),
Mehdi Amini33661072016-03-11 22:19:06 +0000527 GValMaterializer(*this), LValMaterializer(*this),
Teresa Johnsone5a61912015-12-17 17:14:09 +0000528 IsMetadataLinkingPostpass(IsMetadataLinkingPostpass),
529 ValIDToTempMDMap(ValIDToTempMDMap) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000530 for (GlobalValue *GV : ValuesToLink)
531 maybeAdd(GV);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000532
533 // If appropriate, tell the value mapper that it can expect to see
534 // temporary metadata.
535 if (!shouldLinkMetadata())
536 ValueMapperFlags = ValueMapperFlags | RF_HaveUnmaterializedMetadata;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000537 }
538
Teresa Johnsoncc428572015-12-30 19:32:24 +0000539 ~IRLinker() {
540 // In the case where we are not linking metadata, we unset the CanReplace
541 // flag on all temporary metadata in the MetadataToIDs map to ensure
542 // none was replaced while being a map key. Now that we are destructing
543 // the map, set the flag back to true, so that it is replaceable during
544 // metadata linking.
545 if (!shouldLinkMetadata()) {
546 for (auto MDI : MetadataToIDs) {
547 Metadata *MD = const_cast<Metadata *>(MDI.first);
548 MDNode *Node = dyn_cast<MDNode>(MD);
549 assert((Node && Node->isTemporary()) &&
550 "Found non-temp metadata in map when not linking metadata");
551 Node->setCanReplace(true);
552 }
553 }
554 }
555
Rafael Espindolacaabe222015-12-10 14:19:35 +0000556 bool run();
557 Value *materializeDeclFor(Value *V, bool ForAlias);
558 void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000559
560 /// Save the mapping between the given temporary metadata and its metadata
561 /// value id. Used to support metadata linking as a postpass for function
562 /// importing.
563 Metadata *mapTemporaryMetadata(Metadata *MD);
564
565 /// Replace any temporary metadata saved for the source metadata's id with
566 /// the new non-temporary metadata. Used when metadata linking as a postpass
567 /// for function importing.
568 void replaceTemporaryMetadata(const Metadata *OrigMD, Metadata *NewMD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000569
570 /// Indicates whether we need to map the given metadata into the destination
571 /// module. Used to prevent linking of metadata only needed by functions not
572 /// linked into the dest module.
573 bool isMetadataNeeded(Metadata *MD);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000574};
575}
576
577/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
578/// table. This is good for all clients except for us. Go through the trouble
579/// to force this back.
580static void forceRenaming(GlobalValue *GV, StringRef Name) {
581 // If the global doesn't force its name or if it already has the right name,
582 // there is nothing for us to do.
583 if (GV->hasLocalLinkage() || GV->getName() == Name)
584 return;
585
586 Module *M = GV->getParent();
587
588 // If there is a conflict, rename the conflict.
589 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
590 GV->takeName(ConflictGV);
591 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
592 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
593 } else {
594 GV->setName(Name); // Force the name back
595 }
596}
597
598Value *GlobalValueMaterializer::materializeDeclFor(Value *V) {
Mehdi Amini33661072016-03-11 22:19:06 +0000599 return TheIRLinker.materializeDeclFor(V, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000600}
601
602void GlobalValueMaterializer::materializeInitFor(GlobalValue *New,
603 GlobalValue *Old) {
Mehdi Amini33661072016-03-11 22:19:06 +0000604 TheIRLinker.materializeInitFor(New, Old, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000605}
606
Teresa Johnsone5a61912015-12-17 17:14:09 +0000607Metadata *GlobalValueMaterializer::mapTemporaryMetadata(Metadata *MD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000608 return TheIRLinker.mapTemporaryMetadata(MD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000609}
610
611void GlobalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD,
612 Metadata *NewMD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000613 TheIRLinker.replaceTemporaryMetadata(OrigMD, NewMD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000614}
615
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000616bool GlobalValueMaterializer::isMetadataNeeded(Metadata *MD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000617 return TheIRLinker.isMetadataNeeded(MD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000618}
619
Rafael Espindolacaabe222015-12-10 14:19:35 +0000620Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
Mehdi Amini33661072016-03-11 22:19:06 +0000621 return TheIRLinker.materializeDeclFor(V, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000622}
623
624void LocalValueMaterializer::materializeInitFor(GlobalValue *New,
625 GlobalValue *Old) {
Mehdi Amini33661072016-03-11 22:19:06 +0000626 TheIRLinker.materializeInitFor(New, Old, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000627}
628
Teresa Johnsone5a61912015-12-17 17:14:09 +0000629Metadata *LocalValueMaterializer::mapTemporaryMetadata(Metadata *MD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000630 return TheIRLinker.mapTemporaryMetadata(MD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000631}
632
633void LocalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD,
634 Metadata *NewMD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000635 TheIRLinker.replaceTemporaryMetadata(OrigMD, NewMD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000636}
637
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000638bool LocalValueMaterializer::isMetadataNeeded(Metadata *MD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000639 return TheIRLinker.isMetadataNeeded(MD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000640}
641
Rafael Espindolacaabe222015-12-10 14:19:35 +0000642Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) {
643 auto *SGV = dyn_cast<GlobalValue>(V);
644 if (!SGV)
645 return nullptr;
646
647 return linkGlobalValueProto(SGV, ForAlias);
648}
649
650void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old,
651 bool ForAlias) {
652 // If we already created the body, just return.
653 if (auto *F = dyn_cast<Function>(New)) {
654 if (!F->isDeclaration())
655 return;
656 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
657 if (V->hasInitializer())
658 return;
659 } else {
660 auto *A = cast<GlobalAlias>(New);
661 if (A->getAliasee())
662 return;
663 }
664
665 if (ForAlias || shouldLink(New, *Old))
666 linkGlobalValueBody(*New, *Old);
667}
668
Teresa Johnsone5a61912015-12-17 17:14:09 +0000669Metadata *IRLinker::mapTemporaryMetadata(Metadata *MD) {
670 if (!ValIDToTempMDMap)
671 return nullptr;
672 // If this temporary metadata has a value id recorded during function
673 // parsing, record that in the ValIDToTempMDMap if one was provided.
Teresa Johnson6f508af2016-01-21 16:46:40 +0000674 auto I = MetadataToIDs.find(MD);
Teresa Johnsonf5aa64f2016-01-21 17:16:53 +0000675 if (I == MetadataToIDs.end())
676 return nullptr;
677 unsigned Idx = I->second;
678 MDNode *Node = cast<MDNode>(MD);
679 assert(Node->isTemporary());
680 // If we created a temp MD when importing a different function from
681 // this module, reuse the same temporary metadata.
682 auto IterBool = ValIDToTempMDMap->insert(std::make_pair(Idx, Node));
683 return IterBool.first->second;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000684}
685
686void IRLinker::replaceTemporaryMetadata(const Metadata *OrigMD,
687 Metadata *NewMD) {
688 if (!ValIDToTempMDMap)
689 return;
690#ifndef NDEBUG
691 auto *N = dyn_cast_or_null<MDNode>(NewMD);
692 assert(!N || !N->isTemporary());
693#endif
694 // If a mapping between metadata value ids and temporary metadata
695 // created during function importing was provided, and the source
696 // metadata has a value id recorded during metadata parsing, replace
697 // the temporary metadata with the final mapped metadata now.
Teresa Johnson6f508af2016-01-21 16:46:40 +0000698 auto I = MetadataToIDs.find(OrigMD);
Teresa Johnsonf5aa64f2016-01-21 17:16:53 +0000699 if (I == MetadataToIDs.end())
700 return;
701 unsigned Idx = I->second;
702 auto VI = ValIDToTempMDMap->find(Idx);
703 // Nothing to do if we didn't need to create a temporary metadata during
704 // function importing.
705 if (VI == ValIDToTempMDMap->end())
706 return;
707 MDNode *TempMD = VI->second;
708 TempMD->replaceAllUsesWith(NewMD);
709 MDNode::deleteTemporary(TempMD);
710 ValIDToTempMDMap->erase(VI);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000711}
712
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000713bool IRLinker::isMetadataNeeded(Metadata *MD) {
714 // Currently only DISubprogram metadata is marked as being unneeded.
715 if (UnneededSubprograms.empty())
716 return true;
717 MDNode *Node = dyn_cast<MDNode>(MD);
718 if (!Node)
719 return true;
720 DISubprogram *SP = getDISubprogram(Node);
721 if (!SP)
722 return true;
723 return !UnneededSubprograms.count(SP);
724}
725
Rafael Espindolacaabe222015-12-10 14:19:35 +0000726/// Loop through the global variables in the src module and merge them into the
727/// dest module.
728GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
729 // No linking to be performed or linking from the source: simply create an
730 // identical version of the symbol over in the dest module... the
731 // initializer will be filled in later by LinkGlobalInits.
732 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000733 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000734 SGVar->isConstant(), GlobalValue::ExternalLinkage,
735 /*init*/ nullptr, SGVar->getName(),
736 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
737 SGVar->getType()->getAddressSpace());
738 NewDGV->setAlignment(SGVar->getAlignment());
739 return NewDGV;
740}
741
742/// Link the function in the source module into the destination module if
743/// needed, setting up mapping information.
744Function *IRLinker::copyFunctionProto(const Function *SF) {
745 // If there is no linkage to be performed or we are linking from the source,
746 // bring SF over.
747 return Function::Create(TypeMap.get(SF->getFunctionType()),
748 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
749}
750
751/// Set up prototypes for any aliases that come over from the source module.
752GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
753 // If there is no linkage to be performed or we're linking from the source,
754 // bring over SGA.
755 auto *Ty = TypeMap.get(SGA->getValueType());
756 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
757 GlobalValue::ExternalLinkage, SGA->getName(),
758 &DstM);
759}
760
761GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
762 bool ForDefinition) {
763 GlobalValue *NewGV;
764 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
765 NewGV = copyGlobalVariableProto(SGVar);
766 } else if (auto *SF = dyn_cast<Function>(SGV)) {
767 NewGV = copyFunctionProto(SF);
768 } else {
769 if (ForDefinition)
770 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
771 else
772 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000773 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000774 /*isConstant*/ false, GlobalValue::ExternalLinkage,
775 /*init*/ nullptr, SGV->getName(),
776 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
777 SGV->getType()->getAddressSpace());
778 }
779
780 if (ForDefinition)
781 NewGV->setLinkage(SGV->getLinkage());
782 else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() ||
783 SGV->hasLinkOnceLinkage())
784 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
785
786 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000787
788 // Remove these copied constants in case this stays a declaration, since
789 // they point to the source module. If the def is linked the values will
790 // be mapped in during linkFunctionBody.
791 if (auto *NewF = dyn_cast<Function>(NewGV)) {
792 NewF->setPersonalityFn(nullptr);
793 NewF->setPrefixData(nullptr);
794 NewF->setPrologueData(nullptr);
795 }
796
Rafael Espindolacaabe222015-12-10 14:19:35 +0000797 return NewGV;
798}
799
800/// Loop over all of the linked values to compute type mappings. For example,
801/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
802/// types 'Foo' but one got renamed when the module was loaded into the same
803/// LLVMContext.
804void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000805 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000806 GlobalValue *DGV = getLinkedToGlobal(&SGV);
807 if (!DGV)
808 continue;
809
810 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
811 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
812 continue;
813 }
814
815 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000816 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
817 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000818 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
819 }
820
Rafael Espindola40358fb2016-02-16 18:50:12 +0000821 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000822 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
823 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
824
Rafael Espindola40358fb2016-02-16 18:50:12 +0000825 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000826 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
827 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
828
829 // Incorporate types by name, scanning all the types in the source module.
830 // At this point, the destination module may have a type "%foo = { i32 }" for
831 // example. When the source module got loaded into the same LLVMContext, if
832 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000833 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000834 for (StructType *ST : Types) {
835 if (!ST->hasName())
836 continue;
837
838 // Check to see if there is a dot in the name followed by a digit.
839 size_t DotPos = ST->getName().rfind('.');
840 if (DotPos == 0 || DotPos == StringRef::npos ||
841 ST->getName().back() == '.' ||
842 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
843 continue;
844
845 // Check to see if the destination module has a struct with the prefix name.
846 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
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,
877 SmallVectorImpl<Constant *> &Dest) {
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.
885/// Return true on error.
886Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
887 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000888 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000889 ->getElementType();
890
891 StringRef Name = SrcGV->getName();
892 bool IsNewStructor = false;
893 bool IsOldStructor = false;
894 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
895 if (cast<StructType>(EltTy)->getNumElements() == 3)
896 IsNewStructor = true;
897 else
898 IsOldStructor = true;
899 }
900
901 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
902 if (IsOldStructor) {
903 auto &ST = *cast<StructType>(EltTy);
904 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
905 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
906 }
907
908 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000909 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000910
911 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
912 emitError(
913 "Linking globals named '" + SrcGV->getName() +
914 "': can only link appending global with another appending global!");
915 return nullptr;
916 }
917
918 // Check to see that they two arrays agree on type.
919 if (EltTy != DstTy->getElementType()) {
920 emitError("Appending variables with different element types!");
921 return nullptr;
922 }
923 if (DstGV->isConstant() != SrcGV->isConstant()) {
924 emitError("Appending variables linked with different const'ness!");
925 return nullptr;
926 }
927
928 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
929 emitError(
930 "Appending variables with different alignment need to be linked!");
931 return nullptr;
932 }
933
934 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
935 emitError(
936 "Appending variables with different visibility need to be linked!");
937 return nullptr;
938 }
939
940 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
941 emitError(
942 "Appending variables with different unnamed_addr need to be linked!");
943 return nullptr;
944 }
945
946 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
947 emitError(
948 "Appending variables with different section name need to be linked!");
949 return nullptr;
950 }
951 }
952
953 SmallVector<Constant *, 16> DstElements;
954 if (DstGV)
955 getArrayElements(DstGV->getInitializer(), DstElements);
956
957 SmallVector<Constant *, 16> SrcElements;
958 getArrayElements(SrcGV->getInitializer(), SrcElements);
959
960 if (IsNewStructor)
961 SrcElements.erase(
962 std::remove_if(SrcElements.begin(), SrcElements.end(),
963 [this](Constant *E) {
964 auto *Key = dyn_cast<GlobalValue>(
965 E->getAggregateElement(2)->stripPointerCasts());
966 if (!Key)
967 return false;
968 GlobalValue *DGV = getLinkedToGlobal(Key);
969 return !shouldLink(DGV, *Key);
970 }),
971 SrcElements.end());
972 uint64_t NewSize = DstElements.size() + SrcElements.size();
973 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
974
975 // Create the new global variable.
976 GlobalVariable *NG = new GlobalVariable(
977 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
978 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
979 SrcGV->getType()->getAddressSpace());
980
981 NG->copyAttributesFrom(SrcGV);
982 forceRenaming(NG, SrcGV->getName());
983
984 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
985
986 // Stop recursion.
987 ValueMap[SrcGV] = Ret;
988
989 for (auto *V : SrcElements) {
990 Constant *NewV;
991 if (IsOldStructor) {
992 auto *S = cast<ConstantStruct>(V);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000993 auto *E1 = MapValue(S->getOperand(0), ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +0000994 &TypeMap, &GValMaterializer);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000995 auto *E2 = MapValue(S->getOperand(1), ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +0000996 &TypeMap, &GValMaterializer);
997 Value *Null = Constant::getNullValue(VoidPtrTy);
998 NewV =
999 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
1000 } else {
Teresa Johnsone5a61912015-12-17 17:14:09 +00001001 NewV =
1002 MapValue(V, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001003 }
1004 DstElements.push_back(NewV);
1005 }
1006
1007 NG->setInitializer(ConstantArray::get(NewType, DstElements));
1008
1009 // Replace any uses of the two global variables with uses of the new
1010 // global.
1011 if (DstGV) {
1012 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1013 DstGV->eraseFromParent();
1014 }
1015
1016 return Ret;
1017}
1018
Rafael Espindolacaabe222015-12-10 14:19:35 +00001019bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
Teresa Johnsone5a61912015-12-17 17:14:09 +00001020 // Already imported all the values. Just map to the Dest value
1021 // in case it is referenced in the metadata.
1022 if (IsMetadataLinkingPostpass) {
1023 assert(!ValuesToLink.count(&SGV) &&
1024 "Source value unexpectedly requested for link during metadata link");
1025 return false;
1026 }
1027
Rafael Espindolacaabe222015-12-10 14:19:35 +00001028 if (ValuesToLink.count(&SGV))
1029 return true;
1030
1031 if (SGV.hasLocalLinkage())
1032 return true;
1033
Rafael Espindola55a7ae52016-01-20 22:38:23 +00001034 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +00001035 return false;
1036
1037 if (SGV.hasAvailableExternallyLinkage())
1038 return true;
1039
1040 if (DoneLinkingBodies)
1041 return false;
1042
Mehdi Amini33661072016-03-11 22:19:06 +00001043
1044 // Callback to the client to give a chance to lazily add the Global to the
1045 // list of value to link.
1046 bool LazilyAdded = false;
1047 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
1048 maybeAdd(&GV);
1049 LazilyAdded = true;
1050 });
1051 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001052}
1053
1054Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
1055 GlobalValue *DGV = getLinkedToGlobal(SGV);
1056
1057 bool ShouldLink = shouldLink(DGV, *SGV);
1058
1059 // just missing from map
1060 if (ShouldLink) {
1061 auto I = ValueMap.find(SGV);
1062 if (I != ValueMap.end())
1063 return cast<Constant>(I->second);
1064
1065 I = AliasValueMap.find(SGV);
1066 if (I != AliasValueMap.end())
1067 return cast<Constant>(I->second);
1068 }
1069
Mehdi Amini33661072016-03-11 22:19:06 +00001070 if (!ShouldLink && ForAlias)
1071 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001072
1073 // Handle the ultra special appending linkage case first.
1074 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1075 if (SGV->hasAppendingLinkage())
1076 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1077 cast<GlobalVariable>(SGV));
1078
1079 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +00001080 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001081 NewGV = DGV;
1082 } else {
1083 // If we are done linking global value bodies (i.e. we are performing
1084 // metadata linking), don't link in the global value due to this
1085 // reference, simply map it to null.
1086 if (DoneLinkingBodies)
1087 return nullptr;
1088
1089 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +00001090 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +00001091 forceRenaming(NewGV, SGV->getName());
1092 }
1093 if (ShouldLink || ForAlias) {
1094 if (const Comdat *SC = SGV->getComdat()) {
1095 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1096 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1097 DC->setSelectionKind(SC->getSelectionKind());
1098 GO->setComdat(DC);
1099 }
1100 }
1101 }
1102
1103 if (!ShouldLink && ForAlias)
1104 NewGV->setLinkage(GlobalValue::InternalLinkage);
1105
1106 Constant *C = NewGV;
1107 if (DGV)
1108 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1109
1110 if (DGV && NewGV != DGV) {
1111 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1112 DGV->eraseFromParent();
1113 }
1114
1115 return C;
1116}
1117
1118/// Update the initializers in the Dest module now that all globals that may be
1119/// referenced are in Dest.
1120void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1121 // Figure out what the initializer looks like in the dest module.
Teresa Johnsone5a61912015-12-17 17:14:09 +00001122 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, ValueMapperFlags,
1123 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001124}
1125
1126/// Copy the source function over into the dest function and fix up references
1127/// to values. At this point we know that Dest is an external function, and
1128/// that Src is not.
1129bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1130 assert(Dst.isDeclaration() && !Src.isDeclaration());
1131
1132 // Materialize if needed.
1133 if (std::error_code EC = Src.materialize())
1134 return emitError(EC.message());
1135
Teresa Johnsone5a61912015-12-17 17:14:09 +00001136 if (!shouldLinkMetadata())
1137 // This is only supported for lazy links. Do after materialization of
1138 // a function and before remapping metadata on instructions below
1139 // in RemapInstruction, as the saved mapping is used to handle
1140 // the temporary metadata hanging off instructions.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001141 SrcM->getMaterializer()->saveMetadataList(MetadataToIDs,
1142 /* OnlyTempMD = */ true);
Teresa Johnsone5a61912015-12-17 17:14:09 +00001143
Rafael Espindolacaabe222015-12-10 14:19:35 +00001144 // Link in the prefix data.
1145 if (Src.hasPrefixData())
Teresa Johnsone5a61912015-12-17 17:14:09 +00001146 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, ValueMapperFlags,
1147 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001148
1149 // Link in the prologue data.
1150 if (Src.hasPrologueData())
1151 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001152 ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001153 &GValMaterializer));
1154
1155 // Link in the personality function.
1156 if (Src.hasPersonalityFn())
1157 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001158 ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001159 &GValMaterializer));
1160
1161 // Go through and convert function arguments over, remembering the mapping.
1162 Function::arg_iterator DI = Dst.arg_begin();
1163 for (Argument &Arg : Src.args()) {
1164 DI->setName(Arg.getName()); // Copy the name over.
1165
1166 // Add a mapping to our mapping.
1167 ValueMap[&Arg] = &*DI;
1168 ++DI;
1169 }
1170
1171 // Copy over the metadata attachments.
1172 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1173 Src.getAllMetadata(MDs);
1174 for (const auto &I : MDs)
Teresa Johnsone5a61912015-12-17 17:14:09 +00001175 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001176 &TypeMap, &GValMaterializer));
1177
1178 // Splice the body of the source function into the dest function.
1179 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1180
1181 // At this point, all of the instructions and values of the function are now
1182 // copied over. The only problem is that they are still referencing values in
1183 // the Source function as operands. Loop through all of the operands of the
1184 // functions and patch them up to point to the local versions.
1185 for (BasicBlock &BB : Dst)
1186 for (Instruction &I : BB)
Teresa Johnsone5a61912015-12-17 17:14:09 +00001187 RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries | ValueMapperFlags,
1188 &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001189
1190 // There is no need to map the arguments anymore.
1191 for (Argument &Arg : Src.args())
1192 ValueMap.erase(&Arg);
1193
Rafael Espindolacaabe222015-12-10 14:19:35 +00001194 return false;
1195}
1196
1197void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1198 Constant *Aliasee = Src.getAliasee();
Teresa Johnsone5a61912015-12-17 17:14:09 +00001199 Constant *Val = MapValue(Aliasee, AliasValueMap, ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001200 &LValMaterializer);
1201 Dst.setAliasee(Val);
1202}
1203
1204bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1205 if (auto *F = dyn_cast<Function>(&Src))
1206 return linkFunctionBody(cast<Function>(Dst), *F);
1207 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1208 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1209 return false;
1210 }
1211 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1212 return false;
1213}
1214
Teresa Johnson71d12d22016-01-25 22:04:56 +00001215void IRLinker::findReachedSubprograms(
1216 const MDNode *Node, SmallPtrSet<const MDNode *, 16> &Visited) {
1217 if (!Visited.insert(Node).second)
1218 return;
1219 DISubprogram *SP = getDISubprogram(Node);
1220 if (SP)
1221 UnneededSubprograms.erase(SP);
1222 for (auto &Op : Node->operands()) {
1223 const MDNode *OpN = dyn_cast_or_null<MDNode>(Op.get());
1224 if (!OpN)
1225 continue;
1226 findReachedSubprograms(OpN, Visited);
1227 }
1228}
1229
Rafael Espindola394524d2016-01-21 00:00:53 +00001230void IRLinker::findNeededSubprograms() {
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001231 // Track unneeded nodes to make it simpler to handle the case
1232 // where we are checking if an already-mapped SP is needed.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001233 NamedMDNode *CompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001234 if (!CompileUnits)
1235 return;
1236 for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
1237 auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
1238 assert(CU && "Expected valid compile unit");
Teresa Johnsonb9515582016-01-07 00:06:27 +00001239 // Ensure that we don't remove subprograms referenced by DIImportedEntity.
Ahmed Bougachaa7324a22016-01-07 03:14:59 +00001240 // It is not legal to have a DIImportedEntity with a null entity or scope.
Teresa Johnsonf07db002016-01-25 21:29:55 +00001241 // Using getDISubprogram handles the case where the subprogram is reached
1242 // via an intervening DILexicalBlock.
Teresa Johnsonb9515582016-01-07 00:06:27 +00001243 // FIXME: The DISubprogram for functions not linked in but kept due to
1244 // being referenced by a DIImportedEntity should also get their
1245 // IsDefinition flag is unset.
1246 SmallPtrSet<DISubprogram *, 8> ImportedEntitySPs;
1247 for (auto *IE : CU->getImportedEntities()) {
Teresa Johnsonf07db002016-01-25 21:29:55 +00001248 if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getEntity())))
Teresa Johnsonb9515582016-01-07 00:06:27 +00001249 ImportedEntitySPs.insert(SP);
Teresa Johnsonf07db002016-01-25 21:29:55 +00001250 if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getScope())))
Ahmed Bougachaa7324a22016-01-07 03:14:59 +00001251 ImportedEntitySPs.insert(SP);
Teresa Johnsonb9515582016-01-07 00:06:27 +00001252 }
Teresa Johnsond213aa42015-12-22 01:17:19 +00001253 for (auto *Op : CU->getSubprograms()) {
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001254 // Unless we were doing function importing and deferred metadata linking,
1255 // any needed SPs should have been mapped as they would be reached
1256 // from the function linked in (either on the function itself for linked
1257 // function bodies, or from DILocation on inlined instructions).
1258 assert(!(ValueMap.MD()[Op] && IsMetadataLinkingPostpass) &&
1259 "DISubprogram shouldn't be mapped yet");
Teresa Johnsonb9515582016-01-07 00:06:27 +00001260 if (!ValueMap.MD()[Op] && !ImportedEntitySPs.count(Op))
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001261 UnneededSubprograms.insert(Op);
1262 }
1263 }
1264 if (!IsMetadataLinkingPostpass)
1265 return;
1266 // In the case of metadata linking as a postpass (e.g. for function
Teresa Johnson71d12d22016-01-25 22:04:56 +00001267 // importing), see which MD from the source has an associated
1268 // temporary metadata node, which means that any DISubprogram
1269 // reached from that MD was needed by an imported function.
1270 SmallPtrSet<const MDNode *, 16> Visited;
Teresa Johnson61b406e2015-12-29 23:00:22 +00001271 for (auto MDI : MetadataToIDs) {
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001272 const MDNode *Node = dyn_cast<MDNode>(MDI.first);
1273 if (!Node)
1274 continue;
Teresa Johnson71d12d22016-01-25 22:04:56 +00001275 if (!ValIDToTempMDMap->count(MDI.second))
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001276 continue;
Teresa Johnson71d12d22016-01-25 22:04:56 +00001277 // Find any SP needed recursively from this needed Node.
1278 findReachedSubprograms(Node, Visited);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001279 }
1280}
1281
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001282// Squash null subprograms from the given compile unit's subprogram list.
1283void IRLinker::stripNullSubprograms(DICompileUnit *CU) {
1284 // There won't be any nulls if we didn't have any subprograms marked
1285 // as unneeded.
1286 if (UnneededSubprograms.empty())
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001287 return;
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001288 SmallVector<Metadata *, 16> NewSPs;
1289 NewSPs.reserve(CU->getSubprograms().size());
1290 bool FoundNull = false;
1291 for (DISubprogram *SP : CU->getSubprograms()) {
1292 if (!SP) {
1293 FoundNull = true;
1294 continue;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001295 }
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001296 NewSPs.push_back(SP);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001297 }
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001298 if (FoundNull)
1299 CU->replaceSubprograms(MDTuple::get(CU->getContext(), NewSPs));
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001300}
1301
Rafael Espindolacaabe222015-12-10 14:19:35 +00001302/// Insert all of the named MDNodes in Src into the Dest module.
1303void IRLinker::linkNamedMDNodes() {
Rafael Espindola394524d2016-01-21 00:00:53 +00001304 findNeededSubprograms();
Rafael Espindola40358fb2016-02-16 18:50:12 +00001305 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1306 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001307 // Don't link module flags here. Do them separately.
1308 if (&NMD == SrcModFlags)
1309 continue;
1310 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1311 // Add Src elements into Dest node.
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001312 for (const MDNode *op : NMD.operands()) {
1313 MDNode *DestMD = MapMetadata(
Teresa Johnsone5a61912015-12-17 17:14:09 +00001314 op, ValueMap, ValueMapperFlags | RF_NullMapMissingGlobalValues,
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001315 &TypeMap, &GValMaterializer);
1316 // For each newly mapped compile unit remove any null subprograms,
1317 // which occur when findNeededSubprograms identified any as unneeded
1318 // in the dest module.
1319 if (auto *CU = dyn_cast<DICompileUnit>(DestMD))
1320 stripNullSubprograms(CU);
1321 DestNMD->addOperand(DestMD);
1322 }
Rafael Espindolacaabe222015-12-10 14:19:35 +00001323 }
1324}
1325
1326/// Merge the linker flags in Src into the Dest module.
1327bool IRLinker::linkModuleFlagsMetadata() {
1328 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001329 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001330 if (!SrcModFlags)
1331 return false;
1332
1333 // If the destination module doesn't have module flags yet, then just copy
1334 // over the source module's flags.
1335 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1336 if (DstModFlags->getNumOperands() == 0) {
1337 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1338 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1339
1340 return false;
1341 }
1342
1343 // First build a map of the existing module flags and requirements.
1344 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1345 SmallSetVector<MDNode *, 16> Requirements;
1346 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1347 MDNode *Op = DstModFlags->getOperand(I);
1348 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1349 MDString *ID = cast<MDString>(Op->getOperand(1));
1350
1351 if (Behavior->getZExtValue() == Module::Require) {
1352 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1353 } else {
1354 Flags[ID] = std::make_pair(Op, I);
1355 }
1356 }
1357
1358 // Merge in the flags from the source module, and also collect its set of
1359 // requirements.
1360 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1361 MDNode *SrcOp = SrcModFlags->getOperand(I);
1362 ConstantInt *SrcBehavior =
1363 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1364 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1365 MDNode *DstOp;
1366 unsigned DstIndex;
1367 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1368 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1369
1370 // If this is a requirement, add it and continue.
1371 if (SrcBehaviorValue == Module::Require) {
1372 // If the destination module does not already have this requirement, add
1373 // it.
1374 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1375 DstModFlags->addOperand(SrcOp);
1376 }
1377 continue;
1378 }
1379
1380 // If there is no existing flag with this ID, just add it.
1381 if (!DstOp) {
1382 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1383 DstModFlags->addOperand(SrcOp);
1384 continue;
1385 }
1386
1387 // Otherwise, perform a merge.
1388 ConstantInt *DstBehavior =
1389 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1390 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1391
1392 // If either flag has override behavior, handle it first.
1393 if (DstBehaviorValue == Module::Override) {
1394 // Diagnose inconsistent flags which both have override behavior.
1395 if (SrcBehaviorValue == Module::Override &&
1396 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1397 emitError("linking module flags '" + ID->getString() +
1398 "': IDs have conflicting override values");
1399 }
1400 continue;
1401 } else if (SrcBehaviorValue == Module::Override) {
1402 // Update the destination flag to that of the source.
1403 DstModFlags->setOperand(DstIndex, SrcOp);
1404 Flags[ID].first = SrcOp;
1405 continue;
1406 }
1407
1408 // Diagnose inconsistent merge behavior types.
1409 if (SrcBehaviorValue != DstBehaviorValue) {
1410 emitError("linking module flags '" + ID->getString() +
1411 "': IDs have conflicting behaviors");
1412 continue;
1413 }
1414
1415 auto replaceDstValue = [&](MDNode *New) {
1416 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1417 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1418 DstModFlags->setOperand(DstIndex, Flag);
1419 Flags[ID].first = Flag;
1420 };
1421
1422 // Perform the merge for standard behavior types.
1423 switch (SrcBehaviorValue) {
1424 case Module::Require:
1425 case Module::Override:
1426 llvm_unreachable("not possible");
1427 case Module::Error: {
1428 // Emit an error if the values differ.
1429 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1430 emitError("linking module flags '" + ID->getString() +
1431 "': IDs have conflicting values");
1432 }
1433 continue;
1434 }
1435 case Module::Warning: {
1436 // Emit a warning if the values differ.
1437 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1438 emitWarning("linking module flags '" + ID->getString() +
1439 "': IDs have conflicting values");
1440 }
1441 continue;
1442 }
1443 case Module::Append: {
1444 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1445 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1446 SmallVector<Metadata *, 8> MDs;
1447 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1448 MDs.append(DstValue->op_begin(), DstValue->op_end());
1449 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1450
1451 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1452 break;
1453 }
1454 case Module::AppendUnique: {
1455 SmallSetVector<Metadata *, 16> Elts;
1456 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1457 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1458 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1459 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1460
1461 replaceDstValue(MDNode::get(DstM.getContext(),
1462 makeArrayRef(Elts.begin(), Elts.end())));
1463 break;
1464 }
1465 }
1466 }
1467
1468 // Check all of the requirements.
1469 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1470 MDNode *Requirement = Requirements[I];
1471 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1472 Metadata *ReqValue = Requirement->getOperand(1);
1473
1474 MDNode *Op = Flags[Flag].first;
1475 if (!Op || Op->getOperand(2) != ReqValue) {
1476 emitError("linking module flags '" + Flag->getString() +
1477 "': does not have the required value");
1478 continue;
1479 }
1480 }
1481
1482 return HasError;
1483}
1484
1485// This function returns true if the triples match.
1486static bool triplesMatch(const Triple &T0, const Triple &T1) {
1487 // If vendor is apple, ignore the version number.
1488 if (T0.getVendor() == Triple::Apple)
1489 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1490 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1491
1492 return T0 == T1;
1493}
1494
1495// This function returns the merged triple.
1496static std::string mergeTriples(const Triple &SrcTriple,
1497 const Triple &DstTriple) {
1498 // If vendor is apple, pick the triple with the larger version number.
1499 if (SrcTriple.getVendor() == Triple::Apple)
1500 if (DstTriple.isOSVersionLT(SrcTriple))
1501 return SrcTriple.str();
1502
1503 return DstTriple.str();
1504}
1505
1506bool IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001507 // Ensure metadata materialized before value mapping.
1508 if (shouldLinkMetadata() && SrcM->getMaterializer())
1509 if (SrcM->getMaterializer()->materializeMetadata())
1510 return true;
1511
Rafael Espindolacaabe222015-12-10 14:19:35 +00001512 // Inherit the target data from the source module if the destination module
1513 // doesn't have one already.
1514 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001515 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001516
Rafael Espindola40358fb2016-02-16 18:50:12 +00001517 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001518 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001519 SrcM->getModuleIdentifier() + "' is '" +
1520 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001521 DstM.getModuleIdentifier() + "' is '" +
1522 DstM.getDataLayoutStr() + "'\n");
1523 }
1524
1525 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001526 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1527 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001528
Rafael Espindola40358fb2016-02-16 18:50:12 +00001529 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001530
Rafael Espindola40358fb2016-02-16 18:50:12 +00001531 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001532 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001533 SrcM->getModuleIdentifier() + "' is '" +
1534 SrcM->getTargetTriple() + "' whereas '" +
1535 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1536 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001537
1538 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1539
1540 // Append the module inline asm string.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001541 if (!SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001542 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001543 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001544 else
1545 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001546 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001547 }
1548
1549 // Loop over all of the linked values to compute type mappings.
1550 computeTypeMapping();
1551
1552 std::reverse(Worklist.begin(), Worklist.end());
1553 while (!Worklist.empty()) {
1554 GlobalValue *GV = Worklist.back();
1555 Worklist.pop_back();
1556
1557 // Already mapped.
1558 if (ValueMap.find(GV) != ValueMap.end() ||
1559 AliasValueMap.find(GV) != AliasValueMap.end())
1560 continue;
1561
1562 assert(!GV->isDeclaration());
Teresa Johnsone5a61912015-12-17 17:14:09 +00001563 MapValue(GV, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001564 if (HasError)
1565 return true;
1566 }
1567
1568 // Note that we are done linking global value bodies. This prevents
1569 // metadata linking from creating new references.
1570 DoneLinkingBodies = true;
1571
1572 // Remap all of the named MDNodes in Src into the DstM module. We do this
1573 // after linking GlobalValues so that MDNodes that reference GlobalValues
1574 // are properly remapped.
Teresa Johnsone5a61912015-12-17 17:14:09 +00001575 if (shouldLinkMetadata()) {
1576 // Even if just linking metadata we should link decls above in case
1577 // any are referenced by metadata. IRLinker::shouldLink ensures that
1578 // we don't actually link anything from source.
Teresa Johnson0556e222016-03-10 18:47:03 +00001579 if (IsMetadataLinkingPostpass)
Rafael Espindola40358fb2016-02-16 18:50:12 +00001580 SrcM->getMaterializer()->saveMetadataList(MetadataToIDs,
1581 /* OnlyTempMD = */ false);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001582
Teresa Johnsone5a61912015-12-17 17:14:09 +00001583 linkNamedMDNodes();
1584
1585 if (IsMetadataLinkingPostpass) {
1586 // Handle anything left in the ValIDToTempMDMap, such as metadata nodes
1587 // not reached by the dbg.cu NamedMD (i.e. only reached from
1588 // instructions).
Teresa Johnson61b406e2015-12-29 23:00:22 +00001589 // Walk the MetadataToIDs once to find the set of new (imported) MD
Teresa Johnsone5a61912015-12-17 17:14:09 +00001590 // that still has corresponding temporary metadata, and invoke metadata
1591 // mapping on each one.
Teresa Johnson61b406e2015-12-29 23:00:22 +00001592 for (auto MDI : MetadataToIDs) {
Teresa Johnsone5a61912015-12-17 17:14:09 +00001593 if (!ValIDToTempMDMap->count(MDI.second))
1594 continue;
1595 MapMetadata(MDI.first, ValueMap, ValueMapperFlags, &TypeMap,
1596 &GValMaterializer);
1597 }
1598 assert(ValIDToTempMDMap->empty());
1599 }
1600
1601 // Merge the module flags into the DstM module.
1602 if (linkModuleFlagsMetadata())
1603 return true;
1604 }
Rafael Espindolacaabe222015-12-10 14:19:35 +00001605
1606 return false;
1607}
1608
1609IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1610 : ETypes(E), IsPacked(P) {}
1611
1612IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1613 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1614
1615bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1616 if (IsPacked != That.IsPacked)
1617 return false;
1618 if (ETypes != That.ETypes)
1619 return false;
1620 return true;
1621}
1622
1623bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1624 return !this->operator==(That);
1625}
1626
1627StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1628 return DenseMapInfo<StructType *>::getEmptyKey();
1629}
1630
1631StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1632 return DenseMapInfo<StructType *>::getTombstoneKey();
1633}
1634
1635unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1636 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1637 Key.IsPacked);
1638}
1639
1640unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1641 return getHashValue(KeyTy(ST));
1642}
1643
1644bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1645 const StructType *RHS) {
1646 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1647 return false;
1648 return LHS == KeyTy(RHS);
1649}
1650
1651bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1652 const StructType *RHS) {
1653 if (RHS == getEmptyKey())
1654 return LHS == getEmptyKey();
1655
1656 if (RHS == getTombstoneKey())
1657 return LHS == getTombstoneKey();
1658
1659 return KeyTy(LHS) == KeyTy(RHS);
1660}
1661
1662void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1663 assert(!Ty->isOpaque());
1664 NonOpaqueStructTypes.insert(Ty);
1665}
1666
1667void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1668 assert(!Ty->isOpaque());
1669 NonOpaqueStructTypes.insert(Ty);
1670 bool Removed = OpaqueStructTypes.erase(Ty);
1671 (void)Removed;
1672 assert(Removed);
1673}
1674
1675void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1676 assert(Ty->isOpaque());
1677 OpaqueStructTypes.insert(Ty);
1678}
1679
1680StructType *
1681IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1682 bool IsPacked) {
1683 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1684 auto I = NonOpaqueStructTypes.find_as(Key);
1685 if (I == NonOpaqueStructTypes.end())
1686 return nullptr;
1687 return *I;
1688}
1689
1690bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1691 if (Ty->isOpaque())
1692 return OpaqueStructTypes.count(Ty);
1693 auto I = NonOpaqueStructTypes.find(Ty);
1694 if (I == NonOpaqueStructTypes.end())
1695 return false;
1696 return *I == Ty;
1697}
1698
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001699IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001700 TypeFinder StructTypes;
1701 StructTypes.run(M, true);
1702 for (StructType *Ty : StructTypes) {
1703 if (Ty->isOpaque())
1704 IdentifiedStructTypes.addOpaque(Ty);
1705 else
1706 IdentifiedStructTypes.addNonOpaque(Ty);
1707 }
1708}
1709
1710bool IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001711 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001712 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
1713 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap,
1714 bool IsMetadataLinkingPostpass) {
Rafael Espindola40358fb2016-02-16 18:50:12 +00001715 IRLinker TheIRLinker(Composite, IdentifiedStructTypes, std::move(Src),
1716 ValuesToLink, AddLazyFor, ValIDToTempMDMap,
1717 IsMetadataLinkingPostpass);
Teresa Johnsonbef54362015-12-18 19:28:59 +00001718 bool RetCode = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001719 Composite.dropTriviallyDeadConstantArrays();
1720 return RetCode;
1721}