blob: f67bacedf1bb10b1a3fbd889c9df0c3ee1e846ae [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 Johnson0e7c82c2015-12-18 17:51:37 +0000354 bool isMetadataNeeded(Metadata *MD) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000355};
356
357class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000358 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000359
360public:
Mehdi Amini33661072016-03-11 22:19:06 +0000361 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Rafael Espindolacaabe222015-12-10 14:19:35 +0000362 Value *materializeDeclFor(Value *V) override;
363 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000364 bool isMetadataNeeded(Metadata *MD) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000365};
366
367/// 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
380 /// Mapping of values from what they used to be in Src, to what they are now
381 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
382 /// due to the use of Value handles which the Linker doesn't actually need,
383 /// but this allows us to reuse the ValueMapper code.
384 ValueToValueMapTy ValueMap;
385 ValueToValueMapTy AliasValueMap;
386
387 DenseSet<GlobalValue *> ValuesToLink;
388 std::vector<GlobalValue *> Worklist;
389
390 void maybeAdd(GlobalValue *GV) {
391 if (ValuesToLink.insert(GV).second)
392 Worklist.push_back(GV);
393 }
394
Rafael Espindolacaabe222015-12-10 14:19:35 +0000395 /// Set to true when all global value body linking is complete (including
396 /// lazy linking). Used to prevent metadata linking from creating new
397 /// references.
398 bool DoneLinkingBodies = false;
399
400 bool HasError = false;
401
Teresa Johnsone5a61912015-12-17 17:14:09 +0000402 /// Flags to pass to value mapper invocations.
403 RemapFlags ValueMapperFlags = RF_MoveDistinctMDs;
404
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000405 /// Set of subprogram metadata that does not need to be linked into the
406 /// destination module, because the functions were not imported directly
407 /// or via an inlined body in an imported function.
408 SmallPtrSet<const Metadata *, 16> UnneededSubprograms;
409
Rafael Espindolacaabe222015-12-10 14:19:35 +0000410 /// Handles cloning of a global values from the source module into
411 /// the destination module, including setting the attributes and visibility.
412 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
413
414 /// Helper method for setting a message and returning an error code.
415 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000416 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000417 HasError = true;
418 return true;
419 }
420
421 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000422 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000423 }
424
425 /// Given a global in the source module, return the global in the
426 /// destination module that is being linked to, if any.
427 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
428 // If the source has no name it can't link. If it has local linkage,
429 // there is no name match-up going on.
430 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
431 return nullptr;
432
433 // Otherwise see if we have a match in the destination module's symtab.
434 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
435 if (!DGV)
436 return nullptr;
437
438 // If we found a global with the same name in the dest module, but it has
439 // internal linkage, we are really not doing any linkage here.
440 if (DGV->hasLocalLinkage())
441 return nullptr;
442
443 // Otherwise, we do in fact link to the destination global.
444 return DGV;
445 }
446
447 void computeTypeMapping();
448
449 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
450 const GlobalVariable *SrcGV);
451
Mehdi Amini33661072016-03-11 22:19:06 +0000452 /// Given the GlobaValue \p SGV in the source module, and the matching
453 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
454 /// into the destination module.
455 ///
456 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000457 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
458 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
459
460 bool linkModuleFlagsMetadata();
461
462 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
463 bool linkFunctionBody(Function &Dst, Function &Src);
464 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
465 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
466
467 /// Functions that take care of cloning a specific global value type
468 /// into the destination module.
469 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
470 Function *copyFunctionProto(const Function *SF);
471 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
472
473 void linkNamedMDNodes();
474
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000475 /// Populate the UnneededSubprograms set with the DISubprogram metadata
476 /// from the source module that we don't need to link into the dest module,
477 /// because the functions were not imported directly or via an inlined body
478 /// in an imported function.
Rafael Espindola394524d2016-01-21 00:00:53 +0000479 void findNeededSubprograms();
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000480
481 /// The value mapper leaves nulls in the list of subprograms for any
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +0000482 /// in the UnneededSubprograms map. Strip those out of the mapped
483 /// compile unit.
484 void stripNullSubprograms(DICompileUnit *CU);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000485
Rafael Espindolacaabe222015-12-10 14:19:35 +0000486public:
Rafael Espindola40358fb2016-02-16 18:50:12 +0000487 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set,
488 std::unique_ptr<Module> SrcM, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000489 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
Rafael Espindola40358fb2016-02-16 18:50:12 +0000490 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set),
Teresa Johnsonb703c772016-03-29 18:24:19 +0000491 GValMaterializer(*this), LValMaterializer(*this) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000492 for (GlobalValue *GV : ValuesToLink)
493 maybeAdd(GV);
Teresa Johnsoncc428572015-12-30 19:32:24 +0000494 }
495
Rafael Espindolacaabe222015-12-10 14:19:35 +0000496 bool run();
497 Value *materializeDeclFor(Value *V, bool ForAlias);
498 void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000499
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000500 /// Indicates whether we need to map the given metadata into the destination
501 /// module. Used to prevent linking of metadata only needed by functions not
502 /// linked into the dest module.
503 bool isMetadataNeeded(Metadata *MD);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000504};
505}
506
507/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
508/// table. This is good for all clients except for us. Go through the trouble
509/// to force this back.
510static void forceRenaming(GlobalValue *GV, StringRef Name) {
511 // If the global doesn't force its name or if it already has the right name,
512 // there is nothing for us to do.
513 if (GV->hasLocalLinkage() || GV->getName() == Name)
514 return;
515
516 Module *M = GV->getParent();
517
518 // If there is a conflict, rename the conflict.
519 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
520 GV->takeName(ConflictGV);
521 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
522 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
523 } else {
524 GV->setName(Name); // Force the name back
525 }
526}
527
528Value *GlobalValueMaterializer::materializeDeclFor(Value *V) {
Mehdi Amini33661072016-03-11 22:19:06 +0000529 return TheIRLinker.materializeDeclFor(V, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000530}
531
532void GlobalValueMaterializer::materializeInitFor(GlobalValue *New,
533 GlobalValue *Old) {
Mehdi Amini33661072016-03-11 22:19:06 +0000534 TheIRLinker.materializeInitFor(New, Old, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000535}
536
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000537bool GlobalValueMaterializer::isMetadataNeeded(Metadata *MD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000538 return TheIRLinker.isMetadataNeeded(MD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000539}
540
Rafael Espindolacaabe222015-12-10 14:19:35 +0000541Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
Mehdi Amini33661072016-03-11 22:19:06 +0000542 return TheIRLinker.materializeDeclFor(V, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000543}
544
545void LocalValueMaterializer::materializeInitFor(GlobalValue *New,
546 GlobalValue *Old) {
Mehdi Amini33661072016-03-11 22:19:06 +0000547 TheIRLinker.materializeInitFor(New, Old, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000548}
549
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000550bool LocalValueMaterializer::isMetadataNeeded(Metadata *MD) {
Mehdi Amini33661072016-03-11 22:19:06 +0000551 return TheIRLinker.isMetadataNeeded(MD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000552}
553
Rafael Espindolacaabe222015-12-10 14:19:35 +0000554Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) {
555 auto *SGV = dyn_cast<GlobalValue>(V);
556 if (!SGV)
557 return nullptr;
558
559 return linkGlobalValueProto(SGV, ForAlias);
560}
561
562void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old,
563 bool ForAlias) {
564 // If we already created the body, just return.
565 if (auto *F = dyn_cast<Function>(New)) {
566 if (!F->isDeclaration())
567 return;
568 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
569 if (V->hasInitializer())
570 return;
571 } else {
572 auto *A = cast<GlobalAlias>(New);
573 if (A->getAliasee())
574 return;
575 }
576
577 if (ForAlias || shouldLink(New, *Old))
578 linkGlobalValueBody(*New, *Old);
579}
580
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000581bool IRLinker::isMetadataNeeded(Metadata *MD) {
582 // Currently only DISubprogram metadata is marked as being unneeded.
583 if (UnneededSubprograms.empty())
584 return true;
585 MDNode *Node = dyn_cast<MDNode>(MD);
586 if (!Node)
587 return true;
588 DISubprogram *SP = getDISubprogram(Node);
589 if (!SP)
590 return true;
591 return !UnneededSubprograms.count(SP);
592}
593
Rafael Espindolacaabe222015-12-10 14:19:35 +0000594/// Loop through the global variables in the src module and merge them into the
595/// dest module.
596GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
597 // No linking to be performed or linking from the source: simply create an
598 // identical version of the symbol over in the dest module... the
599 // initializer will be filled in later by LinkGlobalInits.
600 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000601 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000602 SGVar->isConstant(), GlobalValue::ExternalLinkage,
603 /*init*/ nullptr, SGVar->getName(),
604 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
605 SGVar->getType()->getAddressSpace());
606 NewDGV->setAlignment(SGVar->getAlignment());
607 return NewDGV;
608}
609
610/// Link the function in the source module into the destination module if
611/// needed, setting up mapping information.
612Function *IRLinker::copyFunctionProto(const Function *SF) {
613 // If there is no linkage to be performed or we are linking from the source,
614 // bring SF over.
615 return Function::Create(TypeMap.get(SF->getFunctionType()),
616 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
617}
618
619/// Set up prototypes for any aliases that come over from the source module.
620GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
621 // If there is no linkage to be performed or we're linking from the source,
622 // bring over SGA.
623 auto *Ty = TypeMap.get(SGA->getValueType());
624 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
625 GlobalValue::ExternalLinkage, SGA->getName(),
626 &DstM);
627}
628
629GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
630 bool ForDefinition) {
631 GlobalValue *NewGV;
632 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
633 NewGV = copyGlobalVariableProto(SGVar);
634 } else if (auto *SF = dyn_cast<Function>(SGV)) {
635 NewGV = copyFunctionProto(SF);
636 } else {
637 if (ForDefinition)
638 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
639 else
640 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000641 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000642 /*isConstant*/ false, GlobalValue::ExternalLinkage,
643 /*init*/ nullptr, SGV->getName(),
644 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
645 SGV->getType()->getAddressSpace());
646 }
647
648 if (ForDefinition)
649 NewGV->setLinkage(SGV->getLinkage());
650 else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() ||
651 SGV->hasLinkOnceLinkage())
652 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
653
654 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000655
656 // Remove these copied constants in case this stays a declaration, since
657 // they point to the source module. If the def is linked the values will
658 // be mapped in during linkFunctionBody.
659 if (auto *NewF = dyn_cast<Function>(NewGV)) {
660 NewF->setPersonalityFn(nullptr);
661 NewF->setPrefixData(nullptr);
662 NewF->setPrologueData(nullptr);
663 }
664
Rafael Espindolacaabe222015-12-10 14:19:35 +0000665 return NewGV;
666}
667
668/// Loop over all of the linked values to compute type mappings. For example,
669/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
670/// types 'Foo' but one got renamed when the module was loaded into the same
671/// LLVMContext.
672void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000673 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000674 GlobalValue *DGV = getLinkedToGlobal(&SGV);
675 if (!DGV)
676 continue;
677
678 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
679 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
680 continue;
681 }
682
683 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000684 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
685 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000686 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
687 }
688
Rafael Espindola40358fb2016-02-16 18:50:12 +0000689 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000690 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
691 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
692
Rafael Espindola40358fb2016-02-16 18:50:12 +0000693 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000694 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
695 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
696
697 // Incorporate types by name, scanning all the types in the source module.
698 // At this point, the destination module may have a type "%foo = { i32 }" for
699 // example. When the source module got loaded into the same LLVMContext, if
700 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000701 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000702 for (StructType *ST : Types) {
703 if (!ST->hasName())
704 continue;
705
706 // Check to see if there is a dot in the name followed by a digit.
707 size_t DotPos = ST->getName().rfind('.');
708 if (DotPos == 0 || DotPos == StringRef::npos ||
709 ST->getName().back() == '.' ||
710 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
711 continue;
712
713 // Check to see if the destination module has a struct with the prefix name.
714 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
715 if (!DST)
716 continue;
717
718 // Don't use it if this actually came from the source module. They're in
719 // the same LLVMContext after all. Also don't use it unless the type is
720 // actually used in the destination module. This can happen in situations
721 // like this:
722 //
723 // Module A Module B
724 // -------- --------
725 // %Z = type { %A } %B = type { %C.1 }
726 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
727 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
728 // %C = type { i8* } %B.3 = type { %C.1 }
729 //
730 // When we link Module B with Module A, the '%B' in Module B is
731 // used. However, that would then use '%C.1'. But when we process '%C.1',
732 // we prefer to take the '%C' version. So we are then left with both
733 // '%C.1' and '%C' being used for the same types. This leads to some
734 // variables using one type and some using the other.
735 if (TypeMap.DstStructTypesSet.hasType(DST))
736 TypeMap.addTypeMapping(DST, ST);
737 }
738
739 // Now that we have discovered all of the type equivalences, get a body for
740 // any 'opaque' types in the dest module that are now resolved.
741 TypeMap.linkDefinedTypeBodies();
742}
743
744static void getArrayElements(const Constant *C,
745 SmallVectorImpl<Constant *> &Dest) {
746 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
747
748 for (unsigned i = 0; i != NumElements; ++i)
749 Dest.push_back(C->getAggregateElement(i));
750}
751
752/// If there were any appending global variables, link them together now.
753/// Return true on error.
754Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
755 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000756 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000757 ->getElementType();
758
759 StringRef Name = SrcGV->getName();
760 bool IsNewStructor = false;
761 bool IsOldStructor = false;
762 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
763 if (cast<StructType>(EltTy)->getNumElements() == 3)
764 IsNewStructor = true;
765 else
766 IsOldStructor = true;
767 }
768
769 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
770 if (IsOldStructor) {
771 auto &ST = *cast<StructType>(EltTy);
772 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
773 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
774 }
775
776 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000777 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000778
779 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
780 emitError(
781 "Linking globals named '" + SrcGV->getName() +
782 "': can only link appending global with another appending global!");
783 return nullptr;
784 }
785
786 // Check to see that they two arrays agree on type.
787 if (EltTy != DstTy->getElementType()) {
788 emitError("Appending variables with different element types!");
789 return nullptr;
790 }
791 if (DstGV->isConstant() != SrcGV->isConstant()) {
792 emitError("Appending variables linked with different const'ness!");
793 return nullptr;
794 }
795
796 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
797 emitError(
798 "Appending variables with different alignment need to be linked!");
799 return nullptr;
800 }
801
802 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
803 emitError(
804 "Appending variables with different visibility need to be linked!");
805 return nullptr;
806 }
807
808 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
809 emitError(
810 "Appending variables with different unnamed_addr need to be linked!");
811 return nullptr;
812 }
813
814 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
815 emitError(
816 "Appending variables with different section name need to be linked!");
817 return nullptr;
818 }
819 }
820
821 SmallVector<Constant *, 16> DstElements;
822 if (DstGV)
823 getArrayElements(DstGV->getInitializer(), DstElements);
824
825 SmallVector<Constant *, 16> SrcElements;
826 getArrayElements(SrcGV->getInitializer(), SrcElements);
827
828 if (IsNewStructor)
829 SrcElements.erase(
830 std::remove_if(SrcElements.begin(), SrcElements.end(),
831 [this](Constant *E) {
832 auto *Key = dyn_cast<GlobalValue>(
833 E->getAggregateElement(2)->stripPointerCasts());
834 if (!Key)
835 return false;
836 GlobalValue *DGV = getLinkedToGlobal(Key);
837 return !shouldLink(DGV, *Key);
838 }),
839 SrcElements.end());
840 uint64_t NewSize = DstElements.size() + SrcElements.size();
841 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
842
843 // Create the new global variable.
844 GlobalVariable *NG = new GlobalVariable(
845 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
846 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
847 SrcGV->getType()->getAddressSpace());
848
849 NG->copyAttributesFrom(SrcGV);
850 forceRenaming(NG, SrcGV->getName());
851
852 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
853
854 // Stop recursion.
855 ValueMap[SrcGV] = Ret;
856
857 for (auto *V : SrcElements) {
858 Constant *NewV;
859 if (IsOldStructor) {
860 auto *S = cast<ConstantStruct>(V);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000861 auto *E1 = MapValue(S->getOperand(0), ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +0000862 &TypeMap, &GValMaterializer);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000863 auto *E2 = MapValue(S->getOperand(1), ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +0000864 &TypeMap, &GValMaterializer);
865 Value *Null = Constant::getNullValue(VoidPtrTy);
866 NewV =
867 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
868 } else {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000869 NewV =
870 MapValue(V, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000871 }
872 DstElements.push_back(NewV);
873 }
874
875 NG->setInitializer(ConstantArray::get(NewType, DstElements));
876
877 // Replace any uses of the two global variables with uses of the new
878 // global.
879 if (DstGV) {
880 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
881 DstGV->eraseFromParent();
882 }
883
884 return Ret;
885}
886
Rafael Espindolacaabe222015-12-10 14:19:35 +0000887bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
888 if (ValuesToLink.count(&SGV))
889 return true;
890
891 if (SGV.hasLocalLinkage())
892 return true;
893
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000894 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000895 return false;
896
897 if (SGV.hasAvailableExternallyLinkage())
898 return true;
899
900 if (DoneLinkingBodies)
901 return false;
902
Mehdi Amini33661072016-03-11 22:19:06 +0000903
904 // Callback to the client to give a chance to lazily add the Global to the
905 // list of value to link.
906 bool LazilyAdded = false;
907 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
908 maybeAdd(&GV);
909 LazilyAdded = true;
910 });
911 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000912}
913
914Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
915 GlobalValue *DGV = getLinkedToGlobal(SGV);
916
917 bool ShouldLink = shouldLink(DGV, *SGV);
918
919 // just missing from map
920 if (ShouldLink) {
921 auto I = ValueMap.find(SGV);
922 if (I != ValueMap.end())
923 return cast<Constant>(I->second);
924
925 I = AliasValueMap.find(SGV);
926 if (I != AliasValueMap.end())
927 return cast<Constant>(I->second);
928 }
929
Mehdi Amini33661072016-03-11 22:19:06 +0000930 if (!ShouldLink && ForAlias)
931 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000932
933 // Handle the ultra special appending linkage case first.
934 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
935 if (SGV->hasAppendingLinkage())
936 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
937 cast<GlobalVariable>(SGV));
938
939 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000940 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000941 NewGV = DGV;
942 } else {
943 // If we are done linking global value bodies (i.e. we are performing
944 // metadata linking), don't link in the global value due to this
945 // reference, simply map it to null.
946 if (DoneLinkingBodies)
947 return nullptr;
948
949 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +0000950 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000951 forceRenaming(NewGV, SGV->getName());
952 }
953 if (ShouldLink || ForAlias) {
954 if (const Comdat *SC = SGV->getComdat()) {
955 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
956 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
957 DC->setSelectionKind(SC->getSelectionKind());
958 GO->setComdat(DC);
959 }
960 }
961 }
962
963 if (!ShouldLink && ForAlias)
964 NewGV->setLinkage(GlobalValue::InternalLinkage);
965
966 Constant *C = NewGV;
967 if (DGV)
968 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
969
970 if (DGV && NewGV != DGV) {
971 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
972 DGV->eraseFromParent();
973 }
974
975 return C;
976}
977
978/// Update the initializers in the Dest module now that all globals that may be
979/// referenced are in Dest.
980void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
981 // Figure out what the initializer looks like in the dest module.
Teresa Johnsone5a61912015-12-17 17:14:09 +0000982 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, ValueMapperFlags,
983 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000984}
985
986/// Copy the source function over into the dest function and fix up references
987/// to values. At this point we know that Dest is an external function, and
988/// that Src is not.
989bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
990 assert(Dst.isDeclaration() && !Src.isDeclaration());
991
992 // Materialize if needed.
993 if (std::error_code EC = Src.materialize())
994 return emitError(EC.message());
995
996 // Link in the prefix data.
997 if (Src.hasPrefixData())
Teresa Johnsone5a61912015-12-17 17:14:09 +0000998 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, ValueMapperFlags,
999 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001000
1001 // Link in the prologue data.
1002 if (Src.hasPrologueData())
1003 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001004 ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001005 &GValMaterializer));
1006
1007 // Link in the personality function.
1008 if (Src.hasPersonalityFn())
1009 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001010 ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001011 &GValMaterializer));
1012
1013 // Go through and convert function arguments over, remembering the mapping.
1014 Function::arg_iterator DI = Dst.arg_begin();
1015 for (Argument &Arg : Src.args()) {
1016 DI->setName(Arg.getName()); // Copy the name over.
1017
1018 // Add a mapping to our mapping.
1019 ValueMap[&Arg] = &*DI;
1020 ++DI;
1021 }
1022
1023 // Copy over the metadata attachments.
1024 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1025 Src.getAllMetadata(MDs);
1026 for (const auto &I : MDs)
Teresa Johnsone5a61912015-12-17 17:14:09 +00001027 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001028 &TypeMap, &GValMaterializer));
1029
1030 // Splice the body of the source function into the dest function.
1031 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1032
1033 // At this point, all of the instructions and values of the function are now
1034 // copied over. The only problem is that they are still referencing values in
1035 // the Source function as operands. Loop through all of the operands of the
1036 // functions and patch them up to point to the local versions.
1037 for (BasicBlock &BB : Dst)
1038 for (Instruction &I : BB)
Teresa Johnsone5a61912015-12-17 17:14:09 +00001039 RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries | ValueMapperFlags,
1040 &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001041
1042 // There is no need to map the arguments anymore.
1043 for (Argument &Arg : Src.args())
1044 ValueMap.erase(&Arg);
1045
Rafael Espindolacaabe222015-12-10 14:19:35 +00001046 return false;
1047}
1048
1049void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1050 Constant *Aliasee = Src.getAliasee();
Teresa Johnsone5a61912015-12-17 17:14:09 +00001051 Constant *Val = MapValue(Aliasee, AliasValueMap, ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001052 &LValMaterializer);
1053 Dst.setAliasee(Val);
1054}
1055
1056bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1057 if (auto *F = dyn_cast<Function>(&Src))
1058 return linkFunctionBody(cast<Function>(Dst), *F);
1059 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1060 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1061 return false;
1062 }
1063 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1064 return false;
1065}
1066
Rafael Espindola394524d2016-01-21 00:00:53 +00001067void IRLinker::findNeededSubprograms() {
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001068 // Track unneeded nodes to make it simpler to handle the case
1069 // where we are checking if an already-mapped SP is needed.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001070 NamedMDNode *CompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001071 if (!CompileUnits)
1072 return;
1073 for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
1074 auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
1075 assert(CU && "Expected valid compile unit");
Teresa Johnsonb9515582016-01-07 00:06:27 +00001076 // Ensure that we don't remove subprograms referenced by DIImportedEntity.
Ahmed Bougachaa7324a22016-01-07 03:14:59 +00001077 // It is not legal to have a DIImportedEntity with a null entity or scope.
Teresa Johnsonf07db002016-01-25 21:29:55 +00001078 // Using getDISubprogram handles the case where the subprogram is reached
1079 // via an intervening DILexicalBlock.
Teresa Johnsonb9515582016-01-07 00:06:27 +00001080 // FIXME: The DISubprogram for functions not linked in but kept due to
1081 // being referenced by a DIImportedEntity should also get their
1082 // IsDefinition flag is unset.
1083 SmallPtrSet<DISubprogram *, 8> ImportedEntitySPs;
1084 for (auto *IE : CU->getImportedEntities()) {
Teresa Johnsonf07db002016-01-25 21:29:55 +00001085 if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getEntity())))
Teresa Johnsonb9515582016-01-07 00:06:27 +00001086 ImportedEntitySPs.insert(SP);
Teresa Johnsonf07db002016-01-25 21:29:55 +00001087 if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getScope())))
Ahmed Bougachaa7324a22016-01-07 03:14:59 +00001088 ImportedEntitySPs.insert(SP);
Teresa Johnsonb9515582016-01-07 00:06:27 +00001089 }
Teresa Johnsond213aa42015-12-22 01:17:19 +00001090 for (auto *Op : CU->getSubprograms()) {
Teresa Johnsonb703c772016-03-29 18:24:19 +00001091 // Any needed SPs should have been mapped as they would be reached
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001092 // from the function linked in (either on the function itself for linked
1093 // function bodies, or from DILocation on inlined instructions).
Teresa Johnsonb9515582016-01-07 00:06:27 +00001094 if (!ValueMap.MD()[Op] && !ImportedEntitySPs.count(Op))
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001095 UnneededSubprograms.insert(Op);
1096 }
1097 }
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001098}
1099
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001100// Squash null subprograms from the given compile unit's subprogram list.
1101void IRLinker::stripNullSubprograms(DICompileUnit *CU) {
1102 // There won't be any nulls if we didn't have any subprograms marked
1103 // as unneeded.
1104 if (UnneededSubprograms.empty())
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001105 return;
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001106 SmallVector<Metadata *, 16> NewSPs;
1107 NewSPs.reserve(CU->getSubprograms().size());
1108 bool FoundNull = false;
1109 for (DISubprogram *SP : CU->getSubprograms()) {
1110 if (!SP) {
1111 FoundNull = true;
1112 continue;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001113 }
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001114 NewSPs.push_back(SP);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001115 }
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001116 if (FoundNull)
1117 CU->replaceSubprograms(MDTuple::get(CU->getContext(), NewSPs));
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001118}
1119
Rafael Espindolacaabe222015-12-10 14:19:35 +00001120/// Insert all of the named MDNodes in Src into the Dest module.
1121void IRLinker::linkNamedMDNodes() {
Rafael Espindola394524d2016-01-21 00:00:53 +00001122 findNeededSubprograms();
Rafael Espindola40358fb2016-02-16 18:50:12 +00001123 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1124 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001125 // Don't link module flags here. Do them separately.
1126 if (&NMD == SrcModFlags)
1127 continue;
1128 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1129 // Add Src elements into Dest node.
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001130 for (const MDNode *op : NMD.operands()) {
1131 MDNode *DestMD = MapMetadata(
Teresa Johnsone5a61912015-12-17 17:14:09 +00001132 op, ValueMap, ValueMapperFlags | RF_NullMapMissingGlobalValues,
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001133 &TypeMap, &GValMaterializer);
1134 // For each newly mapped compile unit remove any null subprograms,
1135 // which occur when findNeededSubprograms identified any as unneeded
1136 // in the dest module.
1137 if (auto *CU = dyn_cast<DICompileUnit>(DestMD))
1138 stripNullSubprograms(CU);
1139 DestNMD->addOperand(DestMD);
1140 }
Rafael Espindolacaabe222015-12-10 14:19:35 +00001141 }
1142}
1143
1144/// Merge the linker flags in Src into the Dest module.
1145bool IRLinker::linkModuleFlagsMetadata() {
1146 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001147 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001148 if (!SrcModFlags)
1149 return false;
1150
1151 // If the destination module doesn't have module flags yet, then just copy
1152 // over the source module's flags.
1153 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1154 if (DstModFlags->getNumOperands() == 0) {
1155 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1156 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1157
1158 return false;
1159 }
1160
1161 // First build a map of the existing module flags and requirements.
1162 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1163 SmallSetVector<MDNode *, 16> Requirements;
1164 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1165 MDNode *Op = DstModFlags->getOperand(I);
1166 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1167 MDString *ID = cast<MDString>(Op->getOperand(1));
1168
1169 if (Behavior->getZExtValue() == Module::Require) {
1170 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1171 } else {
1172 Flags[ID] = std::make_pair(Op, I);
1173 }
1174 }
1175
1176 // Merge in the flags from the source module, and also collect its set of
1177 // requirements.
1178 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1179 MDNode *SrcOp = SrcModFlags->getOperand(I);
1180 ConstantInt *SrcBehavior =
1181 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1182 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1183 MDNode *DstOp;
1184 unsigned DstIndex;
1185 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1186 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1187
1188 // If this is a requirement, add it and continue.
1189 if (SrcBehaviorValue == Module::Require) {
1190 // If the destination module does not already have this requirement, add
1191 // it.
1192 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1193 DstModFlags->addOperand(SrcOp);
1194 }
1195 continue;
1196 }
1197
1198 // If there is no existing flag with this ID, just add it.
1199 if (!DstOp) {
1200 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1201 DstModFlags->addOperand(SrcOp);
1202 continue;
1203 }
1204
1205 // Otherwise, perform a merge.
1206 ConstantInt *DstBehavior =
1207 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1208 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1209
1210 // If either flag has override behavior, handle it first.
1211 if (DstBehaviorValue == Module::Override) {
1212 // Diagnose inconsistent flags which both have override behavior.
1213 if (SrcBehaviorValue == Module::Override &&
1214 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1215 emitError("linking module flags '" + ID->getString() +
1216 "': IDs have conflicting override values");
1217 }
1218 continue;
1219 } else if (SrcBehaviorValue == Module::Override) {
1220 // Update the destination flag to that of the source.
1221 DstModFlags->setOperand(DstIndex, SrcOp);
1222 Flags[ID].first = SrcOp;
1223 continue;
1224 }
1225
1226 // Diagnose inconsistent merge behavior types.
1227 if (SrcBehaviorValue != DstBehaviorValue) {
1228 emitError("linking module flags '" + ID->getString() +
1229 "': IDs have conflicting behaviors");
1230 continue;
1231 }
1232
1233 auto replaceDstValue = [&](MDNode *New) {
1234 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1235 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1236 DstModFlags->setOperand(DstIndex, Flag);
1237 Flags[ID].first = Flag;
1238 };
1239
1240 // Perform the merge for standard behavior types.
1241 switch (SrcBehaviorValue) {
1242 case Module::Require:
1243 case Module::Override:
1244 llvm_unreachable("not possible");
1245 case Module::Error: {
1246 // Emit an error if the values differ.
1247 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1248 emitError("linking module flags '" + ID->getString() +
1249 "': IDs have conflicting values");
1250 }
1251 continue;
1252 }
1253 case Module::Warning: {
1254 // Emit a warning if the values differ.
1255 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1256 emitWarning("linking module flags '" + ID->getString() +
1257 "': IDs have conflicting values");
1258 }
1259 continue;
1260 }
1261 case Module::Append: {
1262 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1263 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1264 SmallVector<Metadata *, 8> MDs;
1265 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1266 MDs.append(DstValue->op_begin(), DstValue->op_end());
1267 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1268
1269 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1270 break;
1271 }
1272 case Module::AppendUnique: {
1273 SmallSetVector<Metadata *, 16> Elts;
1274 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1275 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1276 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1277 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1278
1279 replaceDstValue(MDNode::get(DstM.getContext(),
1280 makeArrayRef(Elts.begin(), Elts.end())));
1281 break;
1282 }
1283 }
1284 }
1285
1286 // Check all of the requirements.
1287 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1288 MDNode *Requirement = Requirements[I];
1289 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1290 Metadata *ReqValue = Requirement->getOperand(1);
1291
1292 MDNode *Op = Flags[Flag].first;
1293 if (!Op || Op->getOperand(2) != ReqValue) {
1294 emitError("linking module flags '" + Flag->getString() +
1295 "': does not have the required value");
1296 continue;
1297 }
1298 }
1299
1300 return HasError;
1301}
1302
1303// This function returns true if the triples match.
1304static bool triplesMatch(const Triple &T0, const Triple &T1) {
1305 // If vendor is apple, ignore the version number.
1306 if (T0.getVendor() == Triple::Apple)
1307 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1308 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1309
1310 return T0 == T1;
1311}
1312
1313// This function returns the merged triple.
1314static std::string mergeTriples(const Triple &SrcTriple,
1315 const Triple &DstTriple) {
1316 // If vendor is apple, pick the triple with the larger version number.
1317 if (SrcTriple.getVendor() == Triple::Apple)
1318 if (DstTriple.isOSVersionLT(SrcTriple))
1319 return SrcTriple.str();
1320
1321 return DstTriple.str();
1322}
1323
1324bool IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001325 // Ensure metadata materialized before value mapping.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001326 if (SrcM->getMaterializer() && SrcM->getMaterializer()->materializeMetadata())
Teresa Johnson0556e222016-03-10 18:47:03 +00001327 return true;
1328
Rafael Espindolacaabe222015-12-10 14:19:35 +00001329 // Inherit the target data from the source module if the destination module
1330 // doesn't have one already.
1331 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001332 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001333
Rafael Espindola40358fb2016-02-16 18:50:12 +00001334 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001335 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001336 SrcM->getModuleIdentifier() + "' is '" +
1337 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001338 DstM.getModuleIdentifier() + "' is '" +
1339 DstM.getDataLayoutStr() + "'\n");
1340 }
1341
1342 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001343 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1344 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001345
Rafael Espindola40358fb2016-02-16 18:50:12 +00001346 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001347
Rafael Espindola40358fb2016-02-16 18:50:12 +00001348 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001349 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001350 SrcM->getModuleIdentifier() + "' is '" +
1351 SrcM->getTargetTriple() + "' whereas '" +
1352 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1353 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001354
1355 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1356
1357 // Append the module inline asm string.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001358 if (!SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001359 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001360 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001361 else
1362 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001363 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001364 }
1365
1366 // Loop over all of the linked values to compute type mappings.
1367 computeTypeMapping();
1368
1369 std::reverse(Worklist.begin(), Worklist.end());
1370 while (!Worklist.empty()) {
1371 GlobalValue *GV = Worklist.back();
1372 Worklist.pop_back();
1373
1374 // Already mapped.
1375 if (ValueMap.find(GV) != ValueMap.end() ||
1376 AliasValueMap.find(GV) != AliasValueMap.end())
1377 continue;
1378
1379 assert(!GV->isDeclaration());
Teresa Johnsone5a61912015-12-17 17:14:09 +00001380 MapValue(GV, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001381 if (HasError)
1382 return true;
1383 }
1384
1385 // Note that we are done linking global value bodies. This prevents
1386 // metadata linking from creating new references.
1387 DoneLinkingBodies = true;
1388
1389 // Remap all of the named MDNodes in Src into the DstM module. We do this
1390 // after linking GlobalValues so that MDNodes that reference GlobalValues
1391 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001392 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001393
Teresa Johnsonb703c772016-03-29 18:24:19 +00001394 // Merge the module flags into the DstM module.
1395 if (linkModuleFlagsMetadata())
1396 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001397
1398 return false;
1399}
1400
1401IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1402 : ETypes(E), IsPacked(P) {}
1403
1404IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1405 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1406
1407bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1408 if (IsPacked != That.IsPacked)
1409 return false;
1410 if (ETypes != That.ETypes)
1411 return false;
1412 return true;
1413}
1414
1415bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1416 return !this->operator==(That);
1417}
1418
1419StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1420 return DenseMapInfo<StructType *>::getEmptyKey();
1421}
1422
1423StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1424 return DenseMapInfo<StructType *>::getTombstoneKey();
1425}
1426
1427unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1428 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1429 Key.IsPacked);
1430}
1431
1432unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1433 return getHashValue(KeyTy(ST));
1434}
1435
1436bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1437 const StructType *RHS) {
1438 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1439 return false;
1440 return LHS == KeyTy(RHS);
1441}
1442
1443bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1444 const StructType *RHS) {
1445 if (RHS == getEmptyKey())
1446 return LHS == getEmptyKey();
1447
1448 if (RHS == getTombstoneKey())
1449 return LHS == getTombstoneKey();
1450
1451 return KeyTy(LHS) == KeyTy(RHS);
1452}
1453
1454void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1455 assert(!Ty->isOpaque());
1456 NonOpaqueStructTypes.insert(Ty);
1457}
1458
1459void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1460 assert(!Ty->isOpaque());
1461 NonOpaqueStructTypes.insert(Ty);
1462 bool Removed = OpaqueStructTypes.erase(Ty);
1463 (void)Removed;
1464 assert(Removed);
1465}
1466
1467void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1468 assert(Ty->isOpaque());
1469 OpaqueStructTypes.insert(Ty);
1470}
1471
1472StructType *
1473IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1474 bool IsPacked) {
1475 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1476 auto I = NonOpaqueStructTypes.find_as(Key);
1477 if (I == NonOpaqueStructTypes.end())
1478 return nullptr;
1479 return *I;
1480}
1481
1482bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1483 if (Ty->isOpaque())
1484 return OpaqueStructTypes.count(Ty);
1485 auto I = NonOpaqueStructTypes.find(Ty);
1486 if (I == NonOpaqueStructTypes.end())
1487 return false;
1488 return *I == Ty;
1489}
1490
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001491IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001492 TypeFinder StructTypes;
1493 StructTypes.run(M, true);
1494 for (StructType *Ty : StructTypes) {
1495 if (Ty->isOpaque())
1496 IdentifiedStructTypes.addOpaque(Ty);
1497 else
1498 IdentifiedStructTypes.addNonOpaque(Ty);
1499 }
1500}
1501
1502bool IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001503 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +00001504 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
Rafael Espindola40358fb2016-02-16 18:50:12 +00001505 IRLinker TheIRLinker(Composite, IdentifiedStructTypes, std::move(Src),
Teresa Johnsonb703c772016-03-29 18:24:19 +00001506 ValuesToLink, AddLazyFor);
Teresa Johnsonbef54362015-12-18 19:28:59 +00001507 bool RetCode = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001508 Composite.dropTriviallyDeadConstantArrays();
1509 return RetCode;
1510}