blob: 8af2c88db033816f136321dfaf7c60785fdd11a4 [file] [log] [blame]
Mikhail Glushenkovc834bbf2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
Chris Lattner52f7e902001-10-13 07:03:50 +000012//===----------------------------------------------------------------------===//
13
Reid Spencer7cc371a2004-11-14 23:27:04 +000014#include "llvm/Linker.h"
Chris Lattneradbc0b52003-11-20 18:23:14 +000015#include "llvm/Constants.h"
16#include "llvm/DerivedTypes.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000017#include "llvm/Instructions.h"
Chris Lattner5c377c52001-10-14 23:29:15 +000018#include "llvm/Module.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000019#include "llvm/ADT/DenseSet.h"
Rafael Espindola3ed88152012-01-05 23:02:01 +000020#include "llvm/ADT/Optional.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner74382b72009-08-23 22:45:37 +000023#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000024#include "llvm/Support/Path.h"
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +000025#include "llvm/Transforms/Utils/Cloning.h"
Dan Gohman05ea54e2010-08-24 18:50:07 +000026#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner1afcace2011-07-09 17:41:24 +000029//===----------------------------------------------------------------------===//
30// TypeMap implementation.
31//===----------------------------------------------------------------------===//
Chris Lattner5c377c52001-10-14 23:29:15 +000032
Chris Lattner62a81a12008-06-16 21:00:18 +000033namespace {
Chris Lattner1afcace2011-07-09 17:41:24 +000034class TypeMapTy : public ValueMapTypeRemapper {
35 /// MappedTypes - This is a mapping from a source type to a destination type
36 /// to use.
37 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +000038
Chris Lattner1afcace2011-07-09 17:41:24 +000039 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
40 /// we speculatively add types to MappedTypes, but keep track of them here in
41 /// case we need to roll back.
42 SmallVector<Type*, 16> SpeculativeTypes;
43
Chris Lattner68910502011-12-20 00:03:52 +000044 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
45 /// source module that are mapped to an opaque struct in the destination
46 /// module.
47 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
48
49 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
50 /// destination modules who are getting a body from the source module.
51 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Chris Lattnerfc196f92008-06-16 23:06:51 +000052public:
Bill Wendling601c0942012-02-28 04:01:21 +000053
Chris Lattner1afcace2011-07-09 17:41:24 +000054 /// addTypeMapping - Indicate that the specified type in the destination
55 /// module is conceptually equivalent to the specified type in the source
56 /// module.
57 void addTypeMapping(Type *DstTy, Type *SrcTy);
58
59 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
60 /// module from a type definition in the source module.
61 void linkDefinedTypeBodies();
62
63 /// get - Return the mapped type to use for the specified input type from the
64 /// source module.
65 Type *get(Type *SrcTy);
66
67 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
68
69private:
70 Type *getImpl(Type *T);
71 /// remapType - Implement the ValueMapTypeRemapper interface.
72 Type *remapType(Type *SrcTy) {
73 return get(SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000074 }
Chris Lattner1afcace2011-07-09 17:41:24 +000075
76 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattner62a81a12008-06-16 21:00:18 +000077};
78}
79
Chris Lattner1afcace2011-07-09 17:41:24 +000080void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
81 Type *&Entry = MappedTypes[SrcTy];
82 if (Entry) return;
83
84 if (DstTy == SrcTy) {
85 Entry = DstTy;
86 return;
87 }
Bill Wendling601c0942012-02-28 04:01:21 +000088
Chris Lattner1afcace2011-07-09 17:41:24 +000089 // Check to see if these types are recursively isomorphic and establish a
90 // mapping between them if so.
Bill Wendling601c0942012-02-28 04:01:21 +000091 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattner1afcace2011-07-09 17:41:24 +000092 // Oops, they aren't isomorphic. Just discard this request by rolling out
93 // any speculative mappings we've established.
94 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
95 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendling601c0942012-02-28 04:01:21 +000096 }
Chris Lattner1afcace2011-07-09 17:41:24 +000097 SpeculativeTypes.clear();
98}
Chris Lattner62a81a12008-06-16 21:00:18 +000099
Chris Lattner1afcace2011-07-09 17:41:24 +0000100/// areTypesIsomorphic - Recursively walk this pair of types, returning true
101/// if they are isomorphic, false if they are not.
102bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
103 // Two types with differing kinds are clearly not isomorphic.
104 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukmanf976c852005-04-21 22:55:34 +0000105
Chris Lattner1afcace2011-07-09 17:41:24 +0000106 // If we have an entry in the MappedTypes table, then we have our answer.
107 Type *&Entry = MappedTypes[SrcTy];
108 if (Entry)
109 return Entry == DstTy;
Misha Brukmanf976c852005-04-21 22:55:34 +0000110
Chris Lattner1afcace2011-07-09 17:41:24 +0000111 // Two identical types are clearly isomorphic. Remember this
112 // non-speculatively.
113 if (DstTy == SrcTy) {
114 Entry = DstTy;
Chris Lattner56539652008-06-16 20:03:01 +0000115 return true;
Chris Lattner1afcace2011-07-09 17:41:24 +0000116 }
Bill Wendling601c0942012-02-28 04:01:21 +0000117
Chris Lattner1afcace2011-07-09 17:41:24 +0000118 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000119
Chris Lattner1afcace2011-07-09 17:41:24 +0000120 // If this is an opaque struct type, special case it.
121 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
122 // Mapping an opaque type to any struct, just keep the dest struct.
123 if (SSTy->isOpaque()) {
124 Entry = DstTy;
125 SpeculativeTypes.push_back(SrcTy);
Chris Lattner43f4ba82003-08-22 19:12:55 +0000126 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000127 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000128
Chris Lattner68910502011-12-20 00:03:52 +0000129 // Mapping a non-opaque source type to an opaque dest. If this is the first
130 // type that we're mapping onto this destination type then we succeed. Keep
131 // the dest, but fill it in later. This doesn't need to be speculative. If
132 // this is the second (different) type that we're trying to map onto the
133 // same opaque type then we fail.
Chris Lattner1afcace2011-07-09 17:41:24 +0000134 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner68910502011-12-20 00:03:52 +0000135 // We can only map one source type onto the opaque destination type.
136 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
137 return false;
138 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattner1afcace2011-07-09 17:41:24 +0000139 Entry = DstTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000140 return true;
141 }
142 }
143
144 // If the number of subtypes disagree between the two types, then we fail.
145 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Chris Lattnere76c57a2003-08-22 06:07:12 +0000146 return false;
Chris Lattner1afcace2011-07-09 17:41:24 +0000147
148 // Fail if any of the extra properties (e.g. array size) of the type disagree.
149 if (isa<IntegerType>(DstTy))
150 return false; // bitwidth disagrees.
151 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
152 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
153 return false;
Chris Lattner1a31f3b2011-12-20 23:14:57 +0000154
Chris Lattner1afcace2011-07-09 17:41:24 +0000155 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
156 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
157 return false;
158 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
159 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner1bcbf852011-08-12 18:07:26 +0000160 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattner1afcace2011-07-09 17:41:24 +0000161 DSTy->isPacked() != SSTy->isPacked())
162 return false;
163 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
164 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
165 return false;
166 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
167 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
168 return false;
Chris Lattnere76c57a2003-08-22 06:07:12 +0000169 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000170
171 // Otherwise, we speculate that these two types will line up and recursively
172 // check the subelements.
173 Entry = DstTy;
174 SpeculativeTypes.push_back(SrcTy);
175
Bill Wendling601c0942012-02-28 04:01:21 +0000176 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
177 if (!areTypesIsomorphic(DstTy->getContainedType(i),
178 SrcTy->getContainedType(i)))
Chris Lattner1afcace2011-07-09 17:41:24 +0000179 return false;
180
181 // If everything seems to have lined up, then everything is great.
182 return true;
183}
184
185/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
186/// module from a type definition in the source module.
187void TypeMapTy::linkDefinedTypeBodies() {
188 SmallVector<Type*, 16> Elements;
189 SmallString<16> TmpName;
190
191 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner68910502011-12-20 00:03:52 +0000192 // entries to the SrcDefinitionsToResolve vector.
193 while (!SrcDefinitionsToResolve.empty()) {
194 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattner1afcace2011-07-09 17:41:24 +0000195 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
196
197 // TypeMap is a many-to-one mapping, if there were multiple types that
198 // provide a body for DstSTy then previous iterations of this loop may have
199 // already handled it. Just ignore this case.
200 if (!DstSTy->isOpaque()) continue;
201 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
202
203 // Map the body of the source type over to a new body for the dest type.
204 Elements.resize(SrcSTy->getNumElements());
205 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
206 Elements[i] = getImpl(SrcSTy->getElementType(i));
207
208 DstSTy->setBody(Elements, SrcSTy->isPacked());
209
210 // If DstSTy has no name or has a longer name than STy, then viciously steal
211 // STy's name.
212 if (!SrcSTy->hasName()) continue;
213 StringRef SrcName = SrcSTy->getName();
214
215 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
216 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
217 SrcSTy->setName("");
218 DstSTy->setName(TmpName.str());
219 TmpName.clear();
220 }
221 }
Chris Lattner68910502011-12-20 00:03:52 +0000222
223 DstResolvedOpaqueTypes.clear();
Chris Lattner1afcace2011-07-09 17:41:24 +0000224}
225
Bill Wendling601c0942012-02-28 04:01:21 +0000226
Chris Lattner1afcace2011-07-09 17:41:24 +0000227/// get - Return the mapped type to use for the specified input type from the
228/// source module.
229Type *TypeMapTy::get(Type *Ty) {
230 Type *Result = getImpl(Ty);
231
232 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner68910502011-12-20 00:03:52 +0000233 if (!SrcDefinitionsToResolve.empty())
Chris Lattner1afcace2011-07-09 17:41:24 +0000234 linkDefinedTypeBodies();
235 return Result;
236}
237
238/// getImpl - This is the recursive version of get().
239Type *TypeMapTy::getImpl(Type *Ty) {
240 // If we already have an entry for this type, return it.
241 Type **Entry = &MappedTypes[Ty];
242 if (*Entry) return *Entry;
Bill Wendling601c0942012-02-28 04:01:21 +0000243
Chris Lattner1afcace2011-07-09 17:41:24 +0000244 // If this is not a named struct type, then just map all of the elements and
245 // then rebuild the type from inside out.
Chris Lattner1bcbf852011-08-12 18:07:26 +0000246 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000247 // If there are no element types to map, then the type is itself. This is
248 // true for the anonymous {} struct, things like 'float', integers, etc.
249 if (Ty->getNumContainedTypes() == 0)
250 return *Entry = Ty;
251
252 // Remap all of the elements, keeping track of whether any of them change.
253 bool AnyChange = false;
254 SmallVector<Type*, 4> ElementTypes;
255 ElementTypes.resize(Ty->getNumContainedTypes());
256 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
257 ElementTypes[i] = getImpl(Ty->getContainedType(i));
258 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
259 }
260
261 // If we found our type while recursively processing stuff, just use it.
262 Entry = &MappedTypes[Ty];
263 if (*Entry) return *Entry;
264
265 // If all of the element types mapped directly over, then the type is usable
266 // as-is.
267 if (!AnyChange)
268 return *Entry = Ty;
269
270 // Otherwise, rebuild a modified type.
271 switch (Ty->getTypeID()) {
Craig Topper85814382012-02-07 05:05:23 +0000272 default: llvm_unreachable("unknown derived type to remap");
Chris Lattner1afcace2011-07-09 17:41:24 +0000273 case Type::ArrayTyID:
274 return *Entry = ArrayType::get(ElementTypes[0],
275 cast<ArrayType>(Ty)->getNumElements());
276 case Type::VectorTyID:
277 return *Entry = VectorType::get(ElementTypes[0],
278 cast<VectorType>(Ty)->getNumElements());
279 case Type::PointerTyID:
280 return *Entry = PointerType::get(ElementTypes[0],
281 cast<PointerType>(Ty)->getAddressSpace());
282 case Type::FunctionTyID:
283 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000284 makeArrayRef(ElementTypes).slice(1),
Chris Lattner1afcace2011-07-09 17:41:24 +0000285 cast<FunctionType>(Ty)->isVarArg());
286 case Type::StructTyID:
287 // Note that this is only reached for anonymous structs.
288 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
289 cast<StructType>(Ty)->isPacked());
290 }
291 }
292
293 // Otherwise, this is an unmapped named struct. If the struct can be directly
294 // mapped over, just use it as-is. This happens in a case when the linked-in
295 // module has something like:
296 // %T = type {%T*, i32}
297 // @GV = global %T* null
298 // where T does not exist at all in the destination module.
299 //
300 // The other case we watch for is when the type is not in the destination
301 // module, but that it has to be rebuilt because it refers to something that
302 // is already mapped. For example, if the destination module has:
303 // %A = type { i32 }
304 // and the source module has something like
305 // %A' = type { i32 }
306 // %B = type { %A'* }
307 // @GV = global %B* null
308 // then we want to create a new type: "%B = type { %A*}" and have it take the
309 // pristine "%B" name from the source module.
310 //
311 // To determine which case this is, we have to recursively walk the type graph
312 // speculating that we'll be able to reuse it unmodified. Only if this is
313 // safe would we map the entire thing over. Because this is an optimization,
314 // and is not required for the prettiness of the linked module, we just skip
315 // it and always rebuild a type here.
316 StructType *STy = cast<StructType>(Ty);
317
318 // If the type is opaque, we can just use it directly.
319 if (STy->isOpaque())
320 return *Entry = STy;
Bill Wendling601c0942012-02-28 04:01:21 +0000321
Chris Lattner1afcace2011-07-09 17:41:24 +0000322 // Otherwise we create a new type and resolve its body later. This will be
323 // resolved by the top level of get().
Chris Lattner68910502011-12-20 00:03:52 +0000324 SrcDefinitionsToResolve.push_back(STy);
325 StructType *DTy = StructType::create(STy->getContext());
326 DstResolvedOpaqueTypes.insert(DTy);
327 return *Entry = DTy;
Chris Lattner1afcace2011-07-09 17:41:24 +0000328}
329
Bill Wendling601c0942012-02-28 04:01:21 +0000330
331
Chris Lattner1afcace2011-07-09 17:41:24 +0000332//===----------------------------------------------------------------------===//
333// ModuleLinker implementation.
334//===----------------------------------------------------------------------===//
335
336namespace {
337 /// ModuleLinker - This is an implementation class for the LinkModules
338 /// function, which is the entrypoint for this file.
339 class ModuleLinker {
340 Module *DstM, *SrcM;
341
342 TypeMapTy TypeMap;
343
344 /// ValueMap - Mapping of values from what they used to be in Src, to what
345 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
346 /// some overhead due to the use of Value handles which the Linker doesn't
347 /// actually need, but this allows us to reuse the ValueMapper code.
348 ValueToValueMapTy ValueMap;
349
350 struct AppendingVarInfo {
351 GlobalVariable *NewGV; // New aggregate global in dest module.
352 Constant *DstInit; // Old initializer from dest module.
353 Constant *SrcInit; // Old initializer from src module.
354 };
355
356 std::vector<AppendingVarInfo> AppendingVars;
357
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000358 unsigned Mode; // Mode to treat source module.
359
360 // Set of items not to link in from source.
361 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
362
Tanya Lattner9af37a32011-11-02 00:24:56 +0000363 // Vector of functions to lazily link in.
364 std::vector<Function*> LazilyLinkFunctions;
365
Chris Lattner1afcace2011-07-09 17:41:24 +0000366 public:
367 std::string ErrorMsg;
368
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000369 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
370 : DstM(dstM), SrcM(srcM), Mode(mode) { }
Chris Lattner1afcace2011-07-09 17:41:24 +0000371
372 bool run();
373
374 private:
375 /// emitError - Helper method for setting a message and returning an error
376 /// code.
377 bool emitError(const Twine &Message) {
378 ErrorMsg = Message.str();
Chris Lattnerf6f4f7a2008-06-16 18:27:53 +0000379 return true;
Chris Lattnera4477f92008-06-16 21:17:12 +0000380 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000381
382 /// getLinkageResult - This analyzes the two global values and determines
383 /// what the result will look like in the destination module.
384 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000385 GlobalValue::LinkageTypes &LT,
386 GlobalValue::VisibilityTypes &Vis,
387 bool &LinkFromSrc);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000388
Chris Lattner1afcace2011-07-09 17:41:24 +0000389 /// getLinkedToGlobal - Given a global in the source module, return the
390 /// global in the destination module that is being linked to, if any.
391 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
392 // If the source has no name it can't link. If it has local linkage,
393 // there is no name match-up going on.
394 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
395 return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000396
Chris Lattner1afcace2011-07-09 17:41:24 +0000397 // Otherwise see if we have a match in the destination module's symtab.
398 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
399 if (DGV == 0) return 0;
Bill Wendling601c0942012-02-28 04:01:21 +0000400
Chris Lattner1afcace2011-07-09 17:41:24 +0000401 // If we found a global with the same name in the dest module, but it has
402 // internal linkage, we are really not doing any linkage here.
403 if (DGV->hasLocalLinkage())
404 return 0;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000405
Chris Lattner1afcace2011-07-09 17:41:24 +0000406 // Otherwise, we do in fact link to the destination global.
407 return DGV;
408 }
409
410 void computeTypeMapping();
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000411 bool categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
412 DenseMap<MDString*, MDNode*> &ErrorNode,
413 DenseMap<MDString*, MDNode*> &WarningNode,
414 DenseMap<MDString*, MDNode*> &OverrideNode,
415 DenseMap<MDString*,
416 SmallSetVector<MDNode*, 8> > &RequireNodes,
417 SmallSetVector<MDString*, 16> &SeenIDs);
Chris Lattner1afcace2011-07-09 17:41:24 +0000418
419 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
420 bool linkGlobalProto(GlobalVariable *SrcGV);
421 bool linkFunctionProto(Function *SrcF);
422 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000423 bool linkModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000424
425 void linkAppendingVarInit(const AppendingVarInfo &AVI);
426 void linkGlobalInits();
427 void linkFunctionBody(Function *Dst, Function *Src);
428 void linkAliasBodies();
429 void linkNamedMDNodes();
430 };
Bill Wendling601c0942012-02-28 04:01:21 +0000431}
432
433
Chris Lattner2c236f32001-11-03 05:18:24 +0000434
Chris Lattner1afcace2011-07-09 17:41:24 +0000435/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer8bef0372007-02-04 04:29:21 +0000436/// in the symbol table. This is good for all clients except for us. Go
437/// through the trouble to force this back.
Chris Lattner1afcace2011-07-09 17:41:24 +0000438static void forceRenaming(GlobalValue *GV, StringRef Name) {
439 // If the global doesn't force its name or if it already has the right name,
440 // there is nothing for us to do.
441 if (GV->hasLocalLinkage() || GV->getName() == Name)
442 return;
443
444 Module *M = GV->getParent();
Chris Lattnerc0036282004-08-04 07:05:54 +0000445
446 // If there is a conflict, rename the conflict.
Chris Lattner1afcace2011-07-09 17:41:24 +0000447 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner33f29492007-02-11 00:39:38 +0000448 GV->takeName(ConflictGV);
449 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattner1afcace2011-07-09 17:41:24 +0000450 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner33f29492007-02-11 00:39:38 +0000451 } else {
452 GV->setName(Name); // Force the name back
Reid Spenceref9b9a72007-02-05 20:47:22 +0000453 }
Reid Spenceref9b9a72007-02-05 20:47:22 +0000454}
Reid Spencer8bef0372007-02-04 04:29:21 +0000455
Reid Spenceref9b9a72007-02-05 20:47:22 +0000456/// CopyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000457/// a GlobalValue) from the SrcGV to the DestGV.
Reid Spenceref9b9a72007-02-05 20:47:22 +0000458static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands28c3cff2008-05-26 19:58:59 +0000459 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
460 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
461 DestGV->copyAttributesFrom(SrcGV);
462 DestGV->setAlignment(Alignment);
Chris Lattner1afcace2011-07-09 17:41:24 +0000463
464 forceRenaming(DestGV, SrcGV->getName());
Chris Lattnerc0036282004-08-04 07:05:54 +0000465}
466
Rafael Espindola3ed88152012-01-05 23:02:01 +0000467static bool isLessConstraining(GlobalValue::VisibilityTypes a,
468 GlobalValue::VisibilityTypes b) {
469 if (a == GlobalValue::HiddenVisibility)
470 return false;
471 if (b == GlobalValue::HiddenVisibility)
472 return true;
473 if (a == GlobalValue::ProtectedVisibility)
474 return false;
475 if (b == GlobalValue::ProtectedVisibility)
476 return true;
477 return false;
478}
479
Chris Lattner1afcace2011-07-09 17:41:24 +0000480/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattneraee38ea2004-12-03 22:18:41 +0000481/// the result will look like in the destination module. In particular, it
Rafael Espindola3ed88152012-01-05 23:02:01 +0000482/// computes the resultant linkage type and visibility, computes whether the
483/// global in the source should be copied over to the destination (replacing
484/// the existing one), and computes whether this linkage is an error or not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000485bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola3ed88152012-01-05 23:02:01 +0000486 GlobalValue::LinkageTypes &LT,
487 GlobalValue::VisibilityTypes &Vis,
Chris Lattner1afcace2011-07-09 17:41:24 +0000488 bool &LinkFromSrc) {
489 assert(Dest && "Must have two globals being queried");
490 assert(!Src->hasLocalLinkage() &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000491 "If Src has internal linkage, Dest shouldn't be set!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000492
Peter Collingbourne88953162011-10-30 17:46:34 +0000493 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattnerf84c59d2011-07-14 20:23:05 +0000494 bool DestIsDeclaration = Dest->isDeclaration();
Chris Lattner1afcace2011-07-09 17:41:24 +0000495
496 if (SrcIsDeclaration) {
Anton Korobeynikov2b48ef02008-03-10 22:33:22 +0000497 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattneraee38ea2004-12-03 22:18:41 +0000498 // external globals, we aren't adding anything.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000499 if (Src->hasDLLImportLinkage()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000500 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
Chris Lattner1afcace2011-07-09 17:41:24 +0000501 if (DestIsDeclaration) {
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000502 LinkFromSrc = true;
503 LT = Src->getLinkage();
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000504 }
Andrew Lenharth8753c442006-12-15 17:35:32 +0000505 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000506 // If the Dest is weak, use the source linkage.
Andrew Lenharth8753c442006-12-15 17:35:32 +0000507 LinkFromSrc = true;
508 LT = Src->getLinkage();
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000509 } else {
510 LinkFromSrc = false;
511 LT = Dest->getLinkage();
512 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000513 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000514 // If Dest is external but Src is not:
515 LinkFromSrc = true;
516 LT = Src->getLinkage();
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000517 } else if (Src->isWeakForLinker()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000518 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
519 // or DLL* linkage.
Chris Lattner266c7bb2009-04-13 05:44:34 +0000520 if (Dest->hasExternalWeakLinkage() ||
521 Dest->hasAvailableExternallyLinkage() ||
522 (Dest->hasLinkOnceLinkage() &&
523 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattneraee38ea2004-12-03 22:18:41 +0000524 LinkFromSrc = true;
525 LT = Src->getLinkage();
526 } else {
527 LinkFromSrc = false;
528 LT = Dest->getLinkage();
529 }
Duncan Sandsa05ef5e2009-03-08 13:35:23 +0000530 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000531 // At this point we know that Src has External* or DLL* linkage.
532 if (Src->hasExternalWeakLinkage()) {
533 LinkFromSrc = false;
534 LT = Dest->getLinkage();
535 } else {
536 LinkFromSrc = true;
537 LT = GlobalValue::ExternalLinkage;
538 }
Chris Lattneraee38ea2004-12-03 22:18:41 +0000539 } else {
Chris Lattner1afcace2011-07-09 17:41:24 +0000540 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
541 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
542 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
543 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattneraee38ea2004-12-03 22:18:41 +0000544 "Unexpected linkage type!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000545 return emitError("Linking globals named '" + Src->getName() +
Chris Lattneraee38ea2004-12-03 22:18:41 +0000546 "': symbol multiply defined!");
547 }
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +0000548
Rafael Espindola3ed88152012-01-05 23:02:01 +0000549 // Compute the visibility. We follow the rules in the System V Application
550 // Binary Interface.
551 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
552 Dest->getVisibility() : Src->getVisibility();
Chris Lattneraee38ea2004-12-03 22:18:41 +0000553 return false;
554}
Chris Lattner5c377c52001-10-14 23:29:15 +0000555
Chris Lattner1afcace2011-07-09 17:41:24 +0000556/// computeTypeMapping - Loop over all of the linked values to compute type
557/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
558/// we have two struct types 'Foo' but one got renamed when the module was
559/// loaded into the same LLVMContext.
560void ModuleLinker::computeTypeMapping() {
561 // Incorporate globals.
562 for (Module::global_iterator I = SrcM->global_begin(),
563 E = SrcM->global_end(); I != E; ++I) {
564 GlobalValue *DGV = getLinkedToGlobal(I);
565 if (DGV == 0) continue;
566
567 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
568 TypeMap.addTypeMapping(DGV->getType(), I->getType());
569 continue;
570 }
571
572 // Unify the element type of appending arrays.
573 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
574 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
575 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patelab67e702009-08-11 18:01:24 +0000576 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000577
578 // Incorporate functions.
579 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
580 if (GlobalValue *DGV = getLinkedToGlobal(I))
581 TypeMap.addTypeMapping(DGV->getType(), I->getType());
582 }
Bill Wendlingc68d1272012-02-27 22:34:19 +0000583
Bill Wendling601c0942012-02-28 04:01:21 +0000584 // Incorporate types by name, scanning all the types in the source module.
585 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling348e5e72012-02-27 23:48:30 +0000586 // example. When the source module got loaded into the same LLVMContext, if
587 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling601c0942012-02-28 04:01:21 +0000588 // Though it isn't required for correctness, attempt to link these up to clean
589 // up the IR.
Bill Wendling348e5e72012-02-27 23:48:30 +0000590 std::vector<StructType*> SrcStructTypes;
591 SrcM->findUsedStructTypes(SrcStructTypes);
592
593 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
594 SrcStructTypes.end());
595
596 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
597 StructType *ST = SrcStructTypes[i];
598 if (!ST->hasName()) continue;
599
600 // Check to see if there is a dot in the name followed by a digit.
Bill Wendling601c0942012-02-28 04:01:21 +0000601 size_t DotPos = ST->getName().rfind('.');
602 if (DotPos == 0 || DotPos == StringRef::npos ||
603 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
604 continue;
Bill Wendling348e5e72012-02-27 23:48:30 +0000605
606 // Check to see if the destination module has a struct with the prefix name.
Bill Wendling601c0942012-02-28 04:01:21 +0000607 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling348e5e72012-02-27 23:48:30 +0000608 // Don't use it if this actually came from the source module. They're in
609 // the same LLVMContext after all.
610 if (!SrcStructTypesSet.count(DST))
611 TypeMap.addTypeMapping(DST, ST);
612 }
613
Chris Lattner1afcace2011-07-09 17:41:24 +0000614 // Don't bother incorporating aliases, they aren't generally typed well.
Bill Wendling601c0942012-02-28 04:01:21 +0000615
Chris Lattner1afcace2011-07-09 17:41:24 +0000616 // Now that we have discovered all of the type equivalences, get a body for
617 // any 'opaque' types in the dest module that are now resolved.
618 TypeMap.linkDefinedTypeBodies();
Devang Patelab67e702009-08-11 18:01:24 +0000619}
620
Chris Lattner1afcace2011-07-09 17:41:24 +0000621/// linkAppendingVarProto - If there were any appending global variables, link
622/// them together now. Return true on error.
623bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
624 GlobalVariable *SrcGV) {
Bill Wendling601c0942012-02-28 04:01:21 +0000625
Chris Lattner1afcace2011-07-09 17:41:24 +0000626 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
627 return emitError("Linking globals named '" + SrcGV->getName() +
628 "': can only link appending global with another appending global!");
629
630 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
631 ArrayType *SrcTy =
632 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
633 Type *EltTy = DstTy->getElementType();
634
635 // Check to see that they two arrays agree on type.
636 if (EltTy != SrcTy->getElementType())
637 return emitError("Appending variables with different element types!");
638 if (DstGV->isConstant() != SrcGV->isConstant())
639 return emitError("Appending variables linked with different const'ness!");
640
641 if (DstGV->getAlignment() != SrcGV->getAlignment())
642 return emitError(
643 "Appending variables with different alignment need to be linked!");
644
645 if (DstGV->getVisibility() != SrcGV->getVisibility())
646 return emitError(
647 "Appending variables with different visibility need to be linked!");
648
649 if (DstGV->getSection() != SrcGV->getSection())
650 return emitError(
651 "Appending variables with different section name need to be linked!");
652
653 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
654 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
655
656 // Create the new global variable.
657 GlobalVariable *NG =
658 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
659 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
660 DstGV->isThreadLocal(),
661 DstGV->getType()->getAddressSpace());
662
663 // Propagate alignment, visibility and section info.
664 CopyGVAttributes(NG, DstGV);
665
666 AppendingVarInfo AVI;
667 AVI.NewGV = NG;
668 AVI.DstInit = DstGV->getInitializer();
669 AVI.SrcInit = SrcGV->getInitializer();
670 AppendingVars.push_back(AVI);
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000671
Chris Lattner1afcace2011-07-09 17:41:24 +0000672 // Replace any uses of the two global variables with uses of the new
673 // global.
674 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikov01f69392008-03-10 22:34:28 +0000675
Chris Lattner1afcace2011-07-09 17:41:24 +0000676 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
677 DstGV->eraseFromParent();
678
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000679 // Track the source variable so we don't try to link it.
680 DoNotLinkFromSource.insert(SrcGV);
681
Chris Lattner1afcace2011-07-09 17:41:24 +0000682 return false;
683}
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000684
Chris Lattner1afcace2011-07-09 17:41:24 +0000685/// linkGlobalProto - Loop through the global variables in the src module and
686/// merge them into the dest module.
687bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
688 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000689 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Mikhail Glushenkoveba2cb02009-03-03 07:22:23 +0000690
Chris Lattner1afcace2011-07-09 17:41:24 +0000691 if (DGV) {
692 // Concatenation of appending linkage variables is magic and handled later.
693 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
694 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
695
696 // Determine whether linkage of these two globals follows the source
697 // module's definition or the destination module's definition.
Chris Lattnerb324bd72006-11-09 05:18:12 +0000698 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000699 GlobalValue::VisibilityTypes NV;
Chris Lattnerb324bd72006-11-09 05:18:12 +0000700 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000701 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
Chris Lattneraee38ea2004-12-03 22:18:41 +0000702 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000703 NewVisibility = NV;
Chris Lattner0fec08e2003-04-21 21:07:05 +0000704
Chris Lattner1afcace2011-07-09 17:41:24 +0000705 // If we're not linking from the source, then keep the definition that we
706 // have.
707 if (!LinkFromSrc) {
708 // Special case for const propagation.
709 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
710 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
711 DGVar->setConstant(true);
712
Rafael Espindola3ed88152012-01-05 23:02:01 +0000713 // Set calculated linkage and visibility.
Chris Lattner1afcace2011-07-09 17:41:24 +0000714 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000715 DGV->setVisibility(*NewVisibility);
716
Chris Lattner6157e382008-07-14 07:23:24 +0000717 // Make sure to remember this mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000718 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
719
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000720 // Track the source global so that we don't attempt to copy it over when
721 // processing global initializers.
722 DoNotLinkFromSource.insert(SGV);
723
Chris Lattner1afcace2011-07-09 17:41:24 +0000724 return false;
Chris Lattner6157e382008-07-14 07:23:24 +0000725 }
Chris Lattner5c377c52001-10-14 23:29:15 +0000726 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000727
728 // No linking to be performed or linking from the source: simply create an
729 // identical version of the symbol over in the dest module... the
730 // initializer will be filled in later by LinkGlobalInits.
731 GlobalVariable *NewDGV =
732 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
733 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
734 SGV->getName(), /*insertbefore*/0,
735 SGV->isThreadLocal(),
736 SGV->getType()->getAddressSpace());
737 // Propagate alignment, visibility and section info.
738 CopyGVAttributes(NewDGV, SGV);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000739 if (NewVisibility)
740 NewDGV->setVisibility(*NewVisibility);
Chris Lattner1afcace2011-07-09 17:41:24 +0000741
742 if (DGV) {
743 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
744 DGV->eraseFromParent();
745 }
746
747 // Make sure to remember this mapping.
748 ValueMap[SGV] = NewDGV;
Chris Lattner5c377c52001-10-14 23:29:15 +0000749 return false;
750}
751
Chris Lattner1afcace2011-07-09 17:41:24 +0000752/// linkFunctionProto - Link the function in the source module into the
753/// destination module if needed, setting up mapping information.
754bool ModuleLinker::linkFunctionProto(Function *SF) {
755 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000756 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Chris Lattner1afcace2011-07-09 17:41:24 +0000757
758 if (DGV) {
759 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
760 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000761 GlobalValue::VisibilityTypes NV;
762 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000763 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000764 NewVisibility = NV;
765
Chris Lattner1afcace2011-07-09 17:41:24 +0000766 if (!LinkFromSrc) {
767 // Set calculated linkage
768 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000769 DGV->setVisibility(*NewVisibility);
770
Chris Lattner1afcace2011-07-09 17:41:24 +0000771 // Make sure to remember this mapping.
772 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
773
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000774 // Track the function from the source module so we don't attempt to remap
775 // it.
776 DoNotLinkFromSource.insert(SF);
777
Chris Lattner1afcace2011-07-09 17:41:24 +0000778 return false;
779 }
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000780 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000781
782 // If there is no linkage to be performed or we are linking from the source,
783 // bring SF over.
784 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
785 SF->getLinkage(), SF->getName(), DstM);
786 CopyGVAttributes(NewDF, SF);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000787 if (NewVisibility)
788 NewDF->setVisibility(*NewVisibility);
Anton Korobeynikov58887bc2008-03-05 22:22:46 +0000789
Chris Lattner1afcace2011-07-09 17:41:24 +0000790 if (DGV) {
791 // Any uses of DF need to change to NewDF, with cast.
792 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
793 DGV->eraseFromParent();
Tanya Lattner9af37a32011-11-02 00:24:56 +0000794 } else {
795 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
796 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
797 SF->hasAvailableExternallyLinkage()) {
798 DoNotLinkFromSource.insert(SF);
799 LazilyLinkFunctions.push_back(SF);
800 }
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000801 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000802
803 ValueMap[SF] = NewDF;
Lauro Ramos Venancio31ed0fb2007-06-28 19:02:54 +0000804 return false;
805}
806
Chris Lattner1afcace2011-07-09 17:41:24 +0000807/// LinkAliasProto - Set up prototypes for any aliases that come over from the
808/// source module.
809bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
810 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000811 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
812
Chris Lattner1afcace2011-07-09 17:41:24 +0000813 if (DGV) {
814 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000815 GlobalValue::VisibilityTypes NV;
Chris Lattner1afcace2011-07-09 17:41:24 +0000816 bool LinkFromSrc = false;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000817 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
Chris Lattner1afcace2011-07-09 17:41:24 +0000818 return true;
Rafael Espindola3ed88152012-01-05 23:02:01 +0000819 NewVisibility = NV;
820
Chris Lattner1afcace2011-07-09 17:41:24 +0000821 if (!LinkFromSrc) {
822 // Set calculated linkage.
823 DGV->setLinkage(NewLinkage);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000824 DGV->setVisibility(*NewVisibility);
825
Chris Lattner1afcace2011-07-09 17:41:24 +0000826 // Make sure to remember this mapping.
827 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
828
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000829 // Track the alias from the source module so we don't attempt to remap it.
830 DoNotLinkFromSource.insert(SGA);
831
Chris Lattner1afcace2011-07-09 17:41:24 +0000832 return false;
833 }
834 }
835
836 // If there is no linkage to be performed or we're linking from the source,
837 // bring over SGA.
838 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
839 SGA->getLinkage(), SGA->getName(),
840 /*aliasee*/0, DstM);
841 CopyGVAttributes(NewDA, SGA);
Rafael Espindola3ed88152012-01-05 23:02:01 +0000842 if (NewVisibility)
843 NewDA->setVisibility(*NewVisibility);
Chris Lattner5c377c52001-10-14 23:29:15 +0000844
Chris Lattner1afcace2011-07-09 17:41:24 +0000845 if (DGV) {
846 // Any uses of DGV need to change to NewDA, with cast.
847 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
848 DGV->eraseFromParent();
849 }
850
851 ValueMap[SGA] = NewDA;
852 return false;
853}
854
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000855static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattnera1f00f42012-01-25 06:48:06 +0000856 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
857
858 for (unsigned i = 0; i != NumElements; ++i)
859 Dest.push_back(C->getAggregateElement(i));
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000860}
861
Chris Lattner1afcace2011-07-09 17:41:24 +0000862void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
863 // Merge the initializer.
864 SmallVector<Constant*, 16> Elements;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000865 getArrayElements(AVI.DstInit, Elements);
Chris Lattner1afcace2011-07-09 17:41:24 +0000866
867 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000868 getArrayElements(SrcInit, Elements);
869
Chris Lattner1afcace2011-07-09 17:41:24 +0000870 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
871 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
872}
873
874
875// linkGlobalInits - Update the initializers in the Dest module now that all
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000876// globals that may be referenced are in Dest.
Chris Lattner1afcace2011-07-09 17:41:24 +0000877void ModuleLinker::linkGlobalInits() {
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000878 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattner1afcace2011-07-09 17:41:24 +0000879 for (Module::const_global_iterator I = SrcM->global_begin(),
880 E = SrcM->global_end(); I != E; ++I) {
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000881
882 // Only process initialized GV's or ones not already in dest.
883 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000884
885 // Grab destination global variable.
886 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
887 // Figure out what the initializer looks like in the dest module.
888 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
889 RF_None, &TypeMap));
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000890 }
Chris Lattner8d2de8a2001-10-15 03:12:52 +0000891}
Chris Lattner5c377c52001-10-14 23:29:15 +0000892
Chris Lattner1afcace2011-07-09 17:41:24 +0000893// linkFunctionBody - Copy the source function over into the dest function and
Chris Lattnerc8cc4cb2002-05-07 18:36:35 +0000894// fix up references to values. At this point we know that Dest is an external
895// function, and that Src is not.
Chris Lattner1afcace2011-07-09 17:41:24 +0000896void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
897 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Chris Lattner5c377c52001-10-14 23:29:15 +0000898
Chris Lattner0033baf2004-11-16 17:12:38 +0000899 // Go through and convert function arguments over, remembering the mapping.
Chris Lattner1afcace2011-07-09 17:41:24 +0000900 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000901 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000902 I != E; ++I, ++DI) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000903 DI->setName(I->getName()); // Copy the name over.
Chris Lattner5c377c52001-10-14 23:29:15 +0000904
Chris Lattner1afcace2011-07-09 17:41:24 +0000905 // Add a mapping to our mapping.
Anton Korobeynikov817bf2a2008-03-10 22:36:08 +0000906 ValueMap[I] = DI;
Chris Lattner5c377c52001-10-14 23:29:15 +0000907 }
908
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000909 if (Mode == Linker::DestroySource) {
910 // Splice the body of the source function into the dest function.
911 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
912
913 // At this point, all of the instructions and values of the function are now
914 // copied over. The only problem is that they are still referencing values in
915 // the Source function as operands. Loop through all of the operands of the
916 // functions and patch them up to point to the local versions.
917 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
918 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
919 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
920
921 } else {
922 // Clone the body of the function into the dest function.
923 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Mon P Wangd24397a2011-12-23 02:18:32 +0000924 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000925 }
926
Chris Lattner0033baf2004-11-16 17:12:38 +0000927 // There is no need to map the arguments anymore.
Chris Lattner11273152006-06-16 01:24:04 +0000928 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
929 I != E; ++I)
Reid Spenceref9b9a72007-02-05 20:47:22 +0000930 ValueMap.erase(I);
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000931
Chris Lattner5c377c52001-10-14 23:29:15 +0000932}
933
934
Chris Lattner1afcace2011-07-09 17:41:24 +0000935void ModuleLinker::linkAliasBodies() {
936 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000937 I != E; ++I) {
938 if (DoNotLinkFromSource.count(I))
939 continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000940 if (Constant *Aliasee = I->getAliasee()) {
941 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
942 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
David Chisnall34722462010-01-09 16:27:31 +0000943 }
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +0000944 }
Chris Lattner1afcace2011-07-09 17:41:24 +0000945}
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000946
Chris Lattner1afcace2011-07-09 17:41:24 +0000947/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
948/// module.
949void ModuleLinker::linkNamedMDNodes() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000950 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattner1afcace2011-07-09 17:41:24 +0000951 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
952 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000953 // Don't link module flags here. Do them separately.
954 if (&*I == SrcModFlags) continue;
Chris Lattner1afcace2011-07-09 17:41:24 +0000955 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
956 // Add Src elements into Dest node.
957 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
958 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
959 RF_None, &TypeMap));
960 }
961}
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000962
963/// categorizeModuleFlagNodes -
964bool ModuleLinker::
965categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
966 DenseMap<MDString*, MDNode*> &ErrorNode,
967 DenseMap<MDString*, MDNode*> &WarningNode,
968 DenseMap<MDString*, MDNode*> &OverrideNode,
969 DenseMap<MDString*,
970 SmallSetVector<MDNode*, 8> > &RequireNodes,
971 SmallSetVector<MDString*, 16> &SeenIDs) {
972 bool HasErr = false;
973
974 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
975 MDNode *Op = ModFlags->getOperand(I);
976 assert(Op->getNumOperands() == 3 && "Invalid module flag metadata!");
977 assert(isa<ConstantInt>(Op->getOperand(0)) &&
978 "Module flag's first operand must be an integer!");
979 assert(isa<MDString>(Op->getOperand(1)) &&
980 "Module flag's second operand must be an MDString!");
981
982 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
983 MDString *ID = cast<MDString>(Op->getOperand(1));
984 Value *Val = Op->getOperand(2);
985 switch (Behavior->getZExtValue()) {
986 default:
987 assert(false && "Invalid behavior in module flag metadata!");
988 break;
989 case Module::Error: {
990 MDNode *&ErrNode = ErrorNode[ID];
991 if (!ErrNode) ErrNode = Op;
992 if (ErrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +0000993 HasErr = emitError("linking module flags '" + ID->getString() +
994 "': IDs have conflicting values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +0000995 break;
996 }
997 case Module::Warning: {
998 MDNode *&WarnNode = WarningNode[ID];
999 if (!WarnNode) WarnNode = Op;
1000 if (WarnNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001001 errs() << "WARNING: linking module flags '" << ID->getString()
1002 << "': IDs have conflicting values";
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001003 break;
1004 }
1005 case Module::Require: RequireNodes[ID].insert(Op); break;
1006 case Module::Override: {
1007 MDNode *&OvrNode = OverrideNode[ID];
1008 if (!OvrNode) OvrNode = Op;
1009 if (OvrNode->getOperand(2) != Val)
Bill Wendling75b3d682012-02-14 09:13:54 +00001010 HasErr = emitError("linking module flags '" + ID->getString() +
1011 "': IDs have conflicting override values");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001012 break;
1013 }
1014 }
1015
1016 SeenIDs.insert(ID);
1017 }
1018
1019 return HasErr;
1020}
1021
1022/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1023/// module.
1024bool ModuleLinker::linkModuleFlagsMetadata() {
1025 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1026 if (!SrcModFlags) return false;
1027
1028 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1029
1030 // If the destination module doesn't have module flags yet, then just copy
1031 // over the source module's flags.
1032 if (DstModFlags->getNumOperands() == 0) {
1033 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1034 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1035
1036 return false;
1037 }
1038
1039 bool HasErr = false;
1040
1041 // Otherwise, we have to merge them based on their behaviors. First,
1042 // categorize all of the nodes in the modules' module flags. If an error or
1043 // warning occurs, then emit the appropriate message(s).
1044 DenseMap<MDString*, MDNode*> ErrorNode;
1045 DenseMap<MDString*, MDNode*> WarningNode;
1046 DenseMap<MDString*, MDNode*> OverrideNode;
1047 DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes;
1048 SmallSetVector<MDString*, 16> SeenIDs;
1049
1050 HasErr |= categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNode,
1051 OverrideNode, RequireNodes, SeenIDs);
1052 HasErr |= categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNode,
1053 OverrideNode, RequireNodes, SeenIDs);
1054
1055 // Check that there isn't both an error and warning node for a flag.
1056 for (SmallSetVector<MDString*, 16>::iterator
1057 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1058 MDString *ID = *I;
1059 if (ErrorNode[ID] && WarningNode[ID])
Bill Wendling75b3d682012-02-14 09:13:54 +00001060 HasErr = emitError("linking module flags '" + ID->getString() +
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001061 "': IDs have conflicting behaviors");
1062 }
1063
1064 // Early exit if we had an error.
1065 if (HasErr) return true;
1066
1067 // Get the destination's module flags ready for new operands.
1068 DstModFlags->dropAllReferences();
1069
1070 // Add all of the module flags to the destination module.
1071 DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes;
1072 for (SmallSetVector<MDString*, 16>::iterator
1073 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1074 MDString *ID = *I;
1075 if (OverrideNode[ID]) {
1076 DstModFlags->addOperand(OverrideNode[ID]);
1077 AddedNodes[ID].push_back(OverrideNode[ID]);
1078 } else if (ErrorNode[ID]) {
1079 DstModFlags->addOperand(ErrorNode[ID]);
1080 AddedNodes[ID].push_back(ErrorNode[ID]);
1081 } else if (WarningNode[ID]) {
1082 DstModFlags->addOperand(WarningNode[ID]);
1083 AddedNodes[ID].push_back(WarningNode[ID]);
1084 }
1085
1086 for (SmallSetVector<MDNode*, 8>::iterator
1087 II = RequireNodes[ID].begin(), IE = RequireNodes[ID].end();
1088 II != IE; ++II)
1089 DstModFlags->addOperand(*II);
1090 }
1091
1092 // Now check that all of the requirements have been satisfied.
1093 for (SmallSetVector<MDString*, 16>::iterator
1094 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1095 MDString *ID = *I;
1096 SmallSetVector<MDNode*, 8> &Set = RequireNodes[ID];
1097
1098 for (SmallSetVector<MDNode*, 8>::iterator
1099 II = Set.begin(), IE = Set.end(); II != IE; ++II) {
1100 MDNode *Node = *II;
1101 assert(isa<MDNode>(Node->getOperand(2)) &&
1102 "Module flag's third operand must be an MDNode!");
1103 MDNode *Val = cast<MDNode>(Node->getOperand(2));
1104
1105 MDString *ReqID = cast<MDString>(Val->getOperand(0));
1106 Value *ReqVal = Val->getOperand(1);
1107
1108 bool HasValue = false;
1109 for (SmallVectorImpl<MDNode*>::iterator
1110 RI = AddedNodes[ReqID].begin(), RE = AddedNodes[ReqID].end();
1111 RI != RE; ++RI) {
1112 MDNode *ReqNode = *RI;
1113 if (ReqNode->getOperand(2) == ReqVal) {
1114 HasValue = true;
1115 break;
1116 }
1117 }
1118
1119 if (!HasValue)
Bill Wendling75b3d682012-02-14 09:13:54 +00001120 HasErr = emitError("linking module flags '" + ReqID->getString() +
1121 "': does not have the required value");
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001122 }
1123 }
1124
1125 return HasErr;
1126}
Chris Lattner1afcace2011-07-09 17:41:24 +00001127
1128bool ModuleLinker::run() {
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001129 assert(DstM && "Null destination module");
1130 assert(SrcM && "Null source module");
Chris Lattner1afcace2011-07-09 17:41:24 +00001131
1132 // Inherit the target data from the source module if the destination module
1133 // doesn't have one already.
1134 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1135 DstM->setDataLayout(SrcM->getDataLayout());
1136
1137 // Copy the target triple from the source to dest if the dest's is empty.
1138 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1139 DstM->setTargetTriple(SrcM->getTargetTriple());
1140
1141 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1142 SrcM->getDataLayout() != DstM->getDataLayout())
1143 errs() << "WARNING: Linking two modules of different data layouts!\n";
1144 if (!SrcM->getTargetTriple().empty() &&
1145 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1146 errs() << "WARNING: Linking two modules of different target triples: ";
1147 if (!SrcM->getModuleIdentifier().empty())
1148 errs() << SrcM->getModuleIdentifier() << ": ";
1149 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1150 << DstM->getTargetTriple() << "'\n";
1151 }
1152
1153 // Append the module inline asm string.
1154 if (!SrcM->getModuleInlineAsm().empty()) {
1155 if (DstM->getModuleInlineAsm().empty())
1156 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1157 else
1158 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1159 SrcM->getModuleInlineAsm());
1160 }
1161
1162 // Update the destination module's dependent libraries list with the libraries
1163 // from the source module. There's no opportunity for duplicates here as the
1164 // Module ensures that duplicate insertions are discarded.
1165 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
1166 SI != SE; ++SI)
1167 DstM->addLibrary(*SI);
1168
1169 // If the source library's module id is in the dependent library list of the
1170 // destination library, remove it since that module is now linked in.
1171 StringRef ModuleId = SrcM->getModuleIdentifier();
1172 if (!ModuleId.empty())
1173 DstM->removeLibrary(sys::path::stem(ModuleId));
Chris Lattner1afcace2011-07-09 17:41:24 +00001174
1175 // Loop over all of the linked values to compute type mappings.
1176 computeTypeMapping();
1177
1178 // Insert all of the globals in src into the DstM module... without linking
1179 // initializers (which could refer to functions not yet mapped over).
1180 for (Module::global_iterator I = SrcM->global_begin(),
1181 E = SrcM->global_end(); I != E; ++I)
1182 if (linkGlobalProto(I))
1183 return true;
1184
1185 // Link the functions together between the two modules, without doing function
1186 // bodies... this just adds external function prototypes to the DstM
1187 // function... We do this so that when we begin processing function bodies,
1188 // all of the global values that may be referenced are available in our
1189 // ValueMap.
1190 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1191 if (linkFunctionProto(I))
1192 return true;
1193
1194 // If there were any aliases, link them now.
1195 for (Module::alias_iterator I = SrcM->alias_begin(),
1196 E = SrcM->alias_end(); I != E; ++I)
1197 if (linkAliasProto(I))
1198 return true;
1199
1200 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1201 linkAppendingVarInit(AppendingVars[i]);
1202
1203 // Update the initializers in the DstM module now that all globals that may
1204 // be referenced are in DstM.
1205 linkGlobalInits();
1206
1207 // Link in the function bodies that are defined in the source module into
1208 // DstM.
1209 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattner2b28a742011-10-14 22:17:46 +00001210 // Skip if not linking from source.
1211 if (DoNotLinkFromSource.count(SF)) continue;
1212
1213 // Skip if no body (function is external) or materialize.
1214 if (SF->isDeclaration()) {
1215 if (!SF->isMaterializable())
1216 continue;
1217 if (SF->Materialize(&ErrorMsg))
1218 return true;
1219 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001220
1221 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1222 }
1223
1224 // Resolve all uses of aliases with aliasees.
1225 linkAliasBodies();
1226
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001227 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel211da8f2011-08-04 19:44:28 +00001228 // after linking GlobalValues so that MDNodes that reference GlobalValues
1229 // are properly remapped.
1230 linkNamedMDNodes();
1231
Bill Wendlingd34cb1e2012-02-11 11:38:06 +00001232 // Merge the module flags into the DstM module.
1233 if (linkModuleFlagsMetadata())
1234 return true;
1235
Tanya Lattner9af37a32011-11-02 00:24:56 +00001236 // Process vector of lazily linked in functions.
1237 bool LinkedInAnyFunctions;
1238 do {
1239 LinkedInAnyFunctions = false;
1240
1241 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1242 E = LazilyLinkFunctions.end(); I != E; ++I) {
1243 if (!*I)
1244 continue;
1245
1246 Function *SF = *I;
1247 Function *DF = cast<Function>(ValueMap[SF]);
1248
1249 if (!DF->use_empty()) {
1250
1251 // Materialize if necessary.
1252 if (SF->isDeclaration()) {
1253 if (!SF->isMaterializable())
1254 continue;
1255 if (SF->Materialize(&ErrorMsg))
1256 return true;
1257 }
1258
1259 // Link in function body.
1260 linkFunctionBody(DF, SF);
1261
1262 // "Remove" from vector by setting the element to 0.
1263 *I = 0;
1264
1265 // Set flag to indicate we may have more functions to lazily link in
1266 // since we linked in a function.
1267 LinkedInAnyFunctions = true;
1268 }
1269 }
1270 } while (LinkedInAnyFunctions);
1271
1272 // Remove any prototypes of functions that were not actually linked in.
1273 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1274 E = LazilyLinkFunctions.end(); I != E; ++I) {
1275 if (!*I)
1276 continue;
1277
1278 Function *SF = *I;
1279 Function *DF = cast<Function>(ValueMap[SF]);
1280 if (DF->use_empty())
1281 DF->eraseFromParent();
1282 }
1283
Chris Lattner1afcace2011-07-09 17:41:24 +00001284 // Now that all of the types from the source are used, resolve any structs
1285 // copied over to the dest that didn't exist there.
1286 TypeMap.linkDefinedTypeBodies();
1287
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +00001288 return false;
1289}
Chris Lattner52f7e902001-10-13 07:03:50 +00001290
Chris Lattner1afcace2011-07-09 17:41:24 +00001291//===----------------------------------------------------------------------===//
1292// LinkModules entrypoint.
1293//===----------------------------------------------------------------------===//
1294
Chris Lattner52f7e902001-10-13 07:03:50 +00001295// LinkModules - This function links two modules together, with the resulting
1296// left module modified to be the composite of the two input modules. If an
1297// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
Chris Lattner5c377c52001-10-14 23:29:15 +00001298// the problem. Upon failure, the Dest module could be in a modified state, and
1299// shouldn't be relied on to be consistent.
Tanya Lattnerf1f1a4f2011-10-11 00:24:54 +00001300bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1301 std::string *ErrorMsg) {
1302 ModuleLinker TheLinker(Dest, Src, Mode);
Chris Lattner1afcace2011-07-09 17:41:24 +00001303 if (TheLinker.run()) {
1304 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
Reid Spencer619f0242007-02-04 04:43:17 +00001305 return true;
Chris Lattner5a837de2004-08-04 07:44:58 +00001306 }
Chris Lattner1afcace2011-07-09 17:41:24 +00001307
Chris Lattner52f7e902001-10-13 07:03:50 +00001308 return false;
1309}