blob: ca91b1e831626ed4f5e57bf96921378875e3d2c8 [file] [log] [blame]
Rafael Espindolacaabe222015-12-10 14:19:35 +00001//===- lib/Linker/IRMover.cpp ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Linker/IRMover.h"
11#include "LinkDiagnosticInfo.h"
12#include "llvm/ADT/SetVector.h"
13#include "llvm/ADT/SmallString.h"
14#include "llvm/ADT/Triple.h"
15#include "llvm/IR/Constants.h"
Teresa Johnson0e7c82c2015-12-18 17:51:37 +000016#include "llvm/IR/DebugInfo.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000017#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnsone5a61912015-12-17 17:14:09 +000018#include "llvm/IR/GVMaterializer.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000019#include "llvm/IR/Intrinsics.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000020#include "llvm/IR/TypeFinder.h"
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +000021#include "llvm/Support/Error.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000022#include "llvm/Transforms/Utils/Cloning.h"
Benjamin Kramer82de7d32016-05-27 14:27:24 +000023#include <utility>
Rafael Espindolacaabe222015-12-10 14:19:35 +000024using namespace llvm;
25
26//===----------------------------------------------------------------------===//
27// TypeMap implementation.
28//===----------------------------------------------------------------------===//
29
30namespace {
31class TypeMapTy : public ValueMapTypeRemapper {
32 /// This is a mapping from a source type to a destination type to use.
33 DenseMap<Type *, Type *> MappedTypes;
34
35 /// When checking to see if two subgraphs are isomorphic, we speculatively
36 /// add types to MappedTypes, but keep track of them here in case we need to
37 /// roll back.
38 SmallVector<Type *, 16> SpeculativeTypes;
39
40 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
41
42 /// This is a list of non-opaque structs in the source module that are mapped
43 /// to an opaque struct in the destination module.
44 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
45
46 /// This is the set of opaque types in the destination modules who are
47 /// getting a body from the source module.
48 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
49
50public:
51 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
52 : DstStructTypesSet(DstStructTypesSet) {}
53
54 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
55 /// Indicate that the specified type in the destination module is conceptually
56 /// equivalent to the specified type in the source module.
57 void addTypeMapping(Type *DstTy, Type *SrcTy);
58
59 /// Produce a body for an opaque type in the dest module from a type
60 /// definition in the source module.
61 void linkDefinedTypeBodies();
62
63 /// Return the mapped type to use for the specified input type from the
64 /// source module.
65 Type *get(Type *SrcTy);
66 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
67
68 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
69
70 FunctionType *get(FunctionType *T) {
71 return cast<FunctionType>(get((Type *)T));
72 }
73
74private:
75 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
76
77 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
78};
79}
80
81void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
82 assert(SpeculativeTypes.empty());
83 assert(SpeculativeDstOpaqueTypes.empty());
84
85 // Check to see if these types are recursively isomorphic and establish a
86 // mapping between them if so.
87 if (!areTypesIsomorphic(DstTy, SrcTy)) {
88 // Oops, they aren't isomorphic. Just discard this request by rolling out
89 // any speculative mappings we've established.
90 for (Type *Ty : SpeculativeTypes)
91 MappedTypes.erase(Ty);
92
93 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
94 SpeculativeDstOpaqueTypes.size());
95 for (StructType *Ty : SpeculativeDstOpaqueTypes)
96 DstResolvedOpaqueTypes.erase(Ty);
97 } else {
98 for (Type *Ty : SpeculativeTypes)
99 if (auto *STy = dyn_cast<StructType>(Ty))
100 if (STy->hasName())
101 STy->setName("");
102 }
103 SpeculativeTypes.clear();
104 SpeculativeDstOpaqueTypes.clear();
105}
106
107/// Recursively walk this pair of types, returning true if they are isomorphic,
108/// false if they are not.
109bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
110 // Two types with differing kinds are clearly not isomorphic.
111 if (DstTy->getTypeID() != SrcTy->getTypeID())
112 return false;
113
114 // If we have an entry in the MappedTypes table, then we have our answer.
115 Type *&Entry = MappedTypes[SrcTy];
116 if (Entry)
117 return Entry == DstTy;
118
119 // Two identical types are clearly isomorphic. Remember this
120 // non-speculatively.
121 if (DstTy == SrcTy) {
122 Entry = DstTy;
123 return true;
124 }
125
126 // Okay, we have two types with identical kinds that we haven't seen before.
127
128 // If this is an opaque struct type, special case it.
129 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
130 // Mapping an opaque type to any struct, just keep the dest struct.
131 if (SSTy->isOpaque()) {
132 Entry = DstTy;
133 SpeculativeTypes.push_back(SrcTy);
134 return true;
135 }
136
137 // Mapping a non-opaque source type to an opaque dest. If this is the first
138 // type that we're mapping onto this destination type then we succeed. Keep
139 // the dest, but fill it in later. If this is the second (different) type
140 // that we're trying to map onto the same opaque type then we fail.
141 if (cast<StructType>(DstTy)->isOpaque()) {
142 // We can only map one source type onto the opaque destination type.
143 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
144 return false;
145 SrcDefinitionsToResolve.push_back(SSTy);
146 SpeculativeTypes.push_back(SrcTy);
147 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
148 Entry = DstTy;
149 return true;
150 }
151 }
152
153 // If the number of subtypes disagree between the two types, then we fail.
154 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
155 return false;
156
157 // Fail if any of the extra properties (e.g. array size) of the type disagree.
158 if (isa<IntegerType>(DstTy))
159 return false; // bitwidth disagrees.
160 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
161 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
162 return false;
163
164 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
165 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
166 return false;
167 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
168 StructType *SSTy = cast<StructType>(SrcTy);
169 if (DSTy->isLiteral() != SSTy->isLiteral() ||
170 DSTy->isPacked() != SSTy->isPacked())
171 return false;
172 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
173 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
174 return false;
175 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
176 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
177 return false;
178 }
179
180 // Otherwise, we speculate that these two types will line up and recursively
181 // check the subelements.
182 Entry = DstTy;
183 SpeculativeTypes.push_back(SrcTy);
184
185 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
186 if (!areTypesIsomorphic(DstTy->getContainedType(I),
187 SrcTy->getContainedType(I)))
188 return false;
189
190 // If everything seems to have lined up, then everything is great.
191 return true;
192}
193
194void TypeMapTy::linkDefinedTypeBodies() {
195 SmallVector<Type *, 16> Elements;
196 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
197 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
198 assert(DstSTy->isOpaque());
199
200 // Map the body of the source type over to a new body for the dest type.
201 Elements.resize(SrcSTy->getNumElements());
202 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
203 Elements[I] = get(SrcSTy->getElementType(I));
204
205 DstSTy->setBody(Elements, SrcSTy->isPacked());
206 DstStructTypesSet.switchToNonOpaque(DstSTy);
207 }
208 SrcDefinitionsToResolve.clear();
209 DstResolvedOpaqueTypes.clear();
210}
211
212void TypeMapTy::finishType(StructType *DTy, StructType *STy,
213 ArrayRef<Type *> ETypes) {
214 DTy->setBody(ETypes, STy->isPacked());
215
216 // Steal STy's name.
217 if (STy->hasName()) {
218 SmallString<16> TmpName = STy->getName();
219 STy->setName("");
220 DTy->setName(TmpName);
221 }
222
223 DstStructTypesSet.addNonOpaque(DTy);
224}
225
226Type *TypeMapTy::get(Type *Ty) {
227 SmallPtrSet<StructType *, 8> Visited;
228 return get(Ty, Visited);
229}
230
231Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
232 // If we already have an entry for this type, return it.
233 Type **Entry = &MappedTypes[Ty];
234 if (*Entry)
235 return *Entry;
236
237 // These are types that LLVM itself will unique.
238 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
239
240#ifndef NDEBUG
241 if (!IsUniqued) {
242 for (auto &Pair : MappedTypes) {
243 assert(!(Pair.first != Ty && Pair.second == Ty) &&
244 "mapping to a source type");
245 }
246 }
247#endif
248
249 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
250 StructType *DTy = StructType::create(Ty->getContext());
251 return *Entry = DTy;
252 }
253
254 // If this is not a recursive type, then just map all of the elements and
255 // then rebuild the type from inside out.
256 SmallVector<Type *, 4> ElementTypes;
257
258 // If there are no element types to map, then the type is itself. This is
259 // true for the anonymous {} struct, things like 'float', integers, etc.
260 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
261 return *Entry = Ty;
262
263 // Remap all of the elements, keeping track of whether any of them change.
264 bool AnyChange = false;
265 ElementTypes.resize(Ty->getNumContainedTypes());
266 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
267 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
268 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
269 }
270
271 // If we found our type while recursively processing stuff, just use it.
272 Entry = &MappedTypes[Ty];
273 if (*Entry) {
274 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
275 if (DTy->isOpaque()) {
276 auto *STy = cast<StructType>(Ty);
277 finishType(DTy, STy, ElementTypes);
278 }
279 }
280 return *Entry;
281 }
282
283 // If all of the element types mapped directly over and the type is not
Hans Wennborg2d55d672016-10-19 20:10:03 +0000284 // a named struct, then the type is usable as-is.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000285 if (!AnyChange && IsUniqued)
286 return *Entry = Ty;
287
288 // Otherwise, rebuild a modified type.
289 switch (Ty->getTypeID()) {
290 default:
291 llvm_unreachable("unknown derived type to remap");
292 case Type::ArrayTyID:
293 return *Entry = ArrayType::get(ElementTypes[0],
294 cast<ArrayType>(Ty)->getNumElements());
295 case Type::VectorTyID:
296 return *Entry = VectorType::get(ElementTypes[0],
297 cast<VectorType>(Ty)->getNumElements());
298 case Type::PointerTyID:
299 return *Entry = PointerType::get(ElementTypes[0],
300 cast<PointerType>(Ty)->getAddressSpace());
301 case Type::FunctionTyID:
302 return *Entry = FunctionType::get(ElementTypes[0],
303 makeArrayRef(ElementTypes).slice(1),
304 cast<FunctionType>(Ty)->isVarArg());
305 case Type::StructTyID: {
306 auto *STy = cast<StructType>(Ty);
307 bool IsPacked = STy->isPacked();
308 if (IsUniqued)
309 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
310
311 // If the type is opaque, we can just use it directly.
312 if (STy->isOpaque()) {
313 DstStructTypesSet.addOpaque(STy);
314 return *Entry = Ty;
315 }
316
317 if (StructType *OldT =
318 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
319 STy->setName("");
320 return *Entry = OldT;
321 }
322
323 if (!AnyChange) {
324 DstStructTypesSet.addNonOpaque(STy);
325 return *Entry = Ty;
326 }
327
328 StructType *DTy = StructType::create(Ty->getContext());
329 finishType(DTy, STy, ElementTypes);
330 return *Entry = DTy;
331 }
332 }
333}
334
335LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
336 const Twine &Msg)
337 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
338void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
339
340//===----------------------------------------------------------------------===//
Teresa Johnsonbef54362015-12-18 19:28:59 +0000341// IRLinker implementation.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000342//===----------------------------------------------------------------------===//
343
344namespace {
345class IRLinker;
346
347/// Creates prototypes for functions that are lazily linked on the fly. This
348/// speeds up linking for modules with many/ lazily linked functions of which
349/// few get used.
350class GlobalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000351 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000352
353public:
Mehdi Amini33661072016-03-11 22:19:06 +0000354 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000355 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000356};
357
358class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000359 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000360
361public:
Mehdi Amini33661072016-03-11 22:19:06 +0000362 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000363 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000364};
365
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000366/// Type of the Metadata map in \a ValueToValueMapTy.
367typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
368
Rafael Espindolacaabe222015-12-10 14:19:35 +0000369/// This is responsible for keeping track of the state used for moving data
370/// from SrcM to DstM.
371class IRLinker {
372 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000373 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000374
Mehdi Amini33661072016-03-11 22:19:06 +0000375 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000376 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
377
378 TypeMapTy TypeMap;
379 GlobalValueMaterializer GValMaterializer;
380 LocalValueMaterializer LValMaterializer;
381
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000382 /// A metadata map that's shared between IRLinker instances.
383 MDMapT &SharedMDs;
384
Rafael Espindolacaabe222015-12-10 14:19:35 +0000385 /// Mapping of values from what they used to be in Src, to what they are now
386 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
387 /// due to the use of Value handles which the Linker doesn't actually need,
388 /// but this allows us to reuse the ValueMapper code.
389 ValueToValueMapTy ValueMap;
390 ValueToValueMapTy AliasValueMap;
391
392 DenseSet<GlobalValue *> ValuesToLink;
393 std::vector<GlobalValue *> Worklist;
394
395 void maybeAdd(GlobalValue *GV) {
396 if (ValuesToLink.insert(GV).second)
397 Worklist.push_back(GV);
398 }
399
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000400 /// Flag whether the ModuleInlineAsm string in Src should be linked with
401 /// (concatenated into) the ModuleInlineAsm string for the destination
402 /// module. It should be true for full LTO, but not when importing for
403 /// ThinLTO, otherwise we can have duplicate symbols.
404 bool LinkModuleInlineAsm;
405
Rafael Espindolacaabe222015-12-10 14:19:35 +0000406 /// Set to true when all global value body linking is complete (including
407 /// lazy linking). Used to prevent metadata linking from creating new
408 /// references.
409 bool DoneLinkingBodies = false;
410
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000411 /// The Error encountered during materialization. We use an Optional here to
412 /// avoid needing to manage an unconsumed success value.
413 Optional<Error> FoundError;
414 void setError(Error E) {
415 if (E)
416 FoundError = std::move(E);
417 }
418
419 /// Most of the errors produced by this module are inconvertible StringErrors.
420 /// This convenience function lets us return one of those more easily.
421 Error stringErr(const Twine &T) {
422 return make_error<StringError>(T, inconvertibleErrorCode());
423 }
Rafael Espindolacaabe222015-12-10 14:19:35 +0000424
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000425 /// Entry point for mapping values and alternate context for mapping aliases.
426 ValueMapper Mapper;
427 unsigned AliasMCID;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000428
Rafael Espindolacaabe222015-12-10 14:19:35 +0000429 /// Handles cloning of a global values from the source module into
430 /// the destination module, including setting the attributes and visibility.
431 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
432
Rafael Espindolacaabe222015-12-10 14:19:35 +0000433 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000434 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000435 }
436
437 /// Given a global in the source module, return the global in the
438 /// destination module that is being linked to, if any.
439 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
440 // If the source has no name it can't link. If it has local linkage,
441 // there is no name match-up going on.
442 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
443 return nullptr;
444
445 // Otherwise see if we have a match in the destination module's symtab.
446 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
447 if (!DGV)
448 return nullptr;
449
450 // If we found a global with the same name in the dest module, but it has
451 // internal linkage, we are really not doing any linkage here.
452 if (DGV->hasLocalLinkage())
453 return nullptr;
454
455 // Otherwise, we do in fact link to the destination global.
456 return DGV;
457 }
458
459 void computeTypeMapping();
460
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000461 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
462 const GlobalVariable *SrcGV);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000463
Mehdi Amini33661072016-03-11 22:19:06 +0000464 /// Given the GlobaValue \p SGV in the source module, and the matching
465 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
466 /// into the destination module.
467 ///
468 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000469 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000470 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000471
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000472 Error linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000473
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000474 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000475 Error linkFunctionBody(Function &Dst, Function &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000476 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000477 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000478
479 /// Functions that take care of cloning a specific global value type
480 /// into the destination module.
481 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
482 Function *copyFunctionProto(const Function *SF);
483 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
484
485 void linkNamedMDNodes();
486
487public:
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000488 IRLinker(Module &DstM, MDMapT &SharedMDs,
489 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
490 ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000491 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
492 bool LinkModuleInlineAsm)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000493 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
494 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000495 SharedMDs(SharedMDs), LinkModuleInlineAsm(LinkModuleInlineAsm),
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000496 Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
497 &GValMaterializer),
498 AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
499 &LValMaterializer)) {
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000500 ValueMap.getMDMap() = std::move(SharedMDs);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000501 for (GlobalValue *GV : ValuesToLink)
502 maybeAdd(GV);
Teresa Johnsoncc428572015-12-30 19:32:24 +0000503 }
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000504 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Teresa Johnsoncc428572015-12-30 19:32:24 +0000505
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000506 Error run();
Mehdi Amini53a66722016-05-25 21:01:51 +0000507 Value *materialize(Value *V, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000508};
509}
510
511/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
512/// table. This is good for all clients except for us. Go through the trouble
513/// to force this back.
514static void forceRenaming(GlobalValue *GV, StringRef Name) {
515 // If the global doesn't force its name or if it already has the right name,
516 // there is nothing for us to do.
517 if (GV->hasLocalLinkage() || GV->getName() == Name)
518 return;
519
520 Module *M = GV->getParent();
521
522 // If there is a conflict, rename the conflict.
523 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
524 GV->takeName(ConflictGV);
525 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
526 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
527 } else {
528 GV->setName(Name); // Force the name back
529 }
530}
531
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000532Value *GlobalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000533 return TheIRLinker.materialize(SGV, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000534}
535
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000536Value *LocalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000537 return TheIRLinker.materialize(SGV, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000538}
539
Mehdi Amini53a66722016-05-25 21:01:51 +0000540Value *IRLinker::materialize(Value *V, bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000541 auto *SGV = dyn_cast<GlobalValue>(V);
542 if (!SGV)
543 return nullptr;
544
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000545 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
546 if (!NewProto) {
547 setError(NewProto.takeError());
548 return nullptr;
549 }
550 if (!*NewProto)
551 return nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000552
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000553 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
Mehdi Amini53a66722016-05-25 21:01:51 +0000554 if (!New)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000555 return *NewProto;
Mehdi Amini53a66722016-05-25 21:01:51 +0000556
Rafael Espindolacaabe222015-12-10 14:19:35 +0000557 // If we already created the body, just return.
558 if (auto *F = dyn_cast<Function>(New)) {
559 if (!F->isDeclaration())
Mehdi Amini53a66722016-05-25 21:01:51 +0000560 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000561 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000562 if (V->hasInitializer() || V->hasAppendingLinkage())
Mehdi Amini53a66722016-05-25 21:01:51 +0000563 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000564 } else {
565 auto *A = cast<GlobalAlias>(New);
566 if (A->getAliasee())
Mehdi Amini53a66722016-05-25 21:01:51 +0000567 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000568 }
569
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000570 // When linking a global for an alias, it will always be linked. However we
Adrian Prantl1f9ac962016-11-14 17:26:32 +0000571 // need to check if it was not already scheduled to satisfy a reference from a
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000572 // regular global value initializer. We know if it has been schedule if the
573 // "New" GlobalValue that is mapped here for the alias is the same as the one
574 // already mapped. If there is an entry in the ValueMap but the value is
575 // different, it means that the value already had a definition in the
576 // destination module (linkonce for instance), but we need a new definition
577 // for the alias ("New" will be different.
Mehdi Amini53a66722016-05-25 21:01:51 +0000578 if (ForAlias && ValueMap.lookup(SGV) == New)
579 return New;
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000580
Mehdi Amini53a66722016-05-25 21:01:51 +0000581 if (ForAlias || shouldLink(New, *SGV))
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000582 setError(linkGlobalValueBody(*New, *SGV));
Mehdi Amini53a66722016-05-25 21:01:51 +0000583
584 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000585}
586
587/// Loop through the global variables in the src module and merge them into the
588/// dest module.
589GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
590 // No linking to be performed or linking from the source: simply create an
591 // identical version of the symbol over in the dest module... the
592 // initializer will be filled in later by LinkGlobalInits.
593 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000594 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000595 SGVar->isConstant(), GlobalValue::ExternalLinkage,
596 /*init*/ nullptr, SGVar->getName(),
597 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
598 SGVar->getType()->getAddressSpace());
599 NewDGV->setAlignment(SGVar->getAlignment());
600 return NewDGV;
601}
602
603/// Link the function in the source module into the destination module if
604/// needed, setting up mapping information.
605Function *IRLinker::copyFunctionProto(const Function *SF) {
606 // If there is no linkage to be performed or we are linking from the source,
607 // bring SF over.
608 return Function::Create(TypeMap.get(SF->getFunctionType()),
609 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
610}
611
612/// Set up prototypes for any aliases that come over from the source module.
613GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
614 // If there is no linkage to be performed or we're linking from the source,
615 // bring over SGA.
616 auto *Ty = TypeMap.get(SGA->getValueType());
617 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
618 GlobalValue::ExternalLinkage, SGA->getName(),
619 &DstM);
620}
621
622GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
623 bool ForDefinition) {
624 GlobalValue *NewGV;
625 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
626 NewGV = copyGlobalVariableProto(SGVar);
627 } else if (auto *SF = dyn_cast<Function>(SGV)) {
628 NewGV = copyFunctionProto(SF);
629 } else {
630 if (ForDefinition)
631 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
632 else
633 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000634 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000635 /*isConstant*/ false, GlobalValue::ExternalLinkage,
636 /*init*/ nullptr, SGV->getName(),
637 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
638 SGV->getType()->getAddressSpace());
639 }
640
641 if (ForDefinition)
642 NewGV->setLinkage(SGV->getLinkage());
Mehdi Amini113adde2016-04-19 16:11:05 +0000643 else if (SGV->hasExternalWeakLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000644 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
645
646 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000647
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +0000648 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
649 // Metadata for global variables and function declarations is copied eagerly.
650 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000651 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +0000652 }
653
Teresa Johnson5fe40052016-01-12 00:24:24 +0000654 // Remove these copied constants in case this stays a declaration, since
655 // they point to the source module. If the def is linked the values will
656 // be mapped in during linkFunctionBody.
657 if (auto *NewF = dyn_cast<Function>(NewGV)) {
658 NewF->setPersonalityFn(nullptr);
659 NewF->setPrefixData(nullptr);
660 NewF->setPrologueData(nullptr);
661 }
662
Rafael Espindolacaabe222015-12-10 14:19:35 +0000663 return NewGV;
664}
665
666/// Loop over all of the linked values to compute type mappings. For example,
667/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
668/// types 'Foo' but one got renamed when the module was loaded into the same
669/// LLVMContext.
670void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000671 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000672 GlobalValue *DGV = getLinkedToGlobal(&SGV);
673 if (!DGV)
674 continue;
675
676 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
677 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
678 continue;
679 }
680
681 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000682 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
683 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000684 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
685 }
686
Rafael Espindola40358fb2016-02-16 18:50:12 +0000687 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000688 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
689 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
690
Rafael Espindola40358fb2016-02-16 18:50:12 +0000691 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000692 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
693 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
694
695 // Incorporate types by name, scanning all the types in the source module.
696 // At this point, the destination module may have a type "%foo = { i32 }" for
697 // example. When the source module got loaded into the same LLVMContext, if
698 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000699 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000700 for (StructType *ST : Types) {
701 if (!ST->hasName())
702 continue;
703
Hans Wennborgaeacdc22016-11-18 17:33:05 +0000704 if (TypeMap.DstStructTypesSet.hasType(ST)) {
705 // This is actually a type from the destination module.
706 // getIdentifiedStructTypes() can have found it by walking debug info
707 // metadata nodes, some of which get linked by name when ODR Type Uniquing
708 // is enabled on the Context, from the source to the destination module.
709 continue;
710 }
711
Rafael Espindolacaabe222015-12-10 14:19:35 +0000712 // Check to see if there is a dot in the name followed by a digit.
713 size_t DotPos = ST->getName().rfind('.');
714 if (DotPos == 0 || DotPos == StringRef::npos ||
715 ST->getName().back() == '.' ||
716 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
717 continue;
718
719 // Check to see if the destination module has a struct with the prefix name.
720 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
721 if (!DST)
722 continue;
723
724 // Don't use it if this actually came from the source module. They're in
725 // the same LLVMContext after all. Also don't use it unless the type is
726 // actually used in the destination module. This can happen in situations
727 // like this:
728 //
729 // Module A Module B
730 // -------- --------
731 // %Z = type { %A } %B = type { %C.1 }
732 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
733 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
734 // %C = type { i8* } %B.3 = type { %C.1 }
735 //
736 // When we link Module B with Module A, the '%B' in Module B is
737 // used. However, that would then use '%C.1'. But when we process '%C.1',
738 // we prefer to take the '%C' version. So we are then left with both
739 // '%C.1' and '%C' being used for the same types. This leads to some
740 // variables using one type and some using the other.
741 if (TypeMap.DstStructTypesSet.hasType(DST))
742 TypeMap.addTypeMapping(DST, ST);
743 }
744
745 // Now that we have discovered all of the type equivalences, get a body for
746 // any 'opaque' types in the dest module that are now resolved.
747 TypeMap.linkDefinedTypeBodies();
748}
749
750static void getArrayElements(const Constant *C,
751 SmallVectorImpl<Constant *> &Dest) {
752 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
753
754 for (unsigned i = 0; i != NumElements; ++i)
755 Dest.push_back(C->getAggregateElement(i));
756}
757
758/// If there were any appending global variables, link them together now.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000759Expected<Constant *>
760IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
761 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000762 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000763 ->getElementType();
764
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000765 // FIXME: This upgrade is done during linking to support the C API. Once the
766 // old form is deprecated, we should move this upgrade to
767 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
768 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000769 StringRef Name = SrcGV->getName();
770 bool IsNewStructor = false;
771 bool IsOldStructor = false;
772 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
773 if (cast<StructType>(EltTy)->getNumElements() == 3)
774 IsNewStructor = true;
775 else
776 IsOldStructor = true;
777 }
778
779 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
780 if (IsOldStructor) {
781 auto &ST = *cast<StructType>(EltTy);
782 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
783 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
784 }
785
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000786 uint64_t DstNumElements = 0;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000787 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000788 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000789 DstNumElements = DstTy->getNumElements();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000790
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000791 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
792 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000793 "Linking globals named '" + SrcGV->getName() +
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000794 "': can only link appending global with another appending "
795 "global!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000796
797 // Check to see that they two arrays agree on type.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000798 if (EltTy != DstTy->getElementType())
799 return stringErr("Appending variables with different element types!");
800 if (DstGV->isConstant() != SrcGV->isConstant())
801 return stringErr("Appending variables linked with different const'ness!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000802
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000803 if (DstGV->getAlignment() != SrcGV->getAlignment())
804 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000805 "Appending variables with different alignment need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000806
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000807 if (DstGV->getVisibility() != SrcGV->getVisibility())
808 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000809 "Appending variables with different visibility need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000810
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000811 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000812 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000813 "Appending variables with different unnamed_addr need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000814
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000815 if (DstGV->getSection() != SrcGV->getSection())
816 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000817 "Appending variables with different section name need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000818 }
819
Rafael Espindolacaabe222015-12-10 14:19:35 +0000820 SmallVector<Constant *, 16> SrcElements;
821 getArrayElements(SrcGV->getInitializer(), SrcElements);
822
Justin Bogner375f71e2016-08-15 22:41:42 +0000823 if (IsNewStructor) {
824 auto It = remove_if(SrcElements, [this](Constant *E) {
825 auto *Key =
826 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
827 if (!Key)
828 return false;
829 GlobalValue *DGV = getLinkedToGlobal(Key);
830 return !shouldLink(DGV, *Key);
831 });
832 SrcElements.erase(It, SrcElements.end());
833 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000834 uint64_t NewSize = DstNumElements + SrcElements.size();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000835 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
836
837 // Create the new global variable.
838 GlobalVariable *NG = new GlobalVariable(
839 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
840 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
841 SrcGV->getType()->getAddressSpace());
842
843 NG->copyAttributesFrom(SrcGV);
844 forceRenaming(NG, SrcGV->getName());
845
846 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
847
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000848 Mapper.scheduleMapAppendingVariable(*NG,
849 DstGV ? DstGV->getInitializer() : nullptr,
850 IsOldStructor, SrcElements);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000851
852 // Replace any uses of the two global variables with uses of the new
853 // global.
854 if (DstGV) {
855 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
856 DstGV->eraseFromParent();
857 }
858
859 return Ret;
860}
861
Rafael Espindolacaabe222015-12-10 14:19:35 +0000862bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
Davide Italiano95339652016-06-07 14:55:04 +0000863 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000864 return true;
865
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000866 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000867 return false;
868
869 if (SGV.hasAvailableExternallyLinkage())
870 return true;
871
Davide Italiano95339652016-06-07 14:55:04 +0000872 if (SGV.isDeclaration() || DoneLinkingBodies)
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000873 return false;
Mehdi Amini33661072016-03-11 22:19:06 +0000874
875 // Callback to the client to give a chance to lazily add the Global to the
876 // list of value to link.
877 bool LazilyAdded = false;
878 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
879 maybeAdd(&GV);
880 LazilyAdded = true;
881 });
882 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000883}
884
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000885Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
886 bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000887 GlobalValue *DGV = getLinkedToGlobal(SGV);
888
889 bool ShouldLink = shouldLink(DGV, *SGV);
890
891 // just missing from map
892 if (ShouldLink) {
893 auto I = ValueMap.find(SGV);
894 if (I != ValueMap.end())
895 return cast<Constant>(I->second);
896
897 I = AliasValueMap.find(SGV);
898 if (I != AliasValueMap.end())
899 return cast<Constant>(I->second);
900 }
901
Mehdi Amini33661072016-03-11 22:19:06 +0000902 if (!ShouldLink && ForAlias)
903 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000904
905 // Handle the ultra special appending linkage case first.
906 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
907 if (SGV->hasAppendingLinkage())
908 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
909 cast<GlobalVariable>(SGV));
910
911 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000912 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000913 NewGV = DGV;
914 } else {
915 // If we are done linking global value bodies (i.e. we are performing
916 // metadata linking), don't link in the global value due to this
917 // reference, simply map it to null.
918 if (DoneLinkingBodies)
919 return nullptr;
920
921 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +0000922 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000923 forceRenaming(NewGV, SGV->getName());
924 }
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000925
926 // Overloaded intrinsics have overloaded types names as part of their
927 // names. If we renamed overloaded types we should rename the intrinsic
928 // as well.
929 if (Function *F = dyn_cast<Function>(NewGV))
930 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F))
931 NewGV = Remangled.getValue();
932
Rafael Espindolacaabe222015-12-10 14:19:35 +0000933 if (ShouldLink || ForAlias) {
934 if (const Comdat *SC = SGV->getComdat()) {
935 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
936 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
937 DC->setSelectionKind(SC->getSelectionKind());
938 GO->setComdat(DC);
939 }
940 }
941 }
942
943 if (!ShouldLink && ForAlias)
944 NewGV->setLinkage(GlobalValue::InternalLinkage);
945
946 Constant *C = NewGV;
947 if (DGV)
948 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
949
950 if (DGV && NewGV != DGV) {
951 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
952 DGV->eraseFromParent();
953 }
954
955 return C;
956}
957
958/// Update the initializers in the Dest module now that all globals that may be
959/// referenced are in Dest.
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000960void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000961 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000962 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000963}
964
965/// Copy the source function over into the dest function and fix up references
966/// to values. At this point we know that Dest is an external function, and
967/// that Src is not.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000968Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000969 assert(Dst.isDeclaration() && !Src.isDeclaration());
970
971 // Materialize if needed.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000972 if (Error Err = Src.materialize())
973 return Err;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000974
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000975 // Link in the operands without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000976 if (Src.hasPrefixData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000977 Dst.setPrefixData(Src.getPrefixData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000978 if (Src.hasPrologueData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000979 Dst.setPrologueData(Src.getPrologueData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000980 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000981 Dst.setPersonalityFn(Src.getPersonalityFn());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000982
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000983 // Copy over the metadata attachments without remapping.
Peter Collingbourne7efd7502016-06-24 21:21:32 +0000984 Dst.copyMetadata(&Src, 0);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000985
Duncan P. N. Exon Smithbdfc9842016-04-06 06:38:15 +0000986 // Steal arguments and splice the body of Src into Dst.
987 Dst.stealArgumentListFrom(Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000988 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
989
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000990 // Everything has been moved over. Remap it.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000991 Mapper.scheduleRemapFunction(Dst);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000992 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000993}
994
995void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000996 Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000997}
998
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000999Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001000 if (auto *F = dyn_cast<Function>(&Src))
1001 return linkFunctionBody(cast<Function>(Dst), *F);
1002 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001003 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001004 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001005 }
1006 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001007 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001008}
1009
1010/// Insert all of the named MDNodes in Src into the Dest module.
1011void IRLinker::linkNamedMDNodes() {
Rafael Espindola40358fb2016-02-16 18:50:12 +00001012 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1013 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001014 // Don't link module flags here. Do them separately.
1015 if (&NMD == SrcModFlags)
1016 continue;
1017 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1018 // Add Src elements into Dest node.
Duncan P. N. Exon Smith8a15dab2016-04-15 23:32:44 +00001019 for (const MDNode *Op : NMD.operands())
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001020 DestNMD->addOperand(Mapper.mapMDNode(*Op));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001021 }
1022}
1023
1024/// Merge the linker flags in Src into the Dest module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001025Error IRLinker::linkModuleFlagsMetadata() {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001026 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001027 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001028 if (!SrcModFlags)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001029 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001030
1031 // If the destination module doesn't have module flags yet, then just copy
1032 // over the source module's flags.
1033 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1034 if (DstModFlags->getNumOperands() == 0) {
1035 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1036 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1037
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001038 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001039 }
1040
1041 // First build a map of the existing module flags and requirements.
1042 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1043 SmallSetVector<MDNode *, 16> Requirements;
1044 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1045 MDNode *Op = DstModFlags->getOperand(I);
1046 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1047 MDString *ID = cast<MDString>(Op->getOperand(1));
1048
1049 if (Behavior->getZExtValue() == Module::Require) {
1050 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1051 } else {
1052 Flags[ID] = std::make_pair(Op, I);
1053 }
1054 }
1055
1056 // Merge in the flags from the source module, and also collect its set of
1057 // requirements.
1058 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1059 MDNode *SrcOp = SrcModFlags->getOperand(I);
1060 ConstantInt *SrcBehavior =
1061 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1062 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1063 MDNode *DstOp;
1064 unsigned DstIndex;
1065 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1066 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1067
1068 // If this is a requirement, add it and continue.
1069 if (SrcBehaviorValue == Module::Require) {
1070 // If the destination module does not already have this requirement, add
1071 // it.
1072 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1073 DstModFlags->addOperand(SrcOp);
1074 }
1075 continue;
1076 }
1077
1078 // If there is no existing flag with this ID, just add it.
1079 if (!DstOp) {
1080 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1081 DstModFlags->addOperand(SrcOp);
1082 continue;
1083 }
1084
1085 // Otherwise, perform a merge.
1086 ConstantInt *DstBehavior =
1087 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1088 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1089
1090 // If either flag has override behavior, handle it first.
1091 if (DstBehaviorValue == Module::Override) {
1092 // Diagnose inconsistent flags which both have override behavior.
1093 if (SrcBehaviorValue == Module::Override &&
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001094 SrcOp->getOperand(2) != DstOp->getOperand(2))
1095 return stringErr("linking module flags '" + ID->getString() +
1096 "': IDs have conflicting override values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001097 continue;
1098 } else if (SrcBehaviorValue == Module::Override) {
1099 // Update the destination flag to that of the source.
1100 DstModFlags->setOperand(DstIndex, SrcOp);
1101 Flags[ID].first = SrcOp;
1102 continue;
1103 }
1104
1105 // Diagnose inconsistent merge behavior types.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001106 if (SrcBehaviorValue != DstBehaviorValue)
1107 return stringErr("linking module flags '" + ID->getString() +
1108 "': IDs have conflicting behaviors");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001109
1110 auto replaceDstValue = [&](MDNode *New) {
1111 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1112 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1113 DstModFlags->setOperand(DstIndex, Flag);
1114 Flags[ID].first = Flag;
1115 };
1116
1117 // Perform the merge for standard behavior types.
1118 switch (SrcBehaviorValue) {
1119 case Module::Require:
1120 case Module::Override:
1121 llvm_unreachable("not possible");
1122 case Module::Error: {
1123 // Emit an error if the values differ.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001124 if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1125 return stringErr("linking module flags '" + ID->getString() +
1126 "': IDs have conflicting values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001127 continue;
1128 }
1129 case Module::Warning: {
1130 // Emit a warning if the values differ.
1131 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1132 emitWarning("linking module flags '" + ID->getString() +
1133 "': IDs have conflicting values");
1134 }
1135 continue;
1136 }
1137 case Module::Append: {
1138 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1139 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1140 SmallVector<Metadata *, 8> MDs;
1141 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1142 MDs.append(DstValue->op_begin(), DstValue->op_end());
1143 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1144
1145 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1146 break;
1147 }
1148 case Module::AppendUnique: {
1149 SmallSetVector<Metadata *, 16> Elts;
1150 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1151 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1152 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1153 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1154
1155 replaceDstValue(MDNode::get(DstM.getContext(),
1156 makeArrayRef(Elts.begin(), Elts.end())));
1157 break;
1158 }
1159 }
1160 }
1161
1162 // Check all of the requirements.
1163 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1164 MDNode *Requirement = Requirements[I];
1165 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1166 Metadata *ReqValue = Requirement->getOperand(1);
1167
1168 MDNode *Op = Flags[Flag].first;
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001169 if (!Op || Op->getOperand(2) != ReqValue)
1170 return stringErr("linking module flags '" + Flag->getString() +
1171 "': does not have the required value");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001172 }
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001173 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001174}
1175
1176// This function returns true if the triples match.
1177static bool triplesMatch(const Triple &T0, const Triple &T1) {
1178 // If vendor is apple, ignore the version number.
1179 if (T0.getVendor() == Triple::Apple)
1180 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1181 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1182
1183 return T0 == T1;
1184}
1185
1186// This function returns the merged triple.
1187static std::string mergeTriples(const Triple &SrcTriple,
1188 const Triple &DstTriple) {
1189 // If vendor is apple, pick the triple with the larger version number.
1190 if (SrcTriple.getVendor() == Triple::Apple)
1191 if (DstTriple.isOSVersionLT(SrcTriple))
1192 return SrcTriple.str();
1193
1194 return DstTriple.str();
1195}
1196
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001197Error IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001198 // Ensure metadata materialized before value mapping.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001199 if (SrcM->getMaterializer())
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001200 if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1201 return Err;
Teresa Johnson0556e222016-03-10 18:47:03 +00001202
Rafael Espindolacaabe222015-12-10 14:19:35 +00001203 // Inherit the target data from the source module if the destination module
1204 // doesn't have one already.
1205 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001206 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001207
Rafael Espindola40358fb2016-02-16 18:50:12 +00001208 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001209 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001210 SrcM->getModuleIdentifier() + "' is '" +
1211 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001212 DstM.getModuleIdentifier() + "' is '" +
1213 DstM.getDataLayoutStr() + "'\n");
1214 }
1215
1216 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001217 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1218 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001219
Rafael Espindola40358fb2016-02-16 18:50:12 +00001220 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001221
Rafael Espindola40358fb2016-02-16 18:50:12 +00001222 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001223 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001224 SrcM->getModuleIdentifier() + "' is '" +
1225 SrcM->getTargetTriple() + "' whereas '" +
1226 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1227 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001228
1229 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1230
1231 // Append the module inline asm string.
Teresa Johnson4b9b3792016-10-12 18:39:29 +00001232 if (LinkModuleInlineAsm && !SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001233 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001234 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001235 else
1236 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001237 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001238 }
1239
1240 // Loop over all of the linked values to compute type mappings.
1241 computeTypeMapping();
1242
1243 std::reverse(Worklist.begin(), Worklist.end());
1244 while (!Worklist.empty()) {
1245 GlobalValue *GV = Worklist.back();
1246 Worklist.pop_back();
1247
1248 // Already mapped.
1249 if (ValueMap.find(GV) != ValueMap.end() ||
1250 AliasValueMap.find(GV) != AliasValueMap.end())
1251 continue;
1252
1253 assert(!GV->isDeclaration());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001254 Mapper.mapValue(*GV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001255 if (FoundError)
1256 return std::move(*FoundError);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001257 }
1258
1259 // Note that we are done linking global value bodies. This prevents
1260 // metadata linking from creating new references.
1261 DoneLinkingBodies = true;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001262 Mapper.addFlags(RF_NullMapMissingGlobalValues);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001263
1264 // Remap all of the named MDNodes in Src into the DstM module. We do this
1265 // after linking GlobalValues so that MDNodes that reference GlobalValues
1266 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001267 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001268
Teresa Johnsonb703c772016-03-29 18:24:19 +00001269 // Merge the module flags into the DstM module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001270 return linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001271}
1272
1273IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1274 : ETypes(E), IsPacked(P) {}
1275
1276IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1277 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1278
1279bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
Davide Italiano95339652016-06-07 14:55:04 +00001280 return IsPacked == That.IsPacked && ETypes == That.ETypes;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001281}
1282
1283bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1284 return !this->operator==(That);
1285}
1286
1287StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1288 return DenseMapInfo<StructType *>::getEmptyKey();
1289}
1290
1291StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1292 return DenseMapInfo<StructType *>::getTombstoneKey();
1293}
1294
1295unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1296 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1297 Key.IsPacked);
1298}
1299
1300unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1301 return getHashValue(KeyTy(ST));
1302}
1303
1304bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1305 const StructType *RHS) {
1306 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1307 return false;
1308 return LHS == KeyTy(RHS);
1309}
1310
1311bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1312 const StructType *RHS) {
Davide Italiano95339652016-06-07 14:55:04 +00001313 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1314 return LHS == RHS;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001315 return KeyTy(LHS) == KeyTy(RHS);
1316}
1317
1318void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1319 assert(!Ty->isOpaque());
1320 NonOpaqueStructTypes.insert(Ty);
1321}
1322
1323void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1324 assert(!Ty->isOpaque());
1325 NonOpaqueStructTypes.insert(Ty);
1326 bool Removed = OpaqueStructTypes.erase(Ty);
1327 (void)Removed;
1328 assert(Removed);
1329}
1330
1331void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1332 assert(Ty->isOpaque());
1333 OpaqueStructTypes.insert(Ty);
1334}
1335
1336StructType *
1337IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1338 bool IsPacked) {
1339 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1340 auto I = NonOpaqueStructTypes.find_as(Key);
Davide Italiano95339652016-06-07 14:55:04 +00001341 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001342}
1343
1344bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1345 if (Ty->isOpaque())
1346 return OpaqueStructTypes.count(Ty);
1347 auto I = NonOpaqueStructTypes.find(Ty);
Davide Italiano95339652016-06-07 14:55:04 +00001348 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001349}
1350
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001351IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001352 TypeFinder StructTypes;
Mehdi Aminifec21582016-11-19 18:44:16 +00001353 StructTypes.run(M, /* OnlyNamed */ false);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001354 for (StructType *Ty : StructTypes) {
1355 if (Ty->isOpaque())
1356 IdentifiedStructTypes.addOpaque(Ty);
1357 else
1358 IdentifiedStructTypes.addNonOpaque(Ty);
1359 }
Mehdi Aminiebb34342016-09-03 21:12:33 +00001360 // Self-map metadatas in the destination module. This is needed when
1361 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1362 // destination module may be reached from the source module.
1363 for (auto *MD : StructTypes.getVisitedMetadata()) {
1364 SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1365 }
Rafael Espindolacaabe222015-12-10 14:19:35 +00001366}
1367
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001368Error IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001369 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnson4b9b3792016-10-12 18:39:29 +00001370 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
1371 bool LinkModuleInlineAsm) {
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +00001372 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
Teresa Johnson4b9b3792016-10-12 18:39:29 +00001373 std::move(Src), ValuesToLink, std::move(AddLazyFor),
1374 LinkModuleInlineAsm);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001375 Error E = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001376 Composite.dropTriviallyDeadConstantArrays();
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001377 return E;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001378}