blob: c8cfe203032c7eff15628626c4b95035bb0970ce [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"
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +000020#include "llvm/Support/Error.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000021#include "llvm/Transforms/Utils/Cloning.h"
Benjamin Kramer82de7d32016-05-27 14:27:24 +000022#include <utility>
Rafael Espindolacaabe222015-12-10 14:19:35 +000023using namespace llvm;
24
25//===----------------------------------------------------------------------===//
26// TypeMap implementation.
27//===----------------------------------------------------------------------===//
28
29namespace {
30class TypeMapTy : public ValueMapTypeRemapper {
31 /// This is a mapping from a source type to a destination type to use.
32 DenseMap<Type *, Type *> MappedTypes;
33
34 /// When checking to see if two subgraphs are isomorphic, we speculatively
35 /// add types to MappedTypes, but keep track of them here in case we need to
36 /// roll back.
37 SmallVector<Type *, 16> SpeculativeTypes;
38
39 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
40
41 /// This is a list of non-opaque structs in the source module that are mapped
42 /// to an opaque struct in the destination module.
43 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
44
45 /// This is the set of opaque types in the destination modules who are
46 /// getting a body from the source module.
47 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
48
49public:
50 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
51 : DstStructTypesSet(DstStructTypesSet) {}
52
53 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
54 /// Indicate that the specified type in the destination module is conceptually
55 /// equivalent to the specified type in the source module.
56 void addTypeMapping(Type *DstTy, Type *SrcTy);
57
58 /// Produce a body for an opaque type in the dest module from a type
59 /// definition in the source module.
60 void linkDefinedTypeBodies();
61
62 /// Return the mapped type to use for the specified input type from the
63 /// source module.
64 Type *get(Type *SrcTy);
65 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
66
67 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
68
69 FunctionType *get(FunctionType *T) {
70 return cast<FunctionType>(get((Type *)T));
71 }
72
73private:
74 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
75
76 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
77};
78}
79
80void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
81 assert(SpeculativeTypes.empty());
82 assert(SpeculativeDstOpaqueTypes.empty());
83
84 // Check to see if these types are recursively isomorphic and establish a
85 // mapping between them if so.
86 if (!areTypesIsomorphic(DstTy, SrcTy)) {
87 // Oops, they aren't isomorphic. Just discard this request by rolling out
88 // any speculative mappings we've established.
89 for (Type *Ty : SpeculativeTypes)
90 MappedTypes.erase(Ty);
91
92 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
93 SpeculativeDstOpaqueTypes.size());
94 for (StructType *Ty : SpeculativeDstOpaqueTypes)
95 DstResolvedOpaqueTypes.erase(Ty);
96 } else {
97 for (Type *Ty : SpeculativeTypes)
98 if (auto *STy = dyn_cast<StructType>(Ty))
99 if (STy->hasName())
100 STy->setName("");
101 }
102 SpeculativeTypes.clear();
103 SpeculativeDstOpaqueTypes.clear();
104}
105
106/// Recursively walk this pair of types, returning true if they are isomorphic,
107/// false if they are not.
108bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
109 // Two types with differing kinds are clearly not isomorphic.
110 if (DstTy->getTypeID() != SrcTy->getTypeID())
111 return false;
112
113 // If we have an entry in the MappedTypes table, then we have our answer.
114 Type *&Entry = MappedTypes[SrcTy];
115 if (Entry)
116 return Entry == DstTy;
117
118 // Two identical types are clearly isomorphic. Remember this
119 // non-speculatively.
120 if (DstTy == SrcTy) {
121 Entry = DstTy;
122 return true;
123 }
124
125 // Okay, we have two types with identical kinds that we haven't seen before.
126
127 // If this is an opaque struct type, special case it.
128 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
129 // Mapping an opaque type to any struct, just keep the dest struct.
130 if (SSTy->isOpaque()) {
131 Entry = DstTy;
132 SpeculativeTypes.push_back(SrcTy);
133 return true;
134 }
135
136 // Mapping a non-opaque source type to an opaque dest. If this is the first
137 // type that we're mapping onto this destination type then we succeed. Keep
138 // the dest, but fill it in later. If this is the second (different) type
139 // that we're trying to map onto the same opaque type then we fail.
140 if (cast<StructType>(DstTy)->isOpaque()) {
141 // We can only map one source type onto the opaque destination type.
142 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
143 return false;
144 SrcDefinitionsToResolve.push_back(SSTy);
145 SpeculativeTypes.push_back(SrcTy);
146 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
147 Entry = DstTy;
148 return true;
149 }
150 }
151
152 // If the number of subtypes disagree between the two types, then we fail.
153 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
154 return false;
155
156 // Fail if any of the extra properties (e.g. array size) of the type disagree.
157 if (isa<IntegerType>(DstTy))
158 return false; // bitwidth disagrees.
159 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
160 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
161 return false;
162
163 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
164 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
165 return false;
166 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
167 StructType *SSTy = cast<StructType>(SrcTy);
168 if (DSTy->isLiteral() != SSTy->isLiteral() ||
169 DSTy->isPacked() != SSTy->isPacked())
170 return false;
171 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
172 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
173 return false;
174 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
175 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
176 return false;
177 }
178
179 // Otherwise, we speculate that these two types will line up and recursively
180 // check the subelements.
181 Entry = DstTy;
182 SpeculativeTypes.push_back(SrcTy);
183
184 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
185 if (!areTypesIsomorphic(DstTy->getContainedType(I),
186 SrcTy->getContainedType(I)))
187 return false;
188
189 // If everything seems to have lined up, then everything is great.
190 return true;
191}
192
193void TypeMapTy::linkDefinedTypeBodies() {
194 SmallVector<Type *, 16> Elements;
195 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
196 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
197 assert(DstSTy->isOpaque());
198
199 // Map the body of the source type over to a new body for the dest type.
200 Elements.resize(SrcSTy->getNumElements());
201 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
202 Elements[I] = get(SrcSTy->getElementType(I));
203
204 DstSTy->setBody(Elements, SrcSTy->isPacked());
205 DstStructTypesSet.switchToNonOpaque(DstSTy);
206 }
207 SrcDefinitionsToResolve.clear();
208 DstResolvedOpaqueTypes.clear();
209}
210
211void TypeMapTy::finishType(StructType *DTy, StructType *STy,
212 ArrayRef<Type *> ETypes) {
213 DTy->setBody(ETypes, STy->isPacked());
214
215 // Steal STy's name.
216 if (STy->hasName()) {
217 SmallString<16> TmpName = STy->getName();
218 STy->setName("");
219 DTy->setName(TmpName);
220 }
221
222 DstStructTypesSet.addNonOpaque(DTy);
223}
224
225Type *TypeMapTy::get(Type *Ty) {
226 SmallPtrSet<StructType *, 8> Visited;
227 return get(Ty, Visited);
228}
229
230Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
231 // If we already have an entry for this type, return it.
232 Type **Entry = &MappedTypes[Ty];
233 if (*Entry)
234 return *Entry;
235
236 // These are types that LLVM itself will unique.
237 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
238
239#ifndef NDEBUG
240 if (!IsUniqued) {
241 for (auto &Pair : MappedTypes) {
242 assert(!(Pair.first != Ty && Pair.second == Ty) &&
243 "mapping to a source type");
244 }
245 }
246#endif
247
248 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
249 StructType *DTy = StructType::create(Ty->getContext());
250 return *Entry = DTy;
251 }
252
253 // If this is not a recursive type, then just map all of the elements and
254 // then rebuild the type from inside out.
255 SmallVector<Type *, 4> ElementTypes;
256
257 // If there are no element types to map, then the type is itself. This is
258 // true for the anonymous {} struct, things like 'float', integers, etc.
259 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
260 return *Entry = Ty;
261
262 // Remap all of the elements, keeping track of whether any of them change.
263 bool AnyChange = false;
264 ElementTypes.resize(Ty->getNumContainedTypes());
265 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
266 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
267 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
268 }
269
270 // If we found our type while recursively processing stuff, just use it.
271 Entry = &MappedTypes[Ty];
272 if (*Entry) {
273 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
274 if (DTy->isOpaque()) {
275 auto *STy = cast<StructType>(Ty);
276 finishType(DTy, STy, ElementTypes);
277 }
278 }
279 return *Entry;
280 }
281
282 // If all of the element types mapped directly over and the type is not
283 // a nomed struct, then the type is usable as-is.
284 if (!AnyChange && IsUniqued)
285 return *Entry = Ty;
286
287 // Otherwise, rebuild a modified type.
288 switch (Ty->getTypeID()) {
289 default:
290 llvm_unreachable("unknown derived type to remap");
291 case Type::ArrayTyID:
292 return *Entry = ArrayType::get(ElementTypes[0],
293 cast<ArrayType>(Ty)->getNumElements());
294 case Type::VectorTyID:
295 return *Entry = VectorType::get(ElementTypes[0],
296 cast<VectorType>(Ty)->getNumElements());
297 case Type::PointerTyID:
298 return *Entry = PointerType::get(ElementTypes[0],
299 cast<PointerType>(Ty)->getAddressSpace());
300 case Type::FunctionTyID:
301 return *Entry = FunctionType::get(ElementTypes[0],
302 makeArrayRef(ElementTypes).slice(1),
303 cast<FunctionType>(Ty)->isVarArg());
304 case Type::StructTyID: {
305 auto *STy = cast<StructType>(Ty);
306 bool IsPacked = STy->isPacked();
307 if (IsUniqued)
308 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
309
310 // If the type is opaque, we can just use it directly.
311 if (STy->isOpaque()) {
312 DstStructTypesSet.addOpaque(STy);
313 return *Entry = Ty;
314 }
315
316 if (StructType *OldT =
317 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
318 STy->setName("");
319 return *Entry = OldT;
320 }
321
322 if (!AnyChange) {
323 DstStructTypesSet.addNonOpaque(STy);
324 return *Entry = Ty;
325 }
326
327 StructType *DTy = StructType::create(Ty->getContext());
328 finishType(DTy, STy, ElementTypes);
329 return *Entry = DTy;
330 }
331 }
332}
333
334LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
335 const Twine &Msg)
336 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
337void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
338
339//===----------------------------------------------------------------------===//
Teresa Johnsonbef54362015-12-18 19:28:59 +0000340// IRLinker implementation.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000341//===----------------------------------------------------------------------===//
342
343namespace {
344class IRLinker;
345
346/// Creates prototypes for functions that are lazily linked on the fly. This
347/// speeds up linking for modules with many/ lazily linked functions of which
348/// few get used.
349class GlobalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000350 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000351
352public:
Mehdi Amini33661072016-03-11 22:19:06 +0000353 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000354 Value *materialize(Value *V) 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) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000362 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000363};
364
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000365/// Type of the Metadata map in \a ValueToValueMapTy.
366typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
367
Rafael Espindolacaabe222015-12-10 14:19:35 +0000368/// This is responsible for keeping track of the state used for moving data
369/// from SrcM to DstM.
370class IRLinker {
371 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000372 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000373
Mehdi Amini33661072016-03-11 22:19:06 +0000374 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000375 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
376
377 TypeMapTy TypeMap;
378 GlobalValueMaterializer GValMaterializer;
379 LocalValueMaterializer LValMaterializer;
380
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000381 /// A metadata map that's shared between IRLinker instances.
382 MDMapT &SharedMDs;
383
Rafael Espindolacaabe222015-12-10 14:19:35 +0000384 /// Mapping of values from what they used to be in Src, to what they are now
385 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
386 /// due to the use of Value handles which the Linker doesn't actually need,
387 /// but this allows us to reuse the ValueMapper code.
388 ValueToValueMapTy ValueMap;
389 ValueToValueMapTy AliasValueMap;
390
391 DenseSet<GlobalValue *> ValuesToLink;
392 std::vector<GlobalValue *> Worklist;
393
394 void maybeAdd(GlobalValue *GV) {
395 if (ValuesToLink.insert(GV).second)
396 Worklist.push_back(GV);
397 }
398
Rafael Espindolacaabe222015-12-10 14:19:35 +0000399 /// Set to true when all global value body linking is complete (including
400 /// lazy linking). Used to prevent metadata linking from creating new
401 /// references.
402 bool DoneLinkingBodies = false;
403
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000404 /// The Error encountered during materialization. We use an Optional here to
405 /// avoid needing to manage an unconsumed success value.
406 Optional<Error> FoundError;
407 void setError(Error E) {
408 if (E)
409 FoundError = std::move(E);
410 }
411
412 /// Most of the errors produced by this module are inconvertible StringErrors.
413 /// This convenience function lets us return one of those more easily.
414 Error stringErr(const Twine &T) {
415 return make_error<StringError>(T, inconvertibleErrorCode());
416 }
Rafael Espindolacaabe222015-12-10 14:19:35 +0000417
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000418 /// Entry point for mapping values and alternate context for mapping aliases.
419 ValueMapper Mapper;
420 unsigned AliasMCID;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000421
Rafael Espindolacaabe222015-12-10 14:19:35 +0000422 /// Handles cloning of a global values from the source module into
423 /// the destination module, including setting the attributes and visibility.
424 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
425
Rafael Espindolacaabe222015-12-10 14:19:35 +0000426 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000427 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000428 }
429
430 /// Given a global in the source module, return the global in the
431 /// destination module that is being linked to, if any.
432 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
433 // If the source has no name it can't link. If it has local linkage,
434 // there is no name match-up going on.
435 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
436 return nullptr;
437
438 // Otherwise see if we have a match in the destination module's symtab.
439 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
440 if (!DGV)
441 return nullptr;
442
443 // If we found a global with the same name in the dest module, but it has
444 // internal linkage, we are really not doing any linkage here.
445 if (DGV->hasLocalLinkage())
446 return nullptr;
447
448 // Otherwise, we do in fact link to the destination global.
449 return DGV;
450 }
451
452 void computeTypeMapping();
453
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000454 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
455 const GlobalVariable *SrcGV);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000456
Mehdi Amini33661072016-03-11 22:19:06 +0000457 /// Given the GlobaValue \p SGV in the source module, and the matching
458 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
459 /// into the destination module.
460 ///
461 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000462 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000463 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000464
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000465 Error linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000466
467 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000468 Error linkFunctionBody(Function &Dst, Function &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000469 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000470 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000471
472 /// Functions that take care of cloning a specific global value type
473 /// into the destination module.
474 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
475 Function *copyFunctionProto(const Function *SF);
476 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
477
478 void linkNamedMDNodes();
479
480public:
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000481 IRLinker(Module &DstM, MDMapT &SharedMDs,
482 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
483 ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000484 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000485 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
486 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
487 SharedMDs(SharedMDs),
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000488 Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
489 &GValMaterializer),
490 AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
491 &LValMaterializer)) {
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000492 ValueMap.getMDMap() = std::move(SharedMDs);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000493 for (GlobalValue *GV : ValuesToLink)
494 maybeAdd(GV);
Teresa Johnsoncc428572015-12-30 19:32:24 +0000495 }
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000496 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Teresa Johnsoncc428572015-12-30 19:32:24 +0000497
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000498 Error run();
Mehdi Amini53a66722016-05-25 21:01:51 +0000499 Value *materialize(Value *V, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000500};
501}
502
503/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
504/// table. This is good for all clients except for us. Go through the trouble
505/// to force this back.
506static void forceRenaming(GlobalValue *GV, StringRef Name) {
507 // If the global doesn't force its name or if it already has the right name,
508 // there is nothing for us to do.
509 if (GV->hasLocalLinkage() || GV->getName() == Name)
510 return;
511
512 Module *M = GV->getParent();
513
514 // If there is a conflict, rename the conflict.
515 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
516 GV->takeName(ConflictGV);
517 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
518 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
519 } else {
520 GV->setName(Name); // Force the name back
521 }
522}
523
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000524Value *GlobalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000525 return TheIRLinker.materialize(SGV, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000526}
527
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000528Value *LocalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000529 return TheIRLinker.materialize(SGV, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000530}
531
Mehdi Amini53a66722016-05-25 21:01:51 +0000532Value *IRLinker::materialize(Value *V, bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000533 auto *SGV = dyn_cast<GlobalValue>(V);
534 if (!SGV)
535 return nullptr;
536
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000537 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
538 if (!NewProto) {
539 setError(NewProto.takeError());
540 return nullptr;
541 }
542 if (!*NewProto)
543 return nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000544
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000545 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
Mehdi Amini53a66722016-05-25 21:01:51 +0000546 if (!New)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000547 return *NewProto;
Mehdi Amini53a66722016-05-25 21:01:51 +0000548
Rafael Espindolacaabe222015-12-10 14:19:35 +0000549 // If we already created the body, just return.
550 if (auto *F = dyn_cast<Function>(New)) {
551 if (!F->isDeclaration())
Mehdi Amini53a66722016-05-25 21:01:51 +0000552 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000553 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000554 if (V->hasInitializer() || V->hasAppendingLinkage())
Mehdi Amini53a66722016-05-25 21:01:51 +0000555 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000556 } else {
557 auto *A = cast<GlobalAlias>(New);
558 if (A->getAliasee())
Mehdi Amini53a66722016-05-25 21:01:51 +0000559 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000560 }
561
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000562 // When linking a global for an alias, it will always be linked. However we
563 // need to check if it was not already scheduled to satify a reference from a
564 // regular global value initializer. We know if it has been schedule if the
565 // "New" GlobalValue that is mapped here for the alias is the same as the one
566 // already mapped. If there is an entry in the ValueMap but the value is
567 // different, it means that the value already had a definition in the
568 // destination module (linkonce for instance), but we need a new definition
569 // for the alias ("New" will be different.
Mehdi Amini53a66722016-05-25 21:01:51 +0000570 if (ForAlias && ValueMap.lookup(SGV) == New)
571 return New;
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000572
Mehdi Amini53a66722016-05-25 21:01:51 +0000573 if (ForAlias || shouldLink(New, *SGV))
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000574 setError(linkGlobalValueBody(*New, *SGV));
Mehdi Amini53a66722016-05-25 21:01:51 +0000575
576 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000577}
578
579/// Loop through the global variables in the src module and merge them into the
580/// dest module.
581GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
582 // No linking to be performed or linking from the source: simply create an
583 // identical version of the symbol over in the dest module... the
584 // initializer will be filled in later by LinkGlobalInits.
585 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000586 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000587 SGVar->isConstant(), GlobalValue::ExternalLinkage,
588 /*init*/ nullptr, SGVar->getName(),
589 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
590 SGVar->getType()->getAddressSpace());
591 NewDGV->setAlignment(SGVar->getAlignment());
592 return NewDGV;
593}
594
595/// Link the function in the source module into the destination module if
596/// needed, setting up mapping information.
597Function *IRLinker::copyFunctionProto(const Function *SF) {
598 // If there is no linkage to be performed or we are linking from the source,
599 // bring SF over.
600 return Function::Create(TypeMap.get(SF->getFunctionType()),
601 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
602}
603
604/// Set up prototypes for any aliases that come over from the source module.
605GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
606 // If there is no linkage to be performed or we're linking from the source,
607 // bring over SGA.
608 auto *Ty = TypeMap.get(SGA->getValueType());
609 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
610 GlobalValue::ExternalLinkage, SGA->getName(),
611 &DstM);
612}
613
614GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
615 bool ForDefinition) {
616 GlobalValue *NewGV;
617 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
618 NewGV = copyGlobalVariableProto(SGVar);
619 } else if (auto *SF = dyn_cast<Function>(SGV)) {
620 NewGV = copyFunctionProto(SF);
621 } else {
622 if (ForDefinition)
623 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
624 else
625 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000626 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000627 /*isConstant*/ false, GlobalValue::ExternalLinkage,
628 /*init*/ nullptr, SGV->getName(),
629 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
630 SGV->getType()->getAddressSpace());
631 }
632
633 if (ForDefinition)
634 NewGV->setLinkage(SGV->getLinkage());
Mehdi Amini113adde2016-04-19 16:11:05 +0000635 else if (SGV->hasExternalWeakLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000636 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
637
638 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000639
Reid Klecknerc0a03632016-05-25 18:36:22 +0000640 // Don't copy the comdat, it's from the original module. We'll handle it
641 // later.
642 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV))
643 NewGO->setComdat(nullptr);
644
Teresa Johnson5fe40052016-01-12 00:24:24 +0000645 // Remove these copied constants in case this stays a declaration, since
646 // they point to the source module. If the def is linked the values will
647 // be mapped in during linkFunctionBody.
648 if (auto *NewF = dyn_cast<Function>(NewGV)) {
649 NewF->setPersonalityFn(nullptr);
650 NewF->setPrefixData(nullptr);
651 NewF->setPrologueData(nullptr);
652 }
653
Rafael Espindolacaabe222015-12-10 14:19:35 +0000654 return NewGV;
655}
656
657/// Loop over all of the linked values to compute type mappings. For example,
658/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
659/// types 'Foo' but one got renamed when the module was loaded into the same
660/// LLVMContext.
661void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000662 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000663 GlobalValue *DGV = getLinkedToGlobal(&SGV);
664 if (!DGV)
665 continue;
666
667 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
668 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
669 continue;
670 }
671
672 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000673 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
674 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000675 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
676 }
677
Rafael Espindola40358fb2016-02-16 18:50:12 +0000678 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000679 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
680 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
681
Rafael Espindola40358fb2016-02-16 18:50:12 +0000682 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000683 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
684 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
685
686 // Incorporate types by name, scanning all the types in the source module.
687 // At this point, the destination module may have a type "%foo = { i32 }" for
688 // example. When the source module got loaded into the same LLVMContext, if
689 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000690 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000691 for (StructType *ST : Types) {
692 if (!ST->hasName())
693 continue;
694
695 // Check to see if there is a dot in the name followed by a digit.
696 size_t DotPos = ST->getName().rfind('.');
697 if (DotPos == 0 || DotPos == StringRef::npos ||
698 ST->getName().back() == '.' ||
699 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
700 continue;
701
702 // Check to see if the destination module has a struct with the prefix name.
703 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
704 if (!DST)
705 continue;
706
707 // Don't use it if this actually came from the source module. They're in
708 // the same LLVMContext after all. Also don't use it unless the type is
709 // actually used in the destination module. This can happen in situations
710 // like this:
711 //
712 // Module A Module B
713 // -------- --------
714 // %Z = type { %A } %B = type { %C.1 }
715 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
716 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
717 // %C = type { i8* } %B.3 = type { %C.1 }
718 //
719 // When we link Module B with Module A, the '%B' in Module B is
720 // used. However, that would then use '%C.1'. But when we process '%C.1',
721 // we prefer to take the '%C' version. So we are then left with both
722 // '%C.1' and '%C' being used for the same types. This leads to some
723 // variables using one type and some using the other.
724 if (TypeMap.DstStructTypesSet.hasType(DST))
725 TypeMap.addTypeMapping(DST, ST);
726 }
727
728 // Now that we have discovered all of the type equivalences, get a body for
729 // any 'opaque' types in the dest module that are now resolved.
730 TypeMap.linkDefinedTypeBodies();
731}
732
733static void getArrayElements(const Constant *C,
734 SmallVectorImpl<Constant *> &Dest) {
735 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
736
737 for (unsigned i = 0; i != NumElements; ++i)
738 Dest.push_back(C->getAggregateElement(i));
739}
740
741/// If there were any appending global variables, link them together now.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000742Expected<Constant *>
743IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
744 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000745 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000746 ->getElementType();
747
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000748 // FIXME: This upgrade is done during linking to support the C API. Once the
749 // old form is deprecated, we should move this upgrade to
750 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
751 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000752 StringRef Name = SrcGV->getName();
753 bool IsNewStructor = false;
754 bool IsOldStructor = false;
755 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
756 if (cast<StructType>(EltTy)->getNumElements() == 3)
757 IsNewStructor = true;
758 else
759 IsOldStructor = true;
760 }
761
762 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
763 if (IsOldStructor) {
764 auto &ST = *cast<StructType>(EltTy);
765 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
766 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
767 }
768
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000769 uint64_t DstNumElements = 0;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000770 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000771 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000772 DstNumElements = DstTy->getNumElements();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000773
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000774 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
775 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000776 "Linking globals named '" + SrcGV->getName() +
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000777 "': can only link appending global with another appending "
778 "global!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000779
780 // Check to see that they two arrays agree on type.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000781 if (EltTy != DstTy->getElementType())
782 return stringErr("Appending variables with different element types!");
783 if (DstGV->isConstant() != SrcGV->isConstant())
784 return stringErr("Appending variables linked with different const'ness!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000785
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000786 if (DstGV->getAlignment() != SrcGV->getAlignment())
787 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000788 "Appending variables with different alignment need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000789
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000790 if (DstGV->getVisibility() != SrcGV->getVisibility())
791 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000792 "Appending variables with different visibility need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000793
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000794 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
795 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000796 "Appending variables with different unnamed_addr need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000797
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000798 if (DstGV->getSection() != SrcGV->getSection())
799 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000800 "Appending variables with different section name need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000801 }
802
Rafael Espindolacaabe222015-12-10 14:19:35 +0000803 SmallVector<Constant *, 16> SrcElements;
804 getArrayElements(SrcGV->getInitializer(), SrcElements);
805
806 if (IsNewStructor)
807 SrcElements.erase(
808 std::remove_if(SrcElements.begin(), SrcElements.end(),
809 [this](Constant *E) {
810 auto *Key = dyn_cast<GlobalValue>(
811 E->getAggregateElement(2)->stripPointerCasts());
812 if (!Key)
813 return false;
814 GlobalValue *DGV = getLinkedToGlobal(Key);
815 return !shouldLink(DGV, *Key);
816 }),
817 SrcElements.end());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000818 uint64_t NewSize = DstNumElements + SrcElements.size();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000819 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
820
821 // Create the new global variable.
822 GlobalVariable *NG = new GlobalVariable(
823 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
824 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
825 SrcGV->getType()->getAddressSpace());
826
827 NG->copyAttributesFrom(SrcGV);
828 forceRenaming(NG, SrcGV->getName());
829
830 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
831
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000832 Mapper.scheduleMapAppendingVariable(*NG,
833 DstGV ? DstGV->getInitializer() : nullptr,
834 IsOldStructor, SrcElements);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000835
836 // Replace any uses of the two global variables with uses of the new
837 // global.
838 if (DstGV) {
839 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
840 DstGV->eraseFromParent();
841 }
842
843 return Ret;
844}
845
Rafael Espindolacaabe222015-12-10 14:19:35 +0000846bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
847 if (ValuesToLink.count(&SGV))
848 return true;
849
850 if (SGV.hasLocalLinkage())
851 return true;
852
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000853 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000854 return false;
855
856 if (SGV.hasAvailableExternallyLinkage())
857 return true;
858
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000859 if (SGV.isDeclaration())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000860 return false;
861
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000862 if (DoneLinkingBodies)
863 return false;
Mehdi Amini33661072016-03-11 22:19:06 +0000864
865 // Callback to the client to give a chance to lazily add the Global to the
866 // list of value to link.
867 bool LazilyAdded = false;
868 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
869 maybeAdd(&GV);
870 LazilyAdded = true;
871 });
872 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000873}
874
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000875Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
876 bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000877 GlobalValue *DGV = getLinkedToGlobal(SGV);
878
879 bool ShouldLink = shouldLink(DGV, *SGV);
880
881 // just missing from map
882 if (ShouldLink) {
883 auto I = ValueMap.find(SGV);
884 if (I != ValueMap.end())
885 return cast<Constant>(I->second);
886
887 I = AliasValueMap.find(SGV);
888 if (I != AliasValueMap.end())
889 return cast<Constant>(I->second);
890 }
891
Mehdi Amini33661072016-03-11 22:19:06 +0000892 if (!ShouldLink && ForAlias)
893 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000894
895 // Handle the ultra special appending linkage case first.
896 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
897 if (SGV->hasAppendingLinkage())
898 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
899 cast<GlobalVariable>(SGV));
900
901 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000902 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000903 NewGV = DGV;
904 } else {
905 // If we are done linking global value bodies (i.e. we are performing
906 // metadata linking), don't link in the global value due to this
907 // reference, simply map it to null.
908 if (DoneLinkingBodies)
909 return nullptr;
910
911 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +0000912 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000913 forceRenaming(NewGV, SGV->getName());
914 }
915 if (ShouldLink || ForAlias) {
916 if (const Comdat *SC = SGV->getComdat()) {
917 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
918 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
919 DC->setSelectionKind(SC->getSelectionKind());
920 GO->setComdat(DC);
921 }
922 }
923 }
924
925 if (!ShouldLink && ForAlias)
926 NewGV->setLinkage(GlobalValue::InternalLinkage);
927
928 Constant *C = NewGV;
929 if (DGV)
930 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
931
932 if (DGV && NewGV != DGV) {
933 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
934 DGV->eraseFromParent();
935 }
936
937 return C;
938}
939
940/// Update the initializers in the Dest module now that all globals that may be
941/// referenced are in Dest.
942void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
943 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000944 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000945}
946
947/// Copy the source function over into the dest function and fix up references
948/// to values. At this point we know that Dest is an external function, and
949/// that Src is not.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000950Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000951 assert(Dst.isDeclaration() && !Src.isDeclaration());
952
953 // Materialize if needed.
954 if (std::error_code EC = Src.materialize())
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000955 return errorCodeToError(EC);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000956
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000957 // Link in the operands without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000958 if (Src.hasPrefixData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000959 Dst.setPrefixData(Src.getPrefixData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000960 if (Src.hasPrologueData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000961 Dst.setPrologueData(Src.getPrologueData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000962 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000963 Dst.setPersonalityFn(Src.getPersonalityFn());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000964
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000965 // Copy over the metadata attachments without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000966 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
967 Src.getAllMetadata(MDs);
968 for (const auto &I : MDs)
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000969 Dst.setMetadata(I.first, I.second);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000970
Duncan P. N. Exon Smithbdfc9842016-04-06 06:38:15 +0000971 // Steal arguments and splice the body of Src into Dst.
972 Dst.stealArgumentListFrom(Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000973 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
974
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000975 // Everything has been moved over. Remap it.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000976 Mapper.scheduleRemapFunction(Dst);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000977 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000978}
979
980void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000981 Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000982}
983
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000984Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000985 if (auto *F = dyn_cast<Function>(&Src))
986 return linkFunctionBody(cast<Function>(Dst), *F);
987 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
988 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000989 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000990 }
991 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000992 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000993}
994
995/// Insert all of the named MDNodes in Src into the Dest module.
996void IRLinker::linkNamedMDNodes() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000997 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
998 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000999 // Don't link module flags here. Do them separately.
1000 if (&NMD == SrcModFlags)
1001 continue;
1002 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1003 // Add Src elements into Dest node.
Duncan P. N. Exon Smith8a15dab2016-04-15 23:32:44 +00001004 for (const MDNode *Op : NMD.operands())
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001005 DestNMD->addOperand(Mapper.mapMDNode(*Op));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001006 }
1007}
1008
1009/// Merge the linker flags in Src into the Dest module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001010Error IRLinker::linkModuleFlagsMetadata() {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001011 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001012 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001013 if (!SrcModFlags)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001014 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001015
1016 // If the destination module doesn't have module flags yet, then just copy
1017 // over the source module's flags.
1018 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1019 if (DstModFlags->getNumOperands() == 0) {
1020 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1021 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1022
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001023 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001024 }
1025
1026 // First build a map of the existing module flags and requirements.
1027 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1028 SmallSetVector<MDNode *, 16> Requirements;
1029 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1030 MDNode *Op = DstModFlags->getOperand(I);
1031 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1032 MDString *ID = cast<MDString>(Op->getOperand(1));
1033
1034 if (Behavior->getZExtValue() == Module::Require) {
1035 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1036 } else {
1037 Flags[ID] = std::make_pair(Op, I);
1038 }
1039 }
1040
1041 // Merge in the flags from the source module, and also collect its set of
1042 // requirements.
1043 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1044 MDNode *SrcOp = SrcModFlags->getOperand(I);
1045 ConstantInt *SrcBehavior =
1046 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1047 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1048 MDNode *DstOp;
1049 unsigned DstIndex;
1050 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1051 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1052
1053 // If this is a requirement, add it and continue.
1054 if (SrcBehaviorValue == Module::Require) {
1055 // If the destination module does not already have this requirement, add
1056 // it.
1057 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1058 DstModFlags->addOperand(SrcOp);
1059 }
1060 continue;
1061 }
1062
1063 // If there is no existing flag with this ID, just add it.
1064 if (!DstOp) {
1065 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1066 DstModFlags->addOperand(SrcOp);
1067 continue;
1068 }
1069
1070 // Otherwise, perform a merge.
1071 ConstantInt *DstBehavior =
1072 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1073 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1074
1075 // If either flag has override behavior, handle it first.
1076 if (DstBehaviorValue == Module::Override) {
1077 // Diagnose inconsistent flags which both have override behavior.
1078 if (SrcBehaviorValue == Module::Override &&
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001079 SrcOp->getOperand(2) != DstOp->getOperand(2))
1080 return stringErr("linking module flags '" + ID->getString() +
1081 "': IDs have conflicting override values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001082 continue;
1083 } else if (SrcBehaviorValue == Module::Override) {
1084 // Update the destination flag to that of the source.
1085 DstModFlags->setOperand(DstIndex, SrcOp);
1086 Flags[ID].first = SrcOp;
1087 continue;
1088 }
1089
1090 // Diagnose inconsistent merge behavior types.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001091 if (SrcBehaviorValue != DstBehaviorValue)
1092 return stringErr("linking module flags '" + ID->getString() +
1093 "': IDs have conflicting behaviors");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001094
1095 auto replaceDstValue = [&](MDNode *New) {
1096 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1097 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1098 DstModFlags->setOperand(DstIndex, Flag);
1099 Flags[ID].first = Flag;
1100 };
1101
1102 // Perform the merge for standard behavior types.
1103 switch (SrcBehaviorValue) {
1104 case Module::Require:
1105 case Module::Override:
1106 llvm_unreachable("not possible");
1107 case Module::Error: {
1108 // Emit an error if the values differ.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001109 if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1110 return stringErr("linking module flags '" + ID->getString() +
1111 "': IDs have conflicting values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001112 continue;
1113 }
1114 case Module::Warning: {
1115 // Emit a warning if the values differ.
1116 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1117 emitWarning("linking module flags '" + ID->getString() +
1118 "': IDs have conflicting values");
1119 }
1120 continue;
1121 }
1122 case Module::Append: {
1123 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1124 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1125 SmallVector<Metadata *, 8> MDs;
1126 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1127 MDs.append(DstValue->op_begin(), DstValue->op_end());
1128 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1129
1130 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1131 break;
1132 }
1133 case Module::AppendUnique: {
1134 SmallSetVector<Metadata *, 16> Elts;
1135 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1136 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1137 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1138 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1139
1140 replaceDstValue(MDNode::get(DstM.getContext(),
1141 makeArrayRef(Elts.begin(), Elts.end())));
1142 break;
1143 }
1144 }
1145 }
1146
1147 // Check all of the requirements.
1148 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1149 MDNode *Requirement = Requirements[I];
1150 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1151 Metadata *ReqValue = Requirement->getOperand(1);
1152
1153 MDNode *Op = Flags[Flag].first;
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001154 if (!Op || Op->getOperand(2) != ReqValue)
1155 return stringErr("linking module flags '" + Flag->getString() +
1156 "': does not have the required value");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001157 }
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001158 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001159}
1160
1161// This function returns true if the triples match.
1162static bool triplesMatch(const Triple &T0, const Triple &T1) {
1163 // If vendor is apple, ignore the version number.
1164 if (T0.getVendor() == Triple::Apple)
1165 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1166 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1167
1168 return T0 == T1;
1169}
1170
1171// This function returns the merged triple.
1172static std::string mergeTriples(const Triple &SrcTriple,
1173 const Triple &DstTriple) {
1174 // If vendor is apple, pick the triple with the larger version number.
1175 if (SrcTriple.getVendor() == Triple::Apple)
1176 if (DstTriple.isOSVersionLT(SrcTriple))
1177 return SrcTriple.str();
1178
1179 return DstTriple.str();
1180}
1181
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001182Error IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001183 // Ensure metadata materialized before value mapping.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001184 if (SrcM->getMaterializer())
1185 if (std::error_code EC = SrcM->getMaterializer()->materializeMetadata())
1186 return errorCodeToError(EC);
Teresa Johnson0556e222016-03-10 18:47:03 +00001187
Rafael Espindolacaabe222015-12-10 14:19:35 +00001188 // Inherit the target data from the source module if the destination module
1189 // doesn't have one already.
1190 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001191 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001192
Rafael Espindola40358fb2016-02-16 18:50:12 +00001193 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001194 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001195 SrcM->getModuleIdentifier() + "' is '" +
1196 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001197 DstM.getModuleIdentifier() + "' is '" +
1198 DstM.getDataLayoutStr() + "'\n");
1199 }
1200
1201 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001202 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1203 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001204
Rafael Espindola40358fb2016-02-16 18:50:12 +00001205 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001206
Rafael Espindola40358fb2016-02-16 18:50:12 +00001207 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001208 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001209 SrcM->getModuleIdentifier() + "' is '" +
1210 SrcM->getTargetTriple() + "' whereas '" +
1211 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1212 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001213
1214 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1215
1216 // Append the module inline asm string.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001217 if (!SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001218 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001219 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001220 else
1221 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001222 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001223 }
1224
1225 // Loop over all of the linked values to compute type mappings.
1226 computeTypeMapping();
1227
1228 std::reverse(Worklist.begin(), Worklist.end());
1229 while (!Worklist.empty()) {
1230 GlobalValue *GV = Worklist.back();
1231 Worklist.pop_back();
1232
1233 // Already mapped.
1234 if (ValueMap.find(GV) != ValueMap.end() ||
1235 AliasValueMap.find(GV) != AliasValueMap.end())
1236 continue;
1237
1238 assert(!GV->isDeclaration());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001239 Mapper.mapValue(*GV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001240 if (FoundError)
1241 return std::move(*FoundError);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001242 }
1243
1244 // Note that we are done linking global value bodies. This prevents
1245 // metadata linking from creating new references.
1246 DoneLinkingBodies = true;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001247 Mapper.addFlags(RF_NullMapMissingGlobalValues);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001248
1249 // Remap all of the named MDNodes in Src into the DstM module. We do this
1250 // after linking GlobalValues so that MDNodes that reference GlobalValues
1251 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001252 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001253
Teresa Johnsonb703c772016-03-29 18:24:19 +00001254 // Merge the module flags into the DstM module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001255 return linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001256}
1257
1258IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1259 : ETypes(E), IsPacked(P) {}
1260
1261IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1262 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1263
1264bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1265 if (IsPacked != That.IsPacked)
1266 return false;
1267 if (ETypes != That.ETypes)
1268 return false;
1269 return true;
1270}
1271
1272bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1273 return !this->operator==(That);
1274}
1275
1276StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1277 return DenseMapInfo<StructType *>::getEmptyKey();
1278}
1279
1280StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1281 return DenseMapInfo<StructType *>::getTombstoneKey();
1282}
1283
1284unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1285 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1286 Key.IsPacked);
1287}
1288
1289unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1290 return getHashValue(KeyTy(ST));
1291}
1292
1293bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1294 const StructType *RHS) {
1295 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1296 return false;
1297 return LHS == KeyTy(RHS);
1298}
1299
1300bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1301 const StructType *RHS) {
1302 if (RHS == getEmptyKey())
1303 return LHS == getEmptyKey();
1304
1305 if (RHS == getTombstoneKey())
1306 return LHS == getTombstoneKey();
1307
1308 return KeyTy(LHS) == KeyTy(RHS);
1309}
1310
1311void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1312 assert(!Ty->isOpaque());
1313 NonOpaqueStructTypes.insert(Ty);
1314}
1315
1316void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1317 assert(!Ty->isOpaque());
1318 NonOpaqueStructTypes.insert(Ty);
1319 bool Removed = OpaqueStructTypes.erase(Ty);
1320 (void)Removed;
1321 assert(Removed);
1322}
1323
1324void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1325 assert(Ty->isOpaque());
1326 OpaqueStructTypes.insert(Ty);
1327}
1328
1329StructType *
1330IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1331 bool IsPacked) {
1332 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1333 auto I = NonOpaqueStructTypes.find_as(Key);
1334 if (I == NonOpaqueStructTypes.end())
1335 return nullptr;
1336 return *I;
1337}
1338
1339bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1340 if (Ty->isOpaque())
1341 return OpaqueStructTypes.count(Ty);
1342 auto I = NonOpaqueStructTypes.find(Ty);
1343 if (I == NonOpaqueStructTypes.end())
1344 return false;
1345 return *I == Ty;
1346}
1347
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001348IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001349 TypeFinder StructTypes;
1350 StructTypes.run(M, true);
1351 for (StructType *Ty : StructTypes) {
1352 if (Ty->isOpaque())
1353 IdentifiedStructTypes.addOpaque(Ty);
1354 else
1355 IdentifiedStructTypes.addNonOpaque(Ty);
1356 }
1357}
1358
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001359Error IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001360 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +00001361 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +00001362 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1363 std::move(Src), ValuesToLink, AddLazyFor);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001364 Error E = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001365 Composite.dropTriviallyDeadConstantArrays();
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001366 return E;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001367}