blob: a0ce497dd4732f109270ce2fa7fc66011f1a167a [file] [log] [blame]
Mikhail Glushenkov59a5afa2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Reid Spencer361e5132004-11-12 20:37:43 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
Reid Spencer361e5132004-11-12 20:37:43 +00008//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM module linker.
11//
Reid Spencer361e5132004-11-12 20:37:43 +000012//===----------------------------------------------------------------------===//
13
Reid Spencer9b0ddbb2004-11-14 23:27:04 +000014#include "llvm/Linker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Rafael Espindola23f8d642012-01-05 23:02:01 +000016#include "llvm/ADT/Optional.h"
Bill Wendling66f02412012-02-11 11:38:06 +000017#include "llvm/ADT/SetVector.h"
Eli Bendersky0f7fd362013-03-19 15:26:24 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000021#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000022#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000023#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000024#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000025#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000026#include <cctype>
Reid Spencer361e5132004-11-12 20:37:43 +000027using namespace llvm;
28
Eli Benderskye17f3702014-02-06 18:01:56 +000029
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000030//===----------------------------------------------------------------------===//
31// TypeMap implementation.
32//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000033
Chris Lattnereee6f992008-06-16 21:00:18 +000034namespace {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000035 typedef SmallPtrSet<StructType*, 32> TypeSet;
36
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000037class TypeMapTy : public ValueMapTypeRemapper {
38 /// MappedTypes - This is a mapping from a source type to a destination type
39 /// to use.
40 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000041
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000042 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
43 /// we speculatively add types to MappedTypes, but keep track of them here in
44 /// case we need to roll back.
45 SmallVector<Type*, 16> SpeculativeTypes;
46
Chris Lattner5e3bd972011-12-20 00:03:52 +000047 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
48 /// source module that are mapped to an opaque struct in the destination
49 /// module.
50 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
51
52 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
53 /// destination modules who are getting a body from the source module.
54 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000055
Chris Lattner56cdea62008-06-16 23:06:51 +000056public:
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000057 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
58
59 TypeSet &DstStructTypesSet;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000060 /// addTypeMapping - Indicate that the specified type in the destination
61 /// module is conceptually equivalent to the specified type in the source
62 /// module.
63 void addTypeMapping(Type *DstTy, Type *SrcTy);
64
65 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
66 /// module from a type definition in the source module.
67 void linkDefinedTypeBodies();
68
69 /// get - Return the mapped type to use for the specified input type from the
70 /// source module.
71 Type *get(Type *SrcTy);
72
73 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
74
Bill Wendlingb6af2f32012-03-22 20:28:27 +000075 /// dump - Dump out the type map for debugging purposes.
76 void dump() const {
77 for (DenseMap<Type*, Type*>::const_iterator
78 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
79 dbgs() << "TypeMap: ";
80 I->first->dump();
81 dbgs() << " => ";
82 I->second->dump();
83 dbgs() << '\n';
84 }
85 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000086
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000087private:
88 Type *getImpl(Type *T);
89 /// remapType - Implement the ValueMapTypeRemapper interface.
Craig Topper85482992014-03-05 07:52:44 +000090 Type *remapType(Type *SrcTy) override {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000091 return get(SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000092 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000093
94 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000095};
96}
97
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000098void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
99 Type *&Entry = MappedTypes[SrcTy];
100 if (Entry) return;
101
102 if (DstTy == SrcTy) {
103 Entry = DstTy;
104 return;
105 }
Bill Wendlingd48b7782012-02-28 04:01:21 +0000106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000107 // Check to see if these types are recursively isomorphic and establish a
108 // mapping between them if so.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000109 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000110 // Oops, they aren't isomorphic. Just discard this request by rolling out
111 // any speculative mappings we've established.
112 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
113 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendlingd48b7782012-02-28 04:01:21 +0000114 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000115 SpeculativeTypes.clear();
116}
Chris Lattnereee6f992008-06-16 21:00:18 +0000117
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000118/// areTypesIsomorphic - Recursively walk this pair of types, returning true
119/// if they are isomorphic, false if they are not.
120bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
121 // Two types with differing kinds are clearly not isomorphic.
122 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000124 // If we have an entry in the MappedTypes table, then we have our answer.
125 Type *&Entry = MappedTypes[SrcTy];
126 if (Entry)
127 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000129 // Two identical types are clearly isomorphic. Remember this
130 // non-speculatively.
131 if (DstTy == SrcTy) {
132 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000133 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000134 }
Bill Wendlingd48b7782012-02-28 04:01:21 +0000135
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000136 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000137
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000138 // If this is an opaque struct type, special case it.
139 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
140 // Mapping an opaque type to any struct, just keep the dest struct.
141 if (SSTy->isOpaque()) {
142 Entry = DstTy;
143 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000144 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000145 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000146
Chris Lattner5e3bd972011-12-20 00:03:52 +0000147 // Mapping a non-opaque source type to an opaque dest. If this is the first
148 // type that we're mapping onto this destination type then we succeed. Keep
149 // the dest, but fill it in later. This doesn't need to be speculative. If
150 // this is the second (different) type that we're trying to map onto the
151 // same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000152 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000153 // We can only map one source type onto the opaque destination type.
154 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
155 return false;
156 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000157 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000158 return true;
159 }
160 }
161
162 // If the number of subtypes disagree between the two types, then we fail.
163 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000164 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000165
166 // Fail if any of the extra properties (e.g. array size) of the type disagree.
167 if (isa<IntegerType>(DstTy))
168 return false; // bitwidth disagrees.
169 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
170 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
171 return false;
Chris Lattnereaf9b762011-12-20 23:14:57 +0000172
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000173 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
174 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
175 return false;
176 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
177 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000178 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000179 DSTy->isPacked() != SSTy->isPacked())
180 return false;
181 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
182 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
183 return false;
184 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000185 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000186 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000187 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000188
189 // Otherwise, we speculate that these two types will line up and recursively
190 // check the subelements.
191 Entry = DstTy;
192 SpeculativeTypes.push_back(SrcTy);
193
Bill Wendlingd48b7782012-02-28 04:01:21 +0000194 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
195 if (!areTypesIsomorphic(DstTy->getContainedType(i),
196 SrcTy->getContainedType(i)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000197 return false;
198
199 // If everything seems to have lined up, then everything is great.
200 return true;
201}
202
203/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
204/// module from a type definition in the source module.
205void TypeMapTy::linkDefinedTypeBodies() {
206 SmallVector<Type*, 16> Elements;
207 SmallString<16> TmpName;
208
209 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner5e3bd972011-12-20 00:03:52 +0000210 // entries to the SrcDefinitionsToResolve vector.
211 while (!SrcDefinitionsToResolve.empty()) {
212 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000213 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
214
215 // TypeMap is a many-to-one mapping, if there were multiple types that
216 // provide a body for DstSTy then previous iterations of this loop may have
217 // already handled it. Just ignore this case.
218 if (!DstSTy->isOpaque()) continue;
219 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
220
221 // Map the body of the source type over to a new body for the dest type.
222 Elements.resize(SrcSTy->getNumElements());
223 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
224 Elements[i] = getImpl(SrcSTy->getElementType(i));
225
226 DstSTy->setBody(Elements, SrcSTy->isPacked());
227
228 // If DstSTy has no name or has a longer name than STy, then viciously steal
229 // STy's name.
230 if (!SrcSTy->hasName()) continue;
231 StringRef SrcName = SrcSTy->getName();
232
233 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
234 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
235 SrcSTy->setName("");
236 DstSTy->setName(TmpName.str());
237 TmpName.clear();
238 }
239 }
Chris Lattner5e3bd972011-12-20 00:03:52 +0000240
241 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000242}
243
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000244/// get - Return the mapped type to use for the specified input type from the
245/// source module.
246Type *TypeMapTy::get(Type *Ty) {
247 Type *Result = getImpl(Ty);
248
249 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000250 if (!SrcDefinitionsToResolve.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000251 linkDefinedTypeBodies();
252 return Result;
253}
254
255/// getImpl - This is the recursive version of get().
256Type *TypeMapTy::getImpl(Type *Ty) {
257 // If we already have an entry for this type, return it.
258 Type **Entry = &MappedTypes[Ty];
259 if (*Entry) return *Entry;
Bill Wendlingd48b7782012-02-28 04:01:21 +0000260
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000261 // If this is not a named struct type, then just map all of the elements and
262 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000263 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000264 // If there are no element types to map, then the type is itself. This is
265 // true for the anonymous {} struct, things like 'float', integers, etc.
266 if (Ty->getNumContainedTypes() == 0)
267 return *Entry = Ty;
268
269 // Remap all of the elements, keeping track of whether any of them change.
270 bool AnyChange = false;
271 SmallVector<Type*, 4> ElementTypes;
272 ElementTypes.resize(Ty->getNumContainedTypes());
273 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
274 ElementTypes[i] = getImpl(Ty->getContainedType(i));
275 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
276 }
277
278 // If we found our type while recursively processing stuff, just use it.
279 Entry = &MappedTypes[Ty];
280 if (*Entry) return *Entry;
281
282 // If all of the element types mapped directly over, then the type is usable
283 // as-is.
284 if (!AnyChange)
285 return *Entry = Ty;
286
287 // Otherwise, rebuild a modified type.
288 switch (Ty->getTypeID()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000289 default: llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000290 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],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000301 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000302 cast<FunctionType>(Ty)->isVarArg());
303 case Type::StructTyID:
304 // Note that this is only reached for anonymous structs.
305 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
306 cast<StructType>(Ty)->isPacked());
307 }
308 }
309
310 // Otherwise, this is an unmapped named struct. If the struct can be directly
311 // mapped over, just use it as-is. This happens in a case when the linked-in
312 // module has something like:
313 // %T = type {%T*, i32}
314 // @GV = global %T* null
315 // where T does not exist at all in the destination module.
316 //
317 // The other case we watch for is when the type is not in the destination
318 // module, but that it has to be rebuilt because it refers to something that
319 // is already mapped. For example, if the destination module has:
320 // %A = type { i32 }
321 // and the source module has something like
322 // %A' = type { i32 }
323 // %B = type { %A'* }
324 // @GV = global %B* null
325 // then we want to create a new type: "%B = type { %A*}" and have it take the
326 // pristine "%B" name from the source module.
327 //
328 // To determine which case this is, we have to recursively walk the type graph
329 // speculating that we'll be able to reuse it unmodified. Only if this is
330 // safe would we map the entire thing over. Because this is an optimization,
331 // and is not required for the prettiness of the linked module, we just skip
332 // it and always rebuild a type here.
333 StructType *STy = cast<StructType>(Ty);
334
335 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000336 if (STy->isOpaque()) {
337 // A named structure type from src module is used. Add it to the Set of
338 // identified structs in the destination module.
339 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000340 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000341 }
Bill Wendlingd48b7782012-02-28 04:01:21 +0000342
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000343 // Otherwise we create a new type and resolve its body later. This will be
344 // resolved by the top level of get().
Chris Lattner5e3bd972011-12-20 00:03:52 +0000345 SrcDefinitionsToResolve.push_back(STy);
346 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000347 // A new identified structure type was created. Add it to the set of
348 // identified structs in the destination module.
349 DstStructTypesSet.insert(DTy);
Chris Lattner5e3bd972011-12-20 00:03:52 +0000350 DstResolvedOpaqueTypes.insert(DTy);
351 return *Entry = DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000352}
353
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000354//===----------------------------------------------------------------------===//
355// ModuleLinker implementation.
356//===----------------------------------------------------------------------===//
357
358namespace {
James Molloyf6f121e2013-05-28 15:17:05 +0000359 class ModuleLinker;
360
361 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
362 /// linked on the fly. This speeds up linking for modules with many
363 /// lazily linked functions of which few get used.
364 class ValueMaterializerTy : public ValueMaterializer {
365 TypeMapTy &TypeMap;
366 Module *DstM;
367 std::vector<Function*> &LazilyLinkFunctions;
368 public:
369 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
370 std::vector<Function*> &LazilyLinkFunctions) :
371 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
372 LazilyLinkFunctions(LazilyLinkFunctions) {
373 }
374
Craig Topper85482992014-03-05 07:52:44 +0000375 Value *materializeValueFor(Value *V) override;
James Molloyf6f121e2013-05-28 15:17:05 +0000376 };
377
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000378 /// ModuleLinker - This is an implementation class for the LinkModules
379 /// function, which is the entrypoint for this file.
380 class ModuleLinker {
381 Module *DstM, *SrcM;
382
383 TypeMapTy TypeMap;
James Molloyf6f121e2013-05-28 15:17:05 +0000384 ValueMaterializerTy ValMaterializer;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000385
386 /// ValueMap - Mapping of values from what they used to be in Src, to what
387 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
388 /// some overhead due to the use of Value handles which the Linker doesn't
389 /// actually need, but this allows us to reuse the ValueMapper code.
390 ValueToValueMapTy ValueMap;
391
392 struct AppendingVarInfo {
393 GlobalVariable *NewGV; // New aggregate global in dest module.
394 Constant *DstInit; // Old initializer from dest module.
395 Constant *SrcInit; // Old initializer from src module.
396 };
397
398 std::vector<AppendingVarInfo> AppendingVars;
399
Tanya Lattnercbb91402011-10-11 00:24:54 +0000400 unsigned Mode; // Mode to treat source module.
401
402 // Set of items not to link in from source.
403 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
404
Tanya Lattner0a48b872011-11-02 00:24:56 +0000405 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000406 std::vector<Function*> LazilyLinkFunctions;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000407
408 bool SuppressWarnings;
Tanya Lattner0a48b872011-11-02 00:24:56 +0000409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000410 public:
411 std::string ErrorMsg;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000412
413 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
414 bool SuppressWarnings=false)
415 : DstM(dstM), SrcM(srcM), TypeMap(Set),
416 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
417 SuppressWarnings(SuppressWarnings) {}
418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 bool run();
420
421 private:
422 /// emitError - Helper method for setting a message and returning an error
423 /// code.
424 bool emitError(const Twine &Message) {
425 ErrorMsg = Message.str();
Chris Lattner99953022008-06-16 18:27:53 +0000426 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000427 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000428
429 /// getLinkageResult - This analyzes the two global values and determines
430 /// what the result will look like in the destination module.
431 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000432 GlobalValue::LinkageTypes &LT,
433 GlobalValue::VisibilityTypes &Vis,
434 bool &LinkFromSrc);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000436 /// getLinkedToGlobal - Given a global in the source module, return the
437 /// global in the destination module that is being linked to, if any.
438 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
439 // If the source has no name it can't link. If it has local linkage,
440 // there is no name match-up going on.
441 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
442 return 0;
Bill Wendlingd48b7782012-02-28 04:01:21 +0000443
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000444 // Otherwise see if we have a match in the destination module's symtab.
445 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
446 if (DGV == 0) return 0;
Bill Wendlingd48b7782012-02-28 04:01:21 +0000447
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000448 // If we found a global with the same name in the dest module, but it has
449 // internal linkage, we are really not doing any linkage here.
450 if (DGV->hasLocalLinkage())
451 return 0;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000452
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000453 // Otherwise, we do in fact link to the destination global.
454 return DGV;
455 }
456
457 void computeTypeMapping();
458
459 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
460 bool linkGlobalProto(GlobalVariable *SrcGV);
461 bool linkFunctionProto(Function *SrcF);
462 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendling66f02412012-02-11 11:38:06 +0000463 bool linkModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000464
465 void linkAppendingVarInit(const AppendingVarInfo &AVI);
466 void linkGlobalInits();
467 void linkFunctionBody(Function *Dst, Function *Src);
468 void linkAliasBodies();
469 void linkNamedMDNodes();
470 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000471}
472
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000473/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer90246aa2007-02-04 04:29:21 +0000474/// in the symbol table. This is good for all clients except for us. Go
475/// through the trouble to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000476static void forceRenaming(GlobalValue *GV, StringRef Name) {
477 // If the global doesn't force its name or if it already has the right name,
478 // there is nothing for us to do.
479 if (GV->hasLocalLinkage() || GV->getName() == Name)
480 return;
481
482 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000483
484 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000485 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000486 GV->takeName(ConflictGV);
487 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000488 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000489 } else {
490 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000491 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000492}
Reid Spencer90246aa2007-02-04 04:29:21 +0000493
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000494/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000495/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000496static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000497 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
498 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
499 DestGV->copyAttributesFrom(SrcGV);
500 DestGV->setAlignment(Alignment);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000501
502 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000503}
504
Rafael Espindola23f8d642012-01-05 23:02:01 +0000505static bool isLessConstraining(GlobalValue::VisibilityTypes a,
506 GlobalValue::VisibilityTypes b) {
507 if (a == GlobalValue::HiddenVisibility)
508 return false;
509 if (b == GlobalValue::HiddenVisibility)
510 return true;
511 if (a == GlobalValue::ProtectedVisibility)
512 return false;
513 if (b == GlobalValue::ProtectedVisibility)
514 return true;
515 return false;
516}
517
James Molloyf6f121e2013-05-28 15:17:05 +0000518Value *ValueMaterializerTy::materializeValueFor(Value *V) {
519 Function *SF = dyn_cast<Function>(V);
520 if (!SF)
521 return NULL;
522
523 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
524 SF->getLinkage(), SF->getName(), DstM);
525 copyGVAttributes(DF, SF);
526
527 LazilyLinkFunctions.push_back(SF);
528 return DF;
529}
530
531
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000532/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattnerfc61de32004-12-03 22:18:41 +0000533/// the result will look like in the destination module. In particular, it
Rafael Espindola23f8d642012-01-05 23:02:01 +0000534/// computes the resultant linkage type and visibility, computes whether the
535/// global in the source should be copied over to the destination (replacing
536/// the existing one), and computes whether this linkage is an error or not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000537bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000538 GlobalValue::LinkageTypes &LT,
539 GlobalValue::VisibilityTypes &Vis,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000540 bool &LinkFromSrc) {
541 assert(Dest && "Must have two globals being queried");
542 assert(!Src->hasLocalLinkage() &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000543 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000544
Peter Collingbourne8bb15d82011-10-30 17:46:34 +0000545 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattner0c134b52011-07-14 20:23:05 +0000546 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000547
548 if (SrcIsDeclaration) {
Anton Korobeynikov1f93c502008-03-10 22:33:22 +0000549 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattnerfc61de32004-12-03 22:18:41 +0000550 // external globals, we aren't adding anything.
Nico Rieck7157bb72014-01-14 15:22:47 +0000551 if (Src->hasDLLImportStorageClass()) {
552 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000553 if (DestIsDeclaration) {
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000554 LinkFromSrc = true;
555 LT = Src->getLinkage();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000556 }
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000557 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands12da8ce2009-03-07 15:45:40 +0000558 // If the Dest is weak, use the source linkage.
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000559 LinkFromSrc = true;
560 LT = Src->getLinkage();
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000561 } else {
562 LinkFromSrc = false;
563 LT = Dest->getLinkage();
564 }
Nico Rieck7157bb72014-01-14 15:22:47 +0000565 } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000566 // If Dest is external but Src is not:
567 LinkFromSrc = true;
568 LT = Src->getLinkage();
Duncan Sandsd725c992009-03-08 13:35:23 +0000569 } else if (Src->isWeakForLinker()) {
Dale Johannesence4396b2008-05-14 20:12:51 +0000570 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
571 // or DLL* linkage.
Chris Lattner184f1be2009-04-13 05:44:34 +0000572 if (Dest->hasExternalWeakLinkage() ||
573 Dest->hasAvailableExternallyLinkage() ||
574 (Dest->hasLinkOnceLinkage() &&
575 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000576 LinkFromSrc = true;
577 LT = Src->getLinkage();
578 } else {
579 LinkFromSrc = false;
580 LT = Dest->getLinkage();
581 }
Duncan Sandsd725c992009-03-08 13:35:23 +0000582 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000583 // At this point we know that Src has External* or DLL* linkage.
584 if (Src->hasExternalWeakLinkage()) {
585 LinkFromSrc = false;
586 LT = Dest->getLinkage();
587 } else {
588 LinkFromSrc = true;
589 LT = GlobalValue::ExternalLinkage;
590 }
Chris Lattnerfc61de32004-12-03 22:18:41 +0000591 } else {
Nico Rieck7157bb72014-01-14 15:22:47 +0000592 assert((Dest->hasExternalLinkage() || Dest->hasExternalWeakLinkage()) &&
593 (Src->hasExternalLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000594 "Unexpected linkage type!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000595 return emitError("Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000596 "': symbol multiply defined!");
597 }
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000598
Rafael Espindola23f8d642012-01-05 23:02:01 +0000599 // Compute the visibility. We follow the rules in the System V Application
600 // Binary Interface.
601 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
602 Dest->getVisibility() : Src->getVisibility();
Chris Lattnerfc61de32004-12-03 22:18:41 +0000603 return false;
604}
Reid Spencer361e5132004-11-12 20:37:43 +0000605
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000606/// computeTypeMapping - Loop over all of the linked values to compute type
607/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
608/// we have two struct types 'Foo' but one got renamed when the module was
609/// loaded into the same LLVMContext.
610void ModuleLinker::computeTypeMapping() {
611 // Incorporate globals.
612 for (Module::global_iterator I = SrcM->global_begin(),
613 E = SrcM->global_end(); I != E; ++I) {
614 GlobalValue *DGV = getLinkedToGlobal(I);
615 if (DGV == 0) continue;
616
617 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
618 TypeMap.addTypeMapping(DGV->getType(), I->getType());
619 continue;
620 }
621
622 // Unify the element type of appending arrays.
623 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
624 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
625 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000626 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000627
628 // Incorporate functions.
629 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
630 if (GlobalValue *DGV = getLinkedToGlobal(I))
631 TypeMap.addTypeMapping(DGV->getType(), I->getType());
632 }
Bill Wendling7b464612012-02-27 22:34:19 +0000633
Bill Wendlingd48b7782012-02-28 04:01:21 +0000634 // Incorporate types by name, scanning all the types in the source module.
635 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000636 // example. When the source module got loaded into the same LLVMContext, if
637 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000638 TypeFinder SrcStructTypes;
639 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000640 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
641 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000642
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000643 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
644 StructType *ST = SrcStructTypes[i];
645 if (!ST->hasName()) continue;
646
647 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000648 size_t DotPos = ST->getName().rfind('.');
649 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000650 ST->getName().back() == '.' ||
651 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000652 continue;
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000653
654 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000655 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000656 // Don't use it if this actually came from the source module. They're in
657 // the same LLVMContext after all. Also don't use it unless the type is
658 // actually used in the destination module. This can happen in situations
659 // like this:
660 //
661 // Module A Module B
662 // -------- --------
663 // %Z = type { %A } %B = type { %C.1 }
664 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
665 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
666 // %C = type { i8* } %B.3 = type { %C.1 }
667 //
668 // When we link Module B with Module A, the '%B' in Module B is
669 // used. However, that would then use '%C.1'. But when we process '%C.1',
670 // we prefer to take the '%C' version. So we are then left with both
671 // '%C.1' and '%C' being used for the same types. This leads to some
672 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000673 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000674 TypeMap.addTypeMapping(DST, ST);
675 }
676
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000677 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000678
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000679 // Now that we have discovered all of the type equivalences, get a body for
680 // any 'opaque' types in the dest module that are now resolved.
681 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000682}
683
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000684/// linkAppendingVarProto - If there were any appending global variables, link
685/// them together now. Return true on error.
686bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
687 GlobalVariable *SrcGV) {
Bill Wendlingd48b7782012-02-28 04:01:21 +0000688
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000689 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
690 return emitError("Linking globals named '" + SrcGV->getName() +
691 "': can only link appending global with another appending global!");
692
693 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
694 ArrayType *SrcTy =
695 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
696 Type *EltTy = DstTy->getElementType();
697
698 // Check to see that they two arrays agree on type.
699 if (EltTy != SrcTy->getElementType())
700 return emitError("Appending variables with different element types!");
701 if (DstGV->isConstant() != SrcGV->isConstant())
702 return emitError("Appending variables linked with different const'ness!");
703
704 if (DstGV->getAlignment() != SrcGV->getAlignment())
705 return emitError(
706 "Appending variables with different alignment need to be linked!");
707
708 if (DstGV->getVisibility() != SrcGV->getVisibility())
709 return emitError(
710 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000711
712 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
713 return emitError(
714 "Appending variables with different unnamed_addr need to be linked!");
715
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000716 if (DstGV->getSection() != SrcGV->getSection())
717 return emitError(
718 "Appending variables with different section name need to be linked!");
719
720 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
721 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
722
723 // Create the new global variable.
724 GlobalVariable *NG =
725 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
726 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000727 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000728 DstGV->getType()->getAddressSpace());
729
730 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000731 copyGVAttributes(NG, DstGV);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000732
733 AppendingVarInfo AVI;
734 AVI.NewGV = NG;
735 AVI.DstInit = DstGV->getInitializer();
736 AVI.SrcInit = SrcGV->getInitializer();
737 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000738
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000739 // Replace any uses of the two global variables with uses of the new
740 // global.
741 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000742
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000743 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
744 DstGV->eraseFromParent();
745
Tanya Lattnercbb91402011-10-11 00:24:54 +0000746 // Track the source variable so we don't try to link it.
747 DoNotLinkFromSource.insert(SrcGV);
748
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000749 return false;
750}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000751
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000752/// linkGlobalProto - Loop through the global variables in the src module and
753/// merge them into the dest module.
754bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
755 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000756 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolad4885da2013-09-04 14:05:09 +0000757 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000758
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000759 if (DGV) {
760 // Concatenation of appending linkage variables is magic and handled later.
761 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
762 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
763
764 // Determine whether linkage of these two globals follows the source
765 // module's definition or the destination module's definition.
Chris Lattner1b9633d2006-11-09 05:18:12 +0000766 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000767 GlobalValue::VisibilityTypes NV;
Chris Lattner1b9633d2006-11-09 05:18:12 +0000768 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000769 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattnerfc61de32004-12-03 22:18:41 +0000770 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000771 NewVisibility = NV;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000772 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Reid Spencer361e5132004-11-12 20:37:43 +0000773
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000774 // If we're not linking from the source, then keep the definition that we
775 // have.
776 if (!LinkFromSrc) {
777 // Special case for const propagation.
778 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
779 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
780 DGVar->setConstant(true);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000781
782 // Set calculated linkage, visibility and unnamed_addr.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000783 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000784 DGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000785 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000786
Chris Lattner0ead7a52008-07-14 07:23:24 +0000787 // Make sure to remember this mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000788 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
789
Tanya Lattnercbb91402011-10-11 00:24:54 +0000790 // Track the source global so that we don't attempt to copy it over when
791 // processing global initializers.
792 DoNotLinkFromSource.insert(SGV);
793
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000794 return false;
Chris Lattner0ead7a52008-07-14 07:23:24 +0000795 }
Reid Spencer361e5132004-11-12 20:37:43 +0000796 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000797
798 // No linking to be performed or linking from the source: simply create an
799 // identical version of the symbol over in the dest module... the
800 // initializer will be filled in later by LinkGlobalInits.
801 GlobalVariable *NewDGV =
802 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
803 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
804 SGV->getName(), /*insertbefore*/0,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000805 SGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000806 SGV->getType()->getAddressSpace());
807 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000808 copyGVAttributes(NewDGV, SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000809 if (NewVisibility)
810 NewDGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000811 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000812
813 if (DGV) {
814 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
815 DGV->eraseFromParent();
816 }
817
818 // Make sure to remember this mapping.
819 ValueMap[SGV] = NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +0000820 return false;
821}
822
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000823/// linkFunctionProto - Link the function in the source module into the
824/// destination module if needed, setting up mapping information.
825bool ModuleLinker::linkFunctionProto(Function *SF) {
826 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000827 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000828 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000829
830 if (DGV) {
831 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
832 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000833 GlobalValue::VisibilityTypes NV;
834 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000835 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000836 NewVisibility = NV;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000837 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindola23f8d642012-01-05 23:02:01 +0000838
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000839 if (!LinkFromSrc) {
840 // Set calculated linkage
841 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000842 DGV->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000843 DGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000844
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000845 // Make sure to remember this mapping.
846 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
847
Tanya Lattnercbb91402011-10-11 00:24:54 +0000848 // Track the function from the source module so we don't attempt to remap
849 // it.
850 DoNotLinkFromSource.insert(SF);
851
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000852 return false;
853 }
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +0000854 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000855
James Molloyf6f121e2013-05-28 15:17:05 +0000856 // If the function is to be lazily linked, don't create it just yet.
857 // The ValueMaterializerTy will deal with creating it if it's used.
858 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
859 SF->hasAvailableExternallyLinkage())) {
860 DoNotLinkFromSource.insert(SF);
861 return false;
862 }
863
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000864 // If there is no linkage to be performed or we are linking from the source,
865 // bring SF over.
866 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
867 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000868 copyGVAttributes(NewDF, SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000869 if (NewVisibility)
870 NewDF->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000871 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +0000872
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000873 if (DGV) {
874 // Any uses of DF need to change to NewDF, with cast.
875 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
876 DGV->eraseFromParent();
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +0000877 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000878
879 ValueMap[SF] = NewDF;
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +0000880 return false;
881}
882
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000883/// LinkAliasProto - Set up prototypes for any aliases that come over from the
884/// source module.
885bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
886 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000887 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
888
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000889 if (DGV) {
890 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000891 GlobalValue::VisibilityTypes NV;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000892 bool LinkFromSrc = false;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000893 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000894 return true;
Rafael Espindola23f8d642012-01-05 23:02:01 +0000895 NewVisibility = NV;
896
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000897 if (!LinkFromSrc) {
898 // Set calculated linkage.
899 DGV->setLinkage(NewLinkage);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000900 DGV->setVisibility(*NewVisibility);
901
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000902 // Make sure to remember this mapping.
903 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
904
Tanya Lattnercbb91402011-10-11 00:24:54 +0000905 // Track the alias from the source module so we don't attempt to remap it.
906 DoNotLinkFromSource.insert(SGA);
907
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000908 return false;
909 }
910 }
911
912 // If there is no linkage to be performed or we're linking from the source,
913 // bring over SGA.
914 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
915 SGA->getLinkage(), SGA->getName(),
916 /*aliasee*/0, DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000917 copyGVAttributes(NewDA, SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000918 if (NewVisibility)
919 NewDA->setVisibility(*NewVisibility);
Reid Spencer361e5132004-11-12 20:37:43 +0000920
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000921 if (DGV) {
922 // Any uses of DGV need to change to NewDA, with cast.
923 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
924 DGV->eraseFromParent();
925 }
926
927 ValueMap[SGA] = NewDA;
928 return false;
929}
930
Chris Lattner00245f42012-01-24 13:41:11 +0000931static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +0000932 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
933
934 for (unsigned i = 0; i != NumElements; ++i)
935 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +0000936}
937
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000938void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
939 // Merge the initializer.
940 SmallVector<Constant*, 16> Elements;
Chris Lattner00245f42012-01-24 13:41:11 +0000941 getArrayElements(AVI.DstInit, Elements);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000942
James Molloyf6f121e2013-05-28 15:17:05 +0000943 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Chris Lattner00245f42012-01-24 13:41:11 +0000944 getArrayElements(SrcInit, Elements);
945
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000946 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
947 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
948}
949
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000950/// linkGlobalInits - Update the initializers in the Dest module now that all
951/// globals that may be referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000952void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +0000953 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000954 for (Module::const_global_iterator I = SrcM->global_begin(),
955 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnercbb91402011-10-11 00:24:54 +0000956
957 // Only process initialized GV's or ones not already in dest.
958 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000959
960 // Grab destination global variable.
961 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
962 // Figure out what the initializer looks like in the dest module.
963 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +0000964 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +0000965 }
Reid Spencer361e5132004-11-12 20:37:43 +0000966}
967
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000968/// linkFunctionBody - Copy the source function over into the dest function and
969/// fix up references to values. At this point we know that Dest is an external
970/// function, and that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000971void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
972 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +0000973
Chris Lattner7391dde2004-11-16 17:12:38 +0000974 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000975 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000976 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +0000977 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000978 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +0000979
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000980 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +0000981 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +0000982 }
983
Tanya Lattnercbb91402011-10-11 00:24:54 +0000984 if (Mode == Linker::DestroySource) {
985 // Splice the body of the source function into the dest function.
986 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
987
988 // At this point, all of the instructions and values of the function are now
989 // copied over. The only problem is that they are still referencing values in
990 // the Source function as operands. Loop through all of the operands of the
991 // functions and patch them up to point to the local versions.
992 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
993 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
James Molloyf6f121e2013-05-28 15:17:05 +0000994 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
995 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +0000996
997 } else {
998 // Clone the body of the function into the dest function.
999 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
James Molloyf6f121e2013-05-28 15:17:05 +00001000 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL,
1001 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +00001002 }
1003
Chris Lattner7391dde2004-11-16 17:12:38 +00001004 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001005 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1006 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001007 ValueMap.erase(I);
Tanya Lattnercbb91402011-10-11 00:24:54 +00001008
Reid Spencer361e5132004-11-12 20:37:43 +00001009}
1010
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001011/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001012void ModuleLinker::linkAliasBodies() {
1013 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001014 I != E; ++I) {
1015 if (DoNotLinkFromSource.count(I))
1016 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001017 if (Constant *Aliasee = I->getAliasee()) {
1018 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
James Molloyf6f121e2013-05-28 15:17:05 +00001019 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None,
1020 &TypeMap, &ValMaterializer));
David Chisnall2c4a34a2010-01-09 16:27:31 +00001021 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001022 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001023}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001024
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001025/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001026/// module.
1027void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001028 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001029 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1030 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001031 // Don't link module flags here. Do them separately.
1032 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001033 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1034 // Add Src elements into Dest node.
1035 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1036 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001037 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001038 }
1039}
Bill Wendling66f02412012-02-11 11:38:06 +00001040
Bill Wendling66f02412012-02-11 11:38:06 +00001041/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1042/// module.
1043bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001044 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001045 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1046 if (!SrcModFlags) return false;
1047
Bill Wendling66f02412012-02-11 11:38:06 +00001048 // If the destination module doesn't have module flags yet, then just copy
1049 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001050 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001051 if (DstModFlags->getNumOperands() == 0) {
1052 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1053 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1054
1055 return false;
1056 }
1057
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001058 // First build a map of the existing module flags and requirements.
1059 DenseMap<MDString*, MDNode*> Flags;
1060 SmallSetVector<MDNode*, 16> Requirements;
1061 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1062 MDNode *Op = DstModFlags->getOperand(I);
1063 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1064 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001065
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001066 if (Behavior->getZExtValue() == Module::Require) {
1067 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1068 } else {
1069 Flags[ID] = Op;
1070 }
Bill Wendling66f02412012-02-11 11:38:06 +00001071 }
1072
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001073 // Merge in the flags from the source module, and also collect its set of
1074 // requirements.
1075 bool HasErr = false;
1076 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1077 MDNode *SrcOp = SrcModFlags->getOperand(I);
1078 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1079 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1080 MDNode *DstOp = Flags.lookup(ID);
1081 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001082
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001083 // If this is a requirement, add it and continue.
1084 if (SrcBehaviorValue == Module::Require) {
1085 // If the destination module does not already have this requirement, add
1086 // it.
1087 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1088 DstModFlags->addOperand(SrcOp);
1089 }
1090 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001091 }
1092
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001093 // If there is no existing flag with this ID, just add it.
1094 if (!DstOp) {
1095 Flags[ID] = SrcOp;
1096 DstModFlags->addOperand(SrcOp);
1097 continue;
1098 }
1099
1100 // Otherwise, perform a merge.
1101 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1102 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1103
1104 // If either flag has override behavior, handle it first.
1105 if (DstBehaviorValue == Module::Override) {
1106 // Diagnose inconsistent flags which both have override behavior.
1107 if (SrcBehaviorValue == Module::Override &&
1108 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1109 HasErr |= emitError("linking module flags '" + ID->getString() +
1110 "': IDs have conflicting override values");
1111 }
1112 continue;
1113 } else if (SrcBehaviorValue == Module::Override) {
1114 // Update the destination flag to that of the source.
1115 DstOp->replaceOperandWith(0, SrcBehavior);
1116 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1117 continue;
1118 }
1119
1120 // Diagnose inconsistent merge behavior types.
1121 if (SrcBehaviorValue != DstBehaviorValue) {
1122 HasErr |= emitError("linking module flags '" + ID->getString() +
1123 "': IDs have conflicting behaviors");
1124 continue;
1125 }
1126
1127 // Perform the merge for standard behavior types.
1128 switch (SrcBehaviorValue) {
1129 case Module::Require:
1130 case Module::Override: assert(0 && "not possible"); break;
1131 case Module::Error: {
1132 // Emit an error if the values differ.
1133 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1134 HasErr |= emitError("linking module flags '" + ID->getString() +
1135 "': IDs have conflicting values");
1136 }
1137 continue;
1138 }
1139 case Module::Warning: {
1140 // Emit a warning if the values differ.
1141 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001142 if (!SuppressWarnings) {
1143 errs() << "WARNING: linking module flags '" << ID->getString()
1144 << "': IDs have conflicting values";
1145 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001146 }
1147 continue;
1148 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001149 case Module::Append: {
1150 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1151 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1152 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1153 Value **VP, **Values = VP = new Value*[NumOps];
1154 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1155 *VP = DstValue->getOperand(i);
1156 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1157 *VP = SrcValue->getOperand(i);
1158 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1159 ArrayRef<Value*>(Values,
1160 NumOps)));
1161 delete[] Values;
1162 break;
1163 }
1164 case Module::AppendUnique: {
1165 SmallSetVector<Value*, 16> Elts;
1166 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1167 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1168 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1169 Elts.insert(DstValue->getOperand(i));
1170 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1171 Elts.insert(SrcValue->getOperand(i));
1172 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1173 ArrayRef<Value*>(Elts.begin(),
1174 Elts.end())));
1175 break;
1176 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001177 }
Bill Wendling66f02412012-02-11 11:38:06 +00001178 }
1179
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001180 // Check all of the requirements.
1181 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1182 MDNode *Requirement = Requirements[I];
1183 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1184 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001185
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001186 MDNode *Op = Flags[Flag];
1187 if (!Op || Op->getOperand(2) != ReqValue) {
1188 HasErr |= emitError("linking module flags '" + Flag->getString() +
1189 "': does not have the required value");
1190 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001191 }
1192 }
1193
1194 return HasErr;
1195}
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001196
1197bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001198 assert(DstM && "Null destination module");
1199 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001200
1201 // Inherit the target data from the source module if the destination module
1202 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001203 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001204 DstM->setDataLayout(SrcM->getDataLayout());
1205
1206 // Copy the target triple from the source to dest if the dest's is empty.
1207 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1208 DstM->setTargetTriple(SrcM->getTargetTriple());
1209
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001210 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001211 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001212 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001213 errs() << "WARNING: Linking two modules of different data layouts: '"
1214 << SrcM->getModuleIdentifier() << "' is '"
1215 << SrcM->getDataLayoutStr() << "' whereas '"
1216 << DstM->getModuleIdentifier() << "' is '"
1217 << DstM->getDataLayoutStr() << "'\n";
Eli Benderskye17f3702014-02-06 18:01:56 +00001218 }
1219 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001220 if (!SrcM->getTargetTriple().empty() &&
1221 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001222 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001223 errs() << "WARNING: Linking two modules of different target triples: "
1224 << SrcM->getModuleIdentifier() << "' is '"
1225 << SrcM->getTargetTriple() << "' whereas '"
1226 << DstM->getModuleIdentifier() << "' is '"
Eli Benderskye17f3702014-02-06 18:01:56 +00001227 << DstM->getTargetTriple() << "'\n";
1228 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001229 }
1230
1231 // Append the module inline asm string.
1232 if (!SrcM->getModuleInlineAsm().empty()) {
1233 if (DstM->getModuleInlineAsm().empty())
1234 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1235 else
1236 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1237 SrcM->getModuleInlineAsm());
1238 }
1239
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001240 // Loop over all of the linked values to compute type mappings.
1241 computeTypeMapping();
1242
1243 // Insert all of the globals in src into the DstM module... without linking
1244 // initializers (which could refer to functions not yet mapped over).
1245 for (Module::global_iterator I = SrcM->global_begin(),
1246 E = SrcM->global_end(); I != E; ++I)
1247 if (linkGlobalProto(I))
1248 return true;
1249
1250 // Link the functions together between the two modules, without doing function
1251 // bodies... this just adds external function prototypes to the DstM
1252 // function... We do this so that when we begin processing function bodies,
1253 // all of the global values that may be referenced are available in our
1254 // ValueMap.
1255 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1256 if (linkFunctionProto(I))
1257 return true;
1258
1259 // If there were any aliases, link them now.
1260 for (Module::alias_iterator I = SrcM->alias_begin(),
1261 E = SrcM->alias_end(); I != E; ++I)
1262 if (linkAliasProto(I))
1263 return true;
1264
1265 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1266 linkAppendingVarInit(AppendingVars[i]);
1267
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001268 // Link in the function bodies that are defined in the source module into
1269 // DstM.
1270 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001271 // Skip if not linking from source.
1272 if (DoNotLinkFromSource.count(SF)) continue;
1273
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001274 Function *DF = cast<Function>(ValueMap[SF]);
1275 if (SF->hasPrefixData()) {
1276 // Link in the prefix data.
1277 DF->setPrefixData(MapValue(
1278 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1279 }
1280
Tanya Lattnerea166d42011-10-14 22:17:46 +00001281 // Skip if no body (function is external) or materialize.
1282 if (SF->isDeclaration()) {
1283 if (!SF->isMaterializable())
1284 continue;
1285 if (SF->Materialize(&ErrorMsg))
1286 return true;
1287 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001288
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001289 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001290 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001291 }
1292
1293 // Resolve all uses of aliases with aliasees.
1294 linkAliasBodies();
1295
Bill Wendling66f02412012-02-11 11:38:06 +00001296 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001297 // after linking GlobalValues so that MDNodes that reference GlobalValues
1298 // are properly remapped.
1299 linkNamedMDNodes();
1300
Bill Wendling66f02412012-02-11 11:38:06 +00001301 // Merge the module flags into the DstM module.
1302 if (linkModuleFlagsMetadata())
1303 return true;
1304
Bill Wendling91686d62014-01-16 06:29:36 +00001305 // Update the initializers in the DstM module now that all globals that may
1306 // be referenced are in DstM.
1307 linkGlobalInits();
1308
Tanya Lattner0a48b872011-11-02 00:24:56 +00001309 // Process vector of lazily linked in functions.
1310 bool LinkedInAnyFunctions;
1311 do {
1312 LinkedInAnyFunctions = false;
1313
Bill Wendlingfa2287822013-03-27 17:54:41 +00001314 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
James Molloyf6f121e2013-05-28 15:17:05 +00001315 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001316 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001317 if (!SF)
1318 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001319
James Molloyf6f121e2013-05-28 15:17:05 +00001320 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001321 if (SF->hasPrefixData()) {
1322 // Link in the prefix data.
1323 DF->setPrefixData(MapValue(SF->getPrefixData(),
1324 ValueMap,
1325 RF_None,
1326 &TypeMap,
1327 &ValMaterializer));
1328 }
James Molloyf6f121e2013-05-28 15:17:05 +00001329
1330 // Materialize if necessary.
1331 if (SF->isDeclaration()) {
1332 if (!SF->isMaterializable())
1333 continue;
1334 if (SF->Materialize(&ErrorMsg))
1335 return true;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001336 }
James Molloyf6f121e2013-05-28 15:17:05 +00001337
1338 // Erase from vector *before* the function body is linked - linkFunctionBody could
1339 // invalidate I.
1340 LazilyLinkFunctions.erase(I);
1341
1342 // Link in function body.
1343 linkFunctionBody(DF, SF);
1344 SF->Dematerialize();
1345
1346 // Set flag to indicate we may have more functions to lazily link in
1347 // since we linked in a function.
1348 LinkedInAnyFunctions = true;
1349 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001350 }
1351 } while (LinkedInAnyFunctions);
1352
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001353 // Now that all of the types from the source are used, resolve any structs
1354 // copied over to the dest that didn't exist there.
1355 TypeMap.linkDefinedTypeBodies();
1356
Anton Korobeynikov26098882008-03-05 23:21:39 +00001357 return false;
1358}
Reid Spencer361e5132004-11-12 20:37:43 +00001359
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001360Linker::Linker(Module *M, bool SuppressWarnings)
1361 : Composite(M), SuppressWarnings(SuppressWarnings) {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001362 TypeFinder StructTypes;
1363 StructTypes.run(*M, true);
1364 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1365}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001366
1367Linker::~Linker() {
1368}
1369
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001370void Linker::deleteModule() {
1371 delete Composite;
1372 Composite = NULL;
1373}
1374
Rafael Espindola3df61b72013-05-04 03:48:37 +00001375bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001376 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1377 SuppressWarnings);
Rafael Espindola287f18b2013-05-04 04:08:02 +00001378 if (TheLinker.run()) {
1379 if (ErrorMsg)
1380 *ErrorMsg = TheLinker.ErrorMsg;
1381 return true;
1382 }
1383 return false;
Rafael Espindola3df61b72013-05-04 03:48:37 +00001384}
1385
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001386//===----------------------------------------------------------------------===//
1387// LinkModules entrypoint.
1388//===----------------------------------------------------------------------===//
1389
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001390/// LinkModules - This function links two modules together, with the resulting
Eli Bendersky970cc632013-03-08 22:29:44 +00001391/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001392/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1393/// the problem. Upon failure, the Dest module could be in a modified state,
1394/// and shouldn't be relied on to be consistent.
Tanya Lattnercbb91402011-10-11 00:24:54 +00001395bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1396 std::string *ErrorMsg) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001397 Linker L(Dest);
1398 return L.linkInModule(Src, Mode, ErrorMsg);
Reid Spencer361e5132004-11-12 20:37:43 +00001399}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001400
1401//===----------------------------------------------------------------------===//
1402// C API.
1403//===----------------------------------------------------------------------===//
1404
1405LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1406 LLVMLinkerMode Mode, char **OutMessages) {
1407 std::string Messages;
1408 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1409 Mode, OutMessages? &Messages : 0);
1410 if (OutMessages)
1411 *OutMessages = strdup(Messages.c_str());
1412 return Result;
1413}