blob: 5577c50b2a9cd71e36fc33fc9fd4a870863abd08 [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"
22using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25// TypeMap implementation.
26//===----------------------------------------------------------------------===//
27
28namespace {
29class TypeMapTy : public ValueMapTypeRemapper {
30 /// This is a mapping from a source type to a destination type to use.
31 DenseMap<Type *, Type *> MappedTypes;
32
33 /// When checking to see if two subgraphs are isomorphic, we speculatively
34 /// add types to MappedTypes, but keep track of them here in case we need to
35 /// roll back.
36 SmallVector<Type *, 16> SpeculativeTypes;
37
38 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
39
40 /// This is a list of non-opaque structs in the source module that are mapped
41 /// to an opaque struct in the destination module.
42 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
43
44 /// This is the set of opaque types in the destination modules who are
45 /// getting a body from the source module.
46 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
47
48public:
49 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
50 : DstStructTypesSet(DstStructTypesSet) {}
51
52 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
53 /// Indicate that the specified type in the destination module is conceptually
54 /// equivalent to the specified type in the source module.
55 void addTypeMapping(Type *DstTy, Type *SrcTy);
56
57 /// Produce a body for an opaque type in the dest module from a type
58 /// definition in the source module.
59 void linkDefinedTypeBodies();
60
61 /// Return the mapped type to use for the specified input type from the
62 /// source module.
63 Type *get(Type *SrcTy);
64 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
65
66 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
67
68 FunctionType *get(FunctionType *T) {
69 return cast<FunctionType>(get((Type *)T));
70 }
71
72private:
73 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
74
75 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
76};
77}
78
79void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
80 assert(SpeculativeTypes.empty());
81 assert(SpeculativeDstOpaqueTypes.empty());
82
83 // Check to see if these types are recursively isomorphic and establish a
84 // mapping between them if so.
85 if (!areTypesIsomorphic(DstTy, SrcTy)) {
86 // Oops, they aren't isomorphic. Just discard this request by rolling out
87 // any speculative mappings we've established.
88 for (Type *Ty : SpeculativeTypes)
89 MappedTypes.erase(Ty);
90
91 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
92 SpeculativeDstOpaqueTypes.size());
93 for (StructType *Ty : SpeculativeDstOpaqueTypes)
94 DstResolvedOpaqueTypes.erase(Ty);
95 } else {
96 for (Type *Ty : SpeculativeTypes)
97 if (auto *STy = dyn_cast<StructType>(Ty))
98 if (STy->hasName())
99 STy->setName("");
100 }
101 SpeculativeTypes.clear();
102 SpeculativeDstOpaqueTypes.clear();
103}
104
105/// Recursively walk this pair of types, returning true if they are isomorphic,
106/// false if they are not.
107bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
108 // Two types with differing kinds are clearly not isomorphic.
109 if (DstTy->getTypeID() != SrcTy->getTypeID())
110 return false;
111
112 // If we have an entry in the MappedTypes table, then we have our answer.
113 Type *&Entry = MappedTypes[SrcTy];
114 if (Entry)
115 return Entry == DstTy;
116
117 // Two identical types are clearly isomorphic. Remember this
118 // non-speculatively.
119 if (DstTy == SrcTy) {
120 Entry = DstTy;
121 return true;
122 }
123
124 // Okay, we have two types with identical kinds that we haven't seen before.
125
126 // If this is an opaque struct type, special case it.
127 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
128 // Mapping an opaque type to any struct, just keep the dest struct.
129 if (SSTy->isOpaque()) {
130 Entry = DstTy;
131 SpeculativeTypes.push_back(SrcTy);
132 return true;
133 }
134
135 // Mapping a non-opaque source type to an opaque dest. If this is the first
136 // type that we're mapping onto this destination type then we succeed. Keep
137 // the dest, but fill it in later. If this is the second (different) type
138 // that we're trying to map onto the same opaque type then we fail.
139 if (cast<StructType>(DstTy)->isOpaque()) {
140 // We can only map one source type onto the opaque destination type.
141 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
142 return false;
143 SrcDefinitionsToResolve.push_back(SSTy);
144 SpeculativeTypes.push_back(SrcTy);
145 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
146 Entry = DstTy;
147 return true;
148 }
149 }
150
151 // If the number of subtypes disagree between the two types, then we fail.
152 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
153 return false;
154
155 // Fail if any of the extra properties (e.g. array size) of the type disagree.
156 if (isa<IntegerType>(DstTy))
157 return false; // bitwidth disagrees.
158 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
159 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
160 return false;
161
162 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
163 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
164 return false;
165 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
166 StructType *SSTy = cast<StructType>(SrcTy);
167 if (DSTy->isLiteral() != SSTy->isLiteral() ||
168 DSTy->isPacked() != SSTy->isPacked())
169 return false;
170 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
171 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
172 return false;
173 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
174 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
175 return false;
176 }
177
178 // Otherwise, we speculate that these two types will line up and recursively
179 // check the subelements.
180 Entry = DstTy;
181 SpeculativeTypes.push_back(SrcTy);
182
183 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
184 if (!areTypesIsomorphic(DstTy->getContainedType(I),
185 SrcTy->getContainedType(I)))
186 return false;
187
188 // If everything seems to have lined up, then everything is great.
189 return true;
190}
191
192void TypeMapTy::linkDefinedTypeBodies() {
193 SmallVector<Type *, 16> Elements;
194 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
195 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
196 assert(DstSTy->isOpaque());
197
198 // Map the body of the source type over to a new body for the dest type.
199 Elements.resize(SrcSTy->getNumElements());
200 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
201 Elements[I] = get(SrcSTy->getElementType(I));
202
203 DstSTy->setBody(Elements, SrcSTy->isPacked());
204 DstStructTypesSet.switchToNonOpaque(DstSTy);
205 }
206 SrcDefinitionsToResolve.clear();
207 DstResolvedOpaqueTypes.clear();
208}
209
210void TypeMapTy::finishType(StructType *DTy, StructType *STy,
211 ArrayRef<Type *> ETypes) {
212 DTy->setBody(ETypes, STy->isPacked());
213
214 // Steal STy's name.
215 if (STy->hasName()) {
216 SmallString<16> TmpName = STy->getName();
217 STy->setName("");
218 DTy->setName(TmpName);
219 }
220
221 DstStructTypesSet.addNonOpaque(DTy);
222}
223
224Type *TypeMapTy::get(Type *Ty) {
225 SmallPtrSet<StructType *, 8> Visited;
226 return get(Ty, Visited);
227}
228
229Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
230 // If we already have an entry for this type, return it.
231 Type **Entry = &MappedTypes[Ty];
232 if (*Entry)
233 return *Entry;
234
235 // These are types that LLVM itself will unique.
236 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
237
238#ifndef NDEBUG
239 if (!IsUniqued) {
240 for (auto &Pair : MappedTypes) {
241 assert(!(Pair.first != Ty && Pair.second == Ty) &&
242 "mapping to a source type");
243 }
244 }
245#endif
246
247 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
248 StructType *DTy = StructType::create(Ty->getContext());
249 return *Entry = DTy;
250 }
251
252 // If this is not a recursive type, then just map all of the elements and
253 // then rebuild the type from inside out.
254 SmallVector<Type *, 4> ElementTypes;
255
256 // If there are no element types to map, then the type is itself. This is
257 // true for the anonymous {} struct, things like 'float', integers, etc.
258 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
259 return *Entry = Ty;
260
261 // Remap all of the elements, keeping track of whether any of them change.
262 bool AnyChange = false;
263 ElementTypes.resize(Ty->getNumContainedTypes());
264 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
265 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
266 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
267 }
268
269 // If we found our type while recursively processing stuff, just use it.
270 Entry = &MappedTypes[Ty];
271 if (*Entry) {
272 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
273 if (DTy->isOpaque()) {
274 auto *STy = cast<StructType>(Ty);
275 finishType(DTy, STy, ElementTypes);
276 }
277 }
278 return *Entry;
279 }
280
281 // If all of the element types mapped directly over and the type is not
282 // a nomed struct, then the type is usable as-is.
283 if (!AnyChange && IsUniqued)
284 return *Entry = Ty;
285
286 // Otherwise, rebuild a modified type.
287 switch (Ty->getTypeID()) {
288 default:
289 llvm_unreachable("unknown derived type to remap");
290 case Type::ArrayTyID:
291 return *Entry = ArrayType::get(ElementTypes[0],
292 cast<ArrayType>(Ty)->getNumElements());
293 case Type::VectorTyID:
294 return *Entry = VectorType::get(ElementTypes[0],
295 cast<VectorType>(Ty)->getNumElements());
296 case Type::PointerTyID:
297 return *Entry = PointerType::get(ElementTypes[0],
298 cast<PointerType>(Ty)->getAddressSpace());
299 case Type::FunctionTyID:
300 return *Entry = FunctionType::get(ElementTypes[0],
301 makeArrayRef(ElementTypes).slice(1),
302 cast<FunctionType>(Ty)->isVarArg());
303 case Type::StructTyID: {
304 auto *STy = cast<StructType>(Ty);
305 bool IsPacked = STy->isPacked();
306 if (IsUniqued)
307 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
308
309 // If the type is opaque, we can just use it directly.
310 if (STy->isOpaque()) {
311 DstStructTypesSet.addOpaque(STy);
312 return *Entry = Ty;
313 }
314
315 if (StructType *OldT =
316 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
317 STy->setName("");
318 return *Entry = OldT;
319 }
320
321 if (!AnyChange) {
322 DstStructTypesSet.addNonOpaque(STy);
323 return *Entry = Ty;
324 }
325
326 StructType *DTy = StructType::create(Ty->getContext());
327 finishType(DTy, STy, ElementTypes);
328 return *Entry = DTy;
329 }
330 }
331}
332
333LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
334 const Twine &Msg)
335 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
336void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
337
338//===----------------------------------------------------------------------===//
Teresa Johnsonbef54362015-12-18 19:28:59 +0000339// IRLinker implementation.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000340//===----------------------------------------------------------------------===//
341
342namespace {
343class IRLinker;
344
345/// Creates prototypes for functions that are lazily linked on the fly. This
346/// speeds up linking for modules with many/ lazily linked functions of which
347/// few get used.
348class GlobalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000349 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000350
351public:
Mehdi Amini33661072016-03-11 22:19:06 +0000352 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000353 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000354};
355
356class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000357 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000358
359public:
Mehdi Amini33661072016-03-11 22:19:06 +0000360 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000361 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000362};
363
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000364/// Type of the Metadata map in \a ValueToValueMapTy.
365typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
366
Rafael Espindolacaabe222015-12-10 14:19:35 +0000367/// This is responsible for keeping track of the state used for moving data
368/// from SrcM to DstM.
369class IRLinker {
370 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000371 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000372
Mehdi Amini33661072016-03-11 22:19:06 +0000373 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000374 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
375
376 TypeMapTy TypeMap;
377 GlobalValueMaterializer GValMaterializer;
378 LocalValueMaterializer LValMaterializer;
379
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000380 /// A metadata map that's shared between IRLinker instances.
381 MDMapT &SharedMDs;
382
Rafael Espindolacaabe222015-12-10 14:19:35 +0000383 /// Mapping of values from what they used to be in Src, to what they are now
384 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
385 /// due to the use of Value handles which the Linker doesn't actually need,
386 /// but this allows us to reuse the ValueMapper code.
387 ValueToValueMapTy ValueMap;
388 ValueToValueMapTy AliasValueMap;
389
390 DenseSet<GlobalValue *> ValuesToLink;
391 std::vector<GlobalValue *> Worklist;
392
393 void maybeAdd(GlobalValue *GV) {
394 if (ValuesToLink.insert(GV).second)
395 Worklist.push_back(GV);
396 }
397
Rafael Espindolacaabe222015-12-10 14:19:35 +0000398 /// Set to true when all global value body linking is complete (including
399 /// lazy linking). Used to prevent metadata linking from creating new
400 /// references.
401 bool DoneLinkingBodies = false;
402
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000403 /// The Error encountered during materialization. We use an Optional here to
404 /// avoid needing to manage an unconsumed success value.
405 Optional<Error> FoundError;
406 void setError(Error E) {
407 if (E)
408 FoundError = std::move(E);
409 }
410
411 /// Most of the errors produced by this module are inconvertible StringErrors.
412 /// This convenience function lets us return one of those more easily.
413 Error stringErr(const Twine &T) {
414 return make_error<StringError>(T, inconvertibleErrorCode());
415 }
Rafael Espindolacaabe222015-12-10 14:19:35 +0000416
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000417 /// Entry point for mapping values and alternate context for mapping aliases.
418 ValueMapper Mapper;
419 unsigned AliasMCID;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000420
Rafael Espindolacaabe222015-12-10 14:19:35 +0000421 /// Handles cloning of a global values from the source module into
422 /// the destination module, including setting the attributes and visibility.
423 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
424
Rafael Espindolacaabe222015-12-10 14:19:35 +0000425 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000426 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000427 }
428
429 /// Given a global in the source module, return the global in the
430 /// destination module that is being linked to, if any.
431 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
432 // If the source has no name it can't link. If it has local linkage,
433 // there is no name match-up going on.
434 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
435 return nullptr;
436
437 // Otherwise see if we have a match in the destination module's symtab.
438 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
439 if (!DGV)
440 return nullptr;
441
442 // If we found a global with the same name in the dest module, but it has
443 // internal linkage, we are really not doing any linkage here.
444 if (DGV->hasLocalLinkage())
445 return nullptr;
446
447 // Otherwise, we do in fact link to the destination global.
448 return DGV;
449 }
450
451 void computeTypeMapping();
452
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000453 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
454 const GlobalVariable *SrcGV);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000455
Mehdi Amini33661072016-03-11 22:19:06 +0000456 /// Given the GlobaValue \p SGV in the source module, and the matching
457 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
458 /// into the destination module.
459 ///
460 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000461 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000462 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000463
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000464 Error linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000465
466 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000467 Error linkFunctionBody(Function &Dst, Function &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000468 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000469 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000470
471 /// Functions that take care of cloning a specific global value type
472 /// into the destination module.
473 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
474 Function *copyFunctionProto(const Function *SF);
475 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
476
477 void linkNamedMDNodes();
478
479public:
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000480 IRLinker(Module &DstM, MDMapT &SharedMDs,
481 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
482 ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000483 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
Rafael Espindola40358fb2016-02-16 18:50:12 +0000484 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set),
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000485 GValMaterializer(*this), LValMaterializer(*this), SharedMDs(SharedMDs),
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000486 Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
487 &GValMaterializer),
488 AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
489 &LValMaterializer)) {
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000490 ValueMap.getMDMap() = std::move(SharedMDs);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000491 for (GlobalValue *GV : ValuesToLink)
492 maybeAdd(GV);
Teresa Johnsoncc428572015-12-30 19:32:24 +0000493 }
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000494 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Teresa Johnsoncc428572015-12-30 19:32:24 +0000495
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000496 Error run();
Mehdi Amini53a66722016-05-25 21:01:51 +0000497 Value *materialize(Value *V, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000498};
499}
500
501/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
502/// table. This is good for all clients except for us. Go through the trouble
503/// to force this back.
504static void forceRenaming(GlobalValue *GV, StringRef Name) {
505 // If the global doesn't force its name or if it already has the right name,
506 // there is nothing for us to do.
507 if (GV->hasLocalLinkage() || GV->getName() == Name)
508 return;
509
510 Module *M = GV->getParent();
511
512 // If there is a conflict, rename the conflict.
513 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
514 GV->takeName(ConflictGV);
515 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
516 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
517 } else {
518 GV->setName(Name); // Force the name back
519 }
520}
521
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000522Value *GlobalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000523 return TheIRLinker.materialize(SGV, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000524}
525
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000526Value *LocalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000527 return TheIRLinker.materialize(SGV, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000528}
529
Mehdi Amini53a66722016-05-25 21:01:51 +0000530Value *IRLinker::materialize(Value *V, bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000531 auto *SGV = dyn_cast<GlobalValue>(V);
532 if (!SGV)
533 return nullptr;
534
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000535 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
536 if (!NewProto) {
537 setError(NewProto.takeError());
538 return nullptr;
539 }
540 if (!*NewProto)
541 return nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000542
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000543 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
Mehdi Amini53a66722016-05-25 21:01:51 +0000544 if (!New)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000545 return *NewProto;
Mehdi Amini53a66722016-05-25 21:01:51 +0000546
Rafael Espindolacaabe222015-12-10 14:19:35 +0000547 // If we already created the body, just return.
548 if (auto *F = dyn_cast<Function>(New)) {
549 if (!F->isDeclaration())
Mehdi Amini53a66722016-05-25 21:01:51 +0000550 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000551 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000552 if (V->hasInitializer() || V->hasAppendingLinkage())
Mehdi Amini53a66722016-05-25 21:01:51 +0000553 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000554 } else {
555 auto *A = cast<GlobalAlias>(New);
556 if (A->getAliasee())
Mehdi Amini53a66722016-05-25 21:01:51 +0000557 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000558 }
559
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000560 // When linking a global for an alias, it will always be linked. However we
561 // need to check if it was not already scheduled to satify a reference from a
562 // regular global value initializer. We know if it has been schedule if the
563 // "New" GlobalValue that is mapped here for the alias is the same as the one
564 // already mapped. If there is an entry in the ValueMap but the value is
565 // different, it means that the value already had a definition in the
566 // destination module (linkonce for instance), but we need a new definition
567 // for the alias ("New" will be different.
Mehdi Amini53a66722016-05-25 21:01:51 +0000568 if (ForAlias && ValueMap.lookup(SGV) == New)
569 return New;
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000570
Mehdi Amini53a66722016-05-25 21:01:51 +0000571 if (ForAlias || shouldLink(New, *SGV))
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000572 setError(linkGlobalValueBody(*New, *SGV));
Mehdi Amini53a66722016-05-25 21:01:51 +0000573
574 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000575}
576
577/// Loop through the global variables in the src module and merge them into the
578/// dest module.
579GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
580 // No linking to be performed or linking from the source: simply create an
581 // identical version of the symbol over in the dest module... the
582 // initializer will be filled in later by LinkGlobalInits.
583 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000584 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000585 SGVar->isConstant(), GlobalValue::ExternalLinkage,
586 /*init*/ nullptr, SGVar->getName(),
587 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
588 SGVar->getType()->getAddressSpace());
589 NewDGV->setAlignment(SGVar->getAlignment());
590 return NewDGV;
591}
592
593/// Link the function in the source module into the destination module if
594/// needed, setting up mapping information.
595Function *IRLinker::copyFunctionProto(const Function *SF) {
596 // If there is no linkage to be performed or we are linking from the source,
597 // bring SF over.
598 return Function::Create(TypeMap.get(SF->getFunctionType()),
599 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
600}
601
602/// Set up prototypes for any aliases that come over from the source module.
603GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
604 // If there is no linkage to be performed or we're linking from the source,
605 // bring over SGA.
606 auto *Ty = TypeMap.get(SGA->getValueType());
607 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
608 GlobalValue::ExternalLinkage, SGA->getName(),
609 &DstM);
610}
611
612GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
613 bool ForDefinition) {
614 GlobalValue *NewGV;
615 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
616 NewGV = copyGlobalVariableProto(SGVar);
617 } else if (auto *SF = dyn_cast<Function>(SGV)) {
618 NewGV = copyFunctionProto(SF);
619 } else {
620 if (ForDefinition)
621 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
622 else
623 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000624 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000625 /*isConstant*/ false, GlobalValue::ExternalLinkage,
626 /*init*/ nullptr, SGV->getName(),
627 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
628 SGV->getType()->getAddressSpace());
629 }
630
631 if (ForDefinition)
632 NewGV->setLinkage(SGV->getLinkage());
Mehdi Amini113adde2016-04-19 16:11:05 +0000633 else if (SGV->hasExternalWeakLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000634 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
635
636 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000637
Reid Klecknerc0a03632016-05-25 18:36:22 +0000638 // Don't copy the comdat, it's from the original module. We'll handle it
639 // later.
640 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV))
641 NewGO->setComdat(nullptr);
642
Teresa Johnson5fe40052016-01-12 00:24:24 +0000643 // Remove these copied constants in case this stays a declaration, since
644 // they point to the source module. If the def is linked the values will
645 // be mapped in during linkFunctionBody.
646 if (auto *NewF = dyn_cast<Function>(NewGV)) {
647 NewF->setPersonalityFn(nullptr);
648 NewF->setPrefixData(nullptr);
649 NewF->setPrologueData(nullptr);
650 }
651
Rafael Espindolacaabe222015-12-10 14:19:35 +0000652 return NewGV;
653}
654
655/// Loop over all of the linked values to compute type mappings. For example,
656/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
657/// types 'Foo' but one got renamed when the module was loaded into the same
658/// LLVMContext.
659void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000660 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000661 GlobalValue *DGV = getLinkedToGlobal(&SGV);
662 if (!DGV)
663 continue;
664
665 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
666 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
667 continue;
668 }
669
670 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000671 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
672 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000673 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
674 }
675
Rafael Espindola40358fb2016-02-16 18:50:12 +0000676 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000677 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
678 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
679
Rafael Espindola40358fb2016-02-16 18:50:12 +0000680 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000681 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
682 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
683
684 // Incorporate types by name, scanning all the types in the source module.
685 // At this point, the destination module may have a type "%foo = { i32 }" for
686 // example. When the source module got loaded into the same LLVMContext, if
687 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000688 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000689 for (StructType *ST : Types) {
690 if (!ST->hasName())
691 continue;
692
693 // Check to see if there is a dot in the name followed by a digit.
694 size_t DotPos = ST->getName().rfind('.');
695 if (DotPos == 0 || DotPos == StringRef::npos ||
696 ST->getName().back() == '.' ||
697 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
698 continue;
699
700 // Check to see if the destination module has a struct with the prefix name.
701 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
702 if (!DST)
703 continue;
704
705 // Don't use it if this actually came from the source module. They're in
706 // the same LLVMContext after all. Also don't use it unless the type is
707 // actually used in the destination module. This can happen in situations
708 // like this:
709 //
710 // Module A Module B
711 // -------- --------
712 // %Z = type { %A } %B = type { %C.1 }
713 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
714 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
715 // %C = type { i8* } %B.3 = type { %C.1 }
716 //
717 // When we link Module B with Module A, the '%B' in Module B is
718 // used. However, that would then use '%C.1'. But when we process '%C.1',
719 // we prefer to take the '%C' version. So we are then left with both
720 // '%C.1' and '%C' being used for the same types. This leads to some
721 // variables using one type and some using the other.
722 if (TypeMap.DstStructTypesSet.hasType(DST))
723 TypeMap.addTypeMapping(DST, ST);
724 }
725
726 // Now that we have discovered all of the type equivalences, get a body for
727 // any 'opaque' types in the dest module that are now resolved.
728 TypeMap.linkDefinedTypeBodies();
729}
730
731static void getArrayElements(const Constant *C,
732 SmallVectorImpl<Constant *> &Dest) {
733 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
734
735 for (unsigned i = 0; i != NumElements; ++i)
736 Dest.push_back(C->getAggregateElement(i));
737}
738
739/// If there were any appending global variables, link them together now.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000740Expected<Constant *>
741IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
742 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000743 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000744 ->getElementType();
745
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000746 // FIXME: This upgrade is done during linking to support the C API. Once the
747 // old form is deprecated, we should move this upgrade to
748 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
749 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000750 StringRef Name = SrcGV->getName();
751 bool IsNewStructor = false;
752 bool IsOldStructor = false;
753 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
754 if (cast<StructType>(EltTy)->getNumElements() == 3)
755 IsNewStructor = true;
756 else
757 IsOldStructor = true;
758 }
759
760 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
761 if (IsOldStructor) {
762 auto &ST = *cast<StructType>(EltTy);
763 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
764 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
765 }
766
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000767 uint64_t DstNumElements = 0;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000768 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000769 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000770 DstNumElements = DstTy->getNumElements();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000771
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000772 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
773 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000774 "Linking globals named '" + SrcGV->getName() +
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000775 "': can only link appending global with another appending "
776 "global!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000777
778 // Check to see that they two arrays agree on type.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000779 if (EltTy != DstTy->getElementType())
780 return stringErr("Appending variables with different element types!");
781 if (DstGV->isConstant() != SrcGV->isConstant())
782 return stringErr("Appending variables linked with different const'ness!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000783
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000784 if (DstGV->getAlignment() != SrcGV->getAlignment())
785 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000786 "Appending variables with different alignment need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000787
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000788 if (DstGV->getVisibility() != SrcGV->getVisibility())
789 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000790 "Appending variables with different visibility need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000791
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000792 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
793 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000794 "Appending variables with different unnamed_addr need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000795
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000796 if (DstGV->getSection() != SrcGV->getSection())
797 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000798 "Appending variables with different section name need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000799 }
800
Rafael Espindolacaabe222015-12-10 14:19:35 +0000801 SmallVector<Constant *, 16> SrcElements;
802 getArrayElements(SrcGV->getInitializer(), SrcElements);
803
804 if (IsNewStructor)
805 SrcElements.erase(
806 std::remove_if(SrcElements.begin(), SrcElements.end(),
807 [this](Constant *E) {
808 auto *Key = dyn_cast<GlobalValue>(
809 E->getAggregateElement(2)->stripPointerCasts());
810 if (!Key)
811 return false;
812 GlobalValue *DGV = getLinkedToGlobal(Key);
813 return !shouldLink(DGV, *Key);
814 }),
815 SrcElements.end());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000816 uint64_t NewSize = DstNumElements + SrcElements.size();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000817 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
818
819 // Create the new global variable.
820 GlobalVariable *NG = new GlobalVariable(
821 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
822 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
823 SrcGV->getType()->getAddressSpace());
824
825 NG->copyAttributesFrom(SrcGV);
826 forceRenaming(NG, SrcGV->getName());
827
828 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
829
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000830 Mapper.scheduleMapAppendingVariable(*NG,
831 DstGV ? DstGV->getInitializer() : nullptr,
832 IsOldStructor, SrcElements);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000833
834 // Replace any uses of the two global variables with uses of the new
835 // global.
836 if (DstGV) {
837 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
838 DstGV->eraseFromParent();
839 }
840
841 return Ret;
842}
843
Rafael Espindolacaabe222015-12-10 14:19:35 +0000844bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
845 if (ValuesToLink.count(&SGV))
846 return true;
847
848 if (SGV.hasLocalLinkage())
849 return true;
850
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000851 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000852 return false;
853
854 if (SGV.hasAvailableExternallyLinkage())
855 return true;
856
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000857 if (SGV.isDeclaration())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000858 return false;
859
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000860 if (DoneLinkingBodies)
861 return false;
Mehdi Amini33661072016-03-11 22:19:06 +0000862
863 // Callback to the client to give a chance to lazily add the Global to the
864 // list of value to link.
865 bool LazilyAdded = false;
866 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
867 maybeAdd(&GV);
868 LazilyAdded = true;
869 });
870 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000871}
872
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000873Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
874 bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000875 GlobalValue *DGV = getLinkedToGlobal(SGV);
876
877 bool ShouldLink = shouldLink(DGV, *SGV);
878
879 // just missing from map
880 if (ShouldLink) {
881 auto I = ValueMap.find(SGV);
882 if (I != ValueMap.end())
883 return cast<Constant>(I->second);
884
885 I = AliasValueMap.find(SGV);
886 if (I != AliasValueMap.end())
887 return cast<Constant>(I->second);
888 }
889
Mehdi Amini33661072016-03-11 22:19:06 +0000890 if (!ShouldLink && ForAlias)
891 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000892
893 // Handle the ultra special appending linkage case first.
894 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
895 if (SGV->hasAppendingLinkage())
896 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
897 cast<GlobalVariable>(SGV));
898
899 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000900 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000901 NewGV = DGV;
902 } else {
903 // If we are done linking global value bodies (i.e. we are performing
904 // metadata linking), don't link in the global value due to this
905 // reference, simply map it to null.
906 if (DoneLinkingBodies)
907 return nullptr;
908
909 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +0000910 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000911 forceRenaming(NewGV, SGV->getName());
912 }
913 if (ShouldLink || ForAlias) {
914 if (const Comdat *SC = SGV->getComdat()) {
915 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
916 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
917 DC->setSelectionKind(SC->getSelectionKind());
918 GO->setComdat(DC);
919 }
920 }
921 }
922
923 if (!ShouldLink && ForAlias)
924 NewGV->setLinkage(GlobalValue::InternalLinkage);
925
926 Constant *C = NewGV;
927 if (DGV)
928 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
929
930 if (DGV && NewGV != DGV) {
931 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
932 DGV->eraseFromParent();
933 }
934
935 return C;
936}
937
938/// Update the initializers in the Dest module now that all globals that may be
939/// referenced are in Dest.
940void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
941 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000942 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000943}
944
945/// Copy the source function over into the dest function and fix up references
946/// to values. At this point we know that Dest is an external function, and
947/// that Src is not.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000948Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000949 assert(Dst.isDeclaration() && !Src.isDeclaration());
950
951 // Materialize if needed.
952 if (std::error_code EC = Src.materialize())
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000953 return errorCodeToError(EC);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000954
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000955 // Link in the operands without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000956 if (Src.hasPrefixData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000957 Dst.setPrefixData(Src.getPrefixData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000958 if (Src.hasPrologueData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000959 Dst.setPrologueData(Src.getPrologueData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000960 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000961 Dst.setPersonalityFn(Src.getPersonalityFn());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000962
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000963 // Copy over the metadata attachments without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000964 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
965 Src.getAllMetadata(MDs);
966 for (const auto &I : MDs)
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000967 Dst.setMetadata(I.first, I.second);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000968
Duncan P. N. Exon Smithbdfc9842016-04-06 06:38:15 +0000969 // Steal arguments and splice the body of Src into Dst.
970 Dst.stealArgumentListFrom(Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000971 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
972
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000973 // Everything has been moved over. Remap it.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000974 Mapper.scheduleRemapFunction(Dst);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000975 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000976}
977
978void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000979 Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000980}
981
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000982Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000983 if (auto *F = dyn_cast<Function>(&Src))
984 return linkFunctionBody(cast<Function>(Dst), *F);
985 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
986 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000987 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000988 }
989 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000990 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000991}
992
993/// Insert all of the named MDNodes in Src into the Dest module.
994void IRLinker::linkNamedMDNodes() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000995 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
996 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000997 // Don't link module flags here. Do them separately.
998 if (&NMD == SrcModFlags)
999 continue;
1000 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1001 // Add Src elements into Dest node.
Duncan P. N. Exon Smith8a15dab2016-04-15 23:32:44 +00001002 for (const MDNode *Op : NMD.operands())
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001003 DestNMD->addOperand(Mapper.mapMDNode(*Op));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001004 }
1005}
1006
1007/// Merge the linker flags in Src into the Dest module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001008Error IRLinker::linkModuleFlagsMetadata() {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001009 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001010 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001011 if (!SrcModFlags)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001012 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001013
1014 // If the destination module doesn't have module flags yet, then just copy
1015 // over the source module's flags.
1016 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1017 if (DstModFlags->getNumOperands() == 0) {
1018 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1019 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1020
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001021 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001022 }
1023
1024 // First build a map of the existing module flags and requirements.
1025 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1026 SmallSetVector<MDNode *, 16> Requirements;
1027 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1028 MDNode *Op = DstModFlags->getOperand(I);
1029 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1030 MDString *ID = cast<MDString>(Op->getOperand(1));
1031
1032 if (Behavior->getZExtValue() == Module::Require) {
1033 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1034 } else {
1035 Flags[ID] = std::make_pair(Op, I);
1036 }
1037 }
1038
1039 // Merge in the flags from the source module, and also collect its set of
1040 // requirements.
1041 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1042 MDNode *SrcOp = SrcModFlags->getOperand(I);
1043 ConstantInt *SrcBehavior =
1044 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1045 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1046 MDNode *DstOp;
1047 unsigned DstIndex;
1048 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1049 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1050
1051 // If this is a requirement, add it and continue.
1052 if (SrcBehaviorValue == Module::Require) {
1053 // If the destination module does not already have this requirement, add
1054 // it.
1055 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1056 DstModFlags->addOperand(SrcOp);
1057 }
1058 continue;
1059 }
1060
1061 // If there is no existing flag with this ID, just add it.
1062 if (!DstOp) {
1063 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1064 DstModFlags->addOperand(SrcOp);
1065 continue;
1066 }
1067
1068 // Otherwise, perform a merge.
1069 ConstantInt *DstBehavior =
1070 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1071 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1072
1073 // If either flag has override behavior, handle it first.
1074 if (DstBehaviorValue == Module::Override) {
1075 // Diagnose inconsistent flags which both have override behavior.
1076 if (SrcBehaviorValue == Module::Override &&
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001077 SrcOp->getOperand(2) != DstOp->getOperand(2))
1078 return stringErr("linking module flags '" + ID->getString() +
1079 "': IDs have conflicting override values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001080 continue;
1081 } else if (SrcBehaviorValue == Module::Override) {
1082 // Update the destination flag to that of the source.
1083 DstModFlags->setOperand(DstIndex, SrcOp);
1084 Flags[ID].first = SrcOp;
1085 continue;
1086 }
1087
1088 // Diagnose inconsistent merge behavior types.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001089 if (SrcBehaviorValue != DstBehaviorValue)
1090 return stringErr("linking module flags '" + ID->getString() +
1091 "': IDs have conflicting behaviors");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001092
1093 auto replaceDstValue = [&](MDNode *New) {
1094 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1095 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1096 DstModFlags->setOperand(DstIndex, Flag);
1097 Flags[ID].first = Flag;
1098 };
1099
1100 // Perform the merge for standard behavior types.
1101 switch (SrcBehaviorValue) {
1102 case Module::Require:
1103 case Module::Override:
1104 llvm_unreachable("not possible");
1105 case Module::Error: {
1106 // Emit an error if the values differ.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001107 if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1108 return stringErr("linking module flags '" + ID->getString() +
1109 "': IDs have conflicting values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001110 continue;
1111 }
1112 case Module::Warning: {
1113 // Emit a warning if the values differ.
1114 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1115 emitWarning("linking module flags '" + ID->getString() +
1116 "': IDs have conflicting values");
1117 }
1118 continue;
1119 }
1120 case Module::Append: {
1121 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1122 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1123 SmallVector<Metadata *, 8> MDs;
1124 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1125 MDs.append(DstValue->op_begin(), DstValue->op_end());
1126 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1127
1128 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1129 break;
1130 }
1131 case Module::AppendUnique: {
1132 SmallSetVector<Metadata *, 16> Elts;
1133 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1134 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1135 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1136 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1137
1138 replaceDstValue(MDNode::get(DstM.getContext(),
1139 makeArrayRef(Elts.begin(), Elts.end())));
1140 break;
1141 }
1142 }
1143 }
1144
1145 // Check all of the requirements.
1146 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1147 MDNode *Requirement = Requirements[I];
1148 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1149 Metadata *ReqValue = Requirement->getOperand(1);
1150
1151 MDNode *Op = Flags[Flag].first;
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001152 if (!Op || Op->getOperand(2) != ReqValue)
1153 return stringErr("linking module flags '" + Flag->getString() +
1154 "': does not have the required value");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001155 }
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001156 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001157}
1158
1159// This function returns true if the triples match.
1160static bool triplesMatch(const Triple &T0, const Triple &T1) {
1161 // If vendor is apple, ignore the version number.
1162 if (T0.getVendor() == Triple::Apple)
1163 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1164 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1165
1166 return T0 == T1;
1167}
1168
1169// This function returns the merged triple.
1170static std::string mergeTriples(const Triple &SrcTriple,
1171 const Triple &DstTriple) {
1172 // If vendor is apple, pick the triple with the larger version number.
1173 if (SrcTriple.getVendor() == Triple::Apple)
1174 if (DstTriple.isOSVersionLT(SrcTriple))
1175 return SrcTriple.str();
1176
1177 return DstTriple.str();
1178}
1179
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001180Error IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001181 // Ensure metadata materialized before value mapping.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001182 if (SrcM->getMaterializer())
1183 if (std::error_code EC = SrcM->getMaterializer()->materializeMetadata())
1184 return errorCodeToError(EC);
Teresa Johnson0556e222016-03-10 18:47:03 +00001185
Rafael Espindolacaabe222015-12-10 14:19:35 +00001186 // Inherit the target data from the source module if the destination module
1187 // doesn't have one already.
1188 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001189 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001190
Rafael Espindola40358fb2016-02-16 18:50:12 +00001191 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001192 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001193 SrcM->getModuleIdentifier() + "' is '" +
1194 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001195 DstM.getModuleIdentifier() + "' is '" +
1196 DstM.getDataLayoutStr() + "'\n");
1197 }
1198
1199 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001200 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1201 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001202
Rafael Espindola40358fb2016-02-16 18:50:12 +00001203 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001204
Rafael Espindola40358fb2016-02-16 18:50:12 +00001205 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001206 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001207 SrcM->getModuleIdentifier() + "' is '" +
1208 SrcM->getTargetTriple() + "' whereas '" +
1209 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1210 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001211
1212 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1213
1214 // Append the module inline asm string.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001215 if (!SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001216 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001217 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001218 else
1219 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001220 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001221 }
1222
1223 // Loop over all of the linked values to compute type mappings.
1224 computeTypeMapping();
1225
1226 std::reverse(Worklist.begin(), Worklist.end());
1227 while (!Worklist.empty()) {
1228 GlobalValue *GV = Worklist.back();
1229 Worklist.pop_back();
1230
1231 // Already mapped.
1232 if (ValueMap.find(GV) != ValueMap.end() ||
1233 AliasValueMap.find(GV) != AliasValueMap.end())
1234 continue;
1235
1236 assert(!GV->isDeclaration());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001237 Mapper.mapValue(*GV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001238 if (FoundError)
1239 return std::move(*FoundError);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001240 }
1241
1242 // Note that we are done linking global value bodies. This prevents
1243 // metadata linking from creating new references.
1244 DoneLinkingBodies = true;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001245 Mapper.addFlags(RF_NullMapMissingGlobalValues);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001246
1247 // Remap all of the named MDNodes in Src into the DstM module. We do this
1248 // after linking GlobalValues so that MDNodes that reference GlobalValues
1249 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001250 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001251
Teresa Johnsonb703c772016-03-29 18:24:19 +00001252 // Merge the module flags into the DstM module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001253 return linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001254}
1255
1256IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1257 : ETypes(E), IsPacked(P) {}
1258
1259IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1260 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1261
1262bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1263 if (IsPacked != That.IsPacked)
1264 return false;
1265 if (ETypes != That.ETypes)
1266 return false;
1267 return true;
1268}
1269
1270bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1271 return !this->operator==(That);
1272}
1273
1274StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1275 return DenseMapInfo<StructType *>::getEmptyKey();
1276}
1277
1278StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1279 return DenseMapInfo<StructType *>::getTombstoneKey();
1280}
1281
1282unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1283 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1284 Key.IsPacked);
1285}
1286
1287unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1288 return getHashValue(KeyTy(ST));
1289}
1290
1291bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1292 const StructType *RHS) {
1293 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1294 return false;
1295 return LHS == KeyTy(RHS);
1296}
1297
1298bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1299 const StructType *RHS) {
1300 if (RHS == getEmptyKey())
1301 return LHS == getEmptyKey();
1302
1303 if (RHS == getTombstoneKey())
1304 return LHS == getTombstoneKey();
1305
1306 return KeyTy(LHS) == KeyTy(RHS);
1307}
1308
1309void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1310 assert(!Ty->isOpaque());
1311 NonOpaqueStructTypes.insert(Ty);
1312}
1313
1314void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1315 assert(!Ty->isOpaque());
1316 NonOpaqueStructTypes.insert(Ty);
1317 bool Removed = OpaqueStructTypes.erase(Ty);
1318 (void)Removed;
1319 assert(Removed);
1320}
1321
1322void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1323 assert(Ty->isOpaque());
1324 OpaqueStructTypes.insert(Ty);
1325}
1326
1327StructType *
1328IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1329 bool IsPacked) {
1330 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1331 auto I = NonOpaqueStructTypes.find_as(Key);
1332 if (I == NonOpaqueStructTypes.end())
1333 return nullptr;
1334 return *I;
1335}
1336
1337bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1338 if (Ty->isOpaque())
1339 return OpaqueStructTypes.count(Ty);
1340 auto I = NonOpaqueStructTypes.find(Ty);
1341 if (I == NonOpaqueStructTypes.end())
1342 return false;
1343 return *I == Ty;
1344}
1345
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001346IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001347 TypeFinder StructTypes;
1348 StructTypes.run(M, true);
1349 for (StructType *Ty : StructTypes) {
1350 if (Ty->isOpaque())
1351 IdentifiedStructTypes.addOpaque(Ty);
1352 else
1353 IdentifiedStructTypes.addNonOpaque(Ty);
1354 }
1355}
1356
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001357Error IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001358 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +00001359 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +00001360 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1361 std::move(Src), ValuesToLink, AddLazyFor);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001362 Error E = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001363 Composite.dropTriviallyDeadConstantArrays();
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001364 return E;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001365}