blob: 1f4c3c13238e770d6904987ea16a72266a4d47dd [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
Chandler Carruth6cc07df2014-03-06 03:42:23 +000014#include "llvm/Linker/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>
David Majnemer82d6ff62014-06-27 18:38:12 +000027#include <tuple>
Reid Spencer361e5132004-11-12 20:37:43 +000028using namespace llvm;
29
Eli Benderskye17f3702014-02-06 18:01:56 +000030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000031//===----------------------------------------------------------------------===//
32// TypeMap implementation.
33//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000034
Chris Lattnereee6f992008-06-16 21:00:18 +000035namespace {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000036 typedef SmallPtrSet<StructType*, 32> TypeSet;
37
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000038class TypeMapTy : public ValueMapTypeRemapper {
39 /// MappedTypes - This is a mapping from a source type to a destination type
40 /// to use.
41 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000042
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000043 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
44 /// we speculatively add types to MappedTypes, but keep track of them here in
45 /// case we need to roll back.
46 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000047
Chris Lattner5e3bd972011-12-20 00:03:52 +000048 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
49 /// source module that are mapped to an opaque struct in the destination
50 /// module.
51 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000052
Chris Lattner5e3bd972011-12-20 00:03:52 +000053 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
54 /// destination modules who are getting a body from the source module.
55 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000056
Chris Lattner56cdea62008-06-16 23:06:51 +000057public:
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000058 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
59
60 TypeSet &DstStructTypesSet;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000061 /// addTypeMapping - Indicate that the specified type in the destination
62 /// module is conceptually equivalent to the specified type in the source
63 /// module.
64 void addTypeMapping(Type *DstTy, Type *SrcTy);
65
66 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
67 /// module from a type definition in the source module.
68 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000069
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000070 /// get - Return the mapped type to use for the specified input type from the
71 /// source module.
72 Type *get(Type *SrcTy);
73
74 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
75
Bill Wendlingb6af2f32012-03-22 20:28:27 +000076 /// dump - Dump out the type map for debugging purposes.
77 void dump() const {
78 for (DenseMap<Type*, Type*>::const_iterator
79 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
80 dbgs() << "TypeMap: ";
81 I->first->dump();
82 dbgs() << " => ";
83 I->second->dump();
84 dbgs() << '\n';
85 }
86 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000088private:
89 Type *getImpl(Type *T);
90 /// remapType - Implement the ValueMapTypeRemapper interface.
Craig Topper85482992014-03-05 07:52:44 +000091 Type *remapType(Type *SrcTy) override {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000092 return get(SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000093 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000095 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000096};
97}
98
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000099void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
100 Type *&Entry = MappedTypes[SrcTy];
101 if (Entry) return;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000102
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000103 if (DstTy == SrcTy) {
104 Entry = DstTy;
105 return;
106 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000107
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000108 // Check to see if these types are recursively isomorphic and establish a
109 // mapping between them if so.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000110 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000111 // Oops, they aren't isomorphic. Just discard this request by rolling out
112 // any speculative mappings we've established.
113 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
114 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendlingd48b7782012-02-28 04:01:21 +0000115 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000116 SpeculativeTypes.clear();
117}
Chris Lattnereee6f992008-06-16 21:00:18 +0000118
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000119/// areTypesIsomorphic - Recursively walk this pair of types, returning true
120/// if they are isomorphic, false if they are not.
121bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
122 // Two types with differing kinds are clearly not isomorphic.
123 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000124
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000125 // If we have an entry in the MappedTypes table, then we have our answer.
126 Type *&Entry = MappedTypes[SrcTy];
127 if (Entry)
128 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000129
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000130 // Two identical types are clearly isomorphic. Remember this
131 // non-speculatively.
132 if (DstTy == SrcTy) {
133 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000134 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000135 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000136
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000137 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000139 // If this is an opaque struct type, special case it.
140 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
141 // Mapping an opaque type to any struct, just keep the dest struct.
142 if (SSTy->isOpaque()) {
143 Entry = DstTy;
144 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000145 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000146 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000147
Chris Lattner5e3bd972011-12-20 00:03:52 +0000148 // Mapping a non-opaque source type to an opaque dest. If this is the first
149 // type that we're mapping onto this destination type then we succeed. Keep
150 // the dest, but fill it in later. This doesn't need to be speculative. If
151 // this is the second (different) type that we're trying to map onto the
152 // same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000153 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000154 // We can only map one source type onto the opaque destination type.
155 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
156 return false;
157 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000158 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000159 return true;
160 }
161 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000162
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000163 // If the number of subtypes disagree between the two types, then we fail.
164 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000165 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000166
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000167 // Fail if any of the extra properties (e.g. array size) of the type disagree.
168 if (isa<IntegerType>(DstTy))
169 return false; // bitwidth disagrees.
170 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
171 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
172 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000174 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
175 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
176 return false;
177 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
178 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000179 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000180 DSTy->isPacked() != SSTy->isPacked())
181 return false;
182 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
183 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
184 return false;
185 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000186 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000187 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000188 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000189
190 // Otherwise, we speculate that these two types will line up and recursively
191 // check the subelements.
192 Entry = DstTy;
193 SpeculativeTypes.push_back(SrcTy);
194
Bill Wendlingd48b7782012-02-28 04:01:21 +0000195 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
196 if (!areTypesIsomorphic(DstTy->getContainedType(i),
197 SrcTy->getContainedType(i)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000198 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000199
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000200 // If everything seems to have lined up, then everything is great.
201 return true;
202}
203
204/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
205/// module from a type definition in the source module.
206void TypeMapTy::linkDefinedTypeBodies() {
207 SmallVector<Type*, 16> Elements;
208 SmallString<16> TmpName;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000209
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000210 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner5e3bd972011-12-20 00:03:52 +0000211 // entries to the SrcDefinitionsToResolve vector.
212 while (!SrcDefinitionsToResolve.empty()) {
213 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000214 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000215
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000216 // TypeMap is a many-to-one mapping, if there were multiple types that
217 // provide a body for DstSTy then previous iterations of this loop may have
218 // already handled it. Just ignore this case.
219 if (!DstSTy->isOpaque()) continue;
220 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000221
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000222 // Map the body of the source type over to a new body for the dest type.
223 Elements.resize(SrcSTy->getNumElements());
224 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
225 Elements[i] = getImpl(SrcSTy->getElementType(i));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000226
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000227 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000228
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000229 // If DstSTy has no name or has a longer name than STy, then viciously steal
230 // STy's name.
231 if (!SrcSTy->hasName()) continue;
232 StringRef SrcName = SrcSTy->getName();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000233
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000234 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
235 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
236 SrcSTy->setName("");
237 DstSTy->setName(TmpName.str());
238 TmpName.clear();
239 }
240 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000241
Chris Lattner5e3bd972011-12-20 00:03:52 +0000242 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000243}
244
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000245/// get - Return the mapped type to use for the specified input type from the
246/// source module.
247Type *TypeMapTy::get(Type *Ty) {
248 Type *Result = getImpl(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000249
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000250 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000251 if (!SrcDefinitionsToResolve.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000252 linkDefinedTypeBodies();
253 return Result;
254}
255
256/// getImpl - This is the recursive version of get().
257Type *TypeMapTy::getImpl(Type *Ty) {
258 // If we already have an entry for this type, return it.
259 Type **Entry = &MappedTypes[Ty];
260 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000261
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000262 // If this is not a named struct type, then just map all of the elements and
263 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000264 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000265 // If there are no element types to map, then the type is itself. This is
266 // true for the anonymous {} struct, things like 'float', integers, etc.
267 if (Ty->getNumContainedTypes() == 0)
268 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000269
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000270 // Remap all of the elements, keeping track of whether any of them change.
271 bool AnyChange = false;
272 SmallVector<Type*, 4> ElementTypes;
273 ElementTypes.resize(Ty->getNumContainedTypes());
274 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
275 ElementTypes[i] = getImpl(Ty->getContainedType(i));
276 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
277 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000278
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000279 // If we found our type while recursively processing stuff, just use it.
280 Entry = &MappedTypes[Ty];
281 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000282
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000283 // If all of the element types mapped directly over, then the type is usable
284 // as-is.
285 if (!AnyChange)
286 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000287
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000288 // Otherwise, rebuild a modified type.
289 switch (Ty->getTypeID()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000290 default: llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000291 case Type::ArrayTyID:
292 return *Entry = ArrayType::get(ElementTypes[0],
293 cast<ArrayType>(Ty)->getNumElements());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000294 case Type::VectorTyID:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000295 return *Entry = VectorType::get(ElementTypes[0],
296 cast<VectorType>(Ty)->getNumElements());
297 case Type::PointerTyID:
298 return *Entry = PointerType::get(ElementTypes[0],
299 cast<PointerType>(Ty)->getAddressSpace());
300 case Type::FunctionTyID:
301 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000302 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000303 cast<FunctionType>(Ty)->isVarArg());
304 case Type::StructTyID:
305 // Note that this is only reached for anonymous structs.
306 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
307 cast<StructType>(Ty)->isPacked());
308 }
309 }
310
311 // Otherwise, this is an unmapped named struct. If the struct can be directly
312 // mapped over, just use it as-is. This happens in a case when the linked-in
313 // module has something like:
314 // %T = type {%T*, i32}
315 // @GV = global %T* null
316 // where T does not exist at all in the destination module.
317 //
318 // The other case we watch for is when the type is not in the destination
319 // module, but that it has to be rebuilt because it refers to something that
320 // is already mapped. For example, if the destination module has:
321 // %A = type { i32 }
322 // and the source module has something like
323 // %A' = type { i32 }
324 // %B = type { %A'* }
325 // @GV = global %B* null
326 // then we want to create a new type: "%B = type { %A*}" and have it take the
327 // pristine "%B" name from the source module.
328 //
329 // To determine which case this is, we have to recursively walk the type graph
330 // speculating that we'll be able to reuse it unmodified. Only if this is
331 // safe would we map the entire thing over. Because this is an optimization,
332 // and is not required for the prettiness of the linked module, we just skip
333 // it and always rebuild a type here.
334 StructType *STy = cast<StructType>(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000335
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000336 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000337 if (STy->isOpaque()) {
338 // A named structure type from src module is used. Add it to the Set of
339 // identified structs in the destination module.
340 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000341 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000342 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000343
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000344 // Otherwise we create a new type and resolve its body later. This will be
345 // resolved by the top level of get().
Chris Lattner5e3bd972011-12-20 00:03:52 +0000346 SrcDefinitionsToResolve.push_back(STy);
347 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000348 // A new identified structure type was created. Add it to the set of
349 // identified structs in the destination module.
350 DstStructTypesSet.insert(DTy);
Chris Lattner5e3bd972011-12-20 00:03:52 +0000351 DstResolvedOpaqueTypes.insert(DTy);
352 return *Entry = DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353}
354
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000355//===----------------------------------------------------------------------===//
356// ModuleLinker implementation.
357//===----------------------------------------------------------------------===//
358
359namespace {
James Molloyf6f121e2013-05-28 15:17:05 +0000360 class ModuleLinker;
361
362 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
363 /// linked on the fly. This speeds up linking for modules with many
364 /// lazily linked functions of which few get used.
365 class ValueMaterializerTy : public ValueMaterializer {
366 TypeMapTy &TypeMap;
367 Module *DstM;
368 std::vector<Function*> &LazilyLinkFunctions;
369 public:
370 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
371 std::vector<Function*> &LazilyLinkFunctions) :
372 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
373 LazilyLinkFunctions(LazilyLinkFunctions) {
374 }
375
Craig Topper85482992014-03-05 07:52:44 +0000376 Value *materializeValueFor(Value *V) override;
James Molloyf6f121e2013-05-28 15:17:05 +0000377 };
378
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000379 /// ModuleLinker - This is an implementation class for the LinkModules
380 /// function, which is the entrypoint for this file.
381 class ModuleLinker {
382 Module *DstM, *SrcM;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000383
384 TypeMapTy TypeMap;
James Molloyf6f121e2013-05-28 15:17:05 +0000385 ValueMaterializerTy ValMaterializer;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000386
387 /// ValueMap - Mapping of values from what they used to be in Src, to what
388 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
389 /// some overhead due to the use of Value handles which the Linker doesn't
390 /// actually need, but this allows us to reuse the ValueMapper code.
391 ValueToValueMapTy ValueMap;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000392
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000393 struct AppendingVarInfo {
394 GlobalVariable *NewGV; // New aggregate global in dest module.
395 Constant *DstInit; // Old initializer from dest module.
396 Constant *SrcInit; // Old initializer from src module.
397 };
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000398
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000399 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000400
Tanya Lattnercbb91402011-10-11 00:24:54 +0000401 unsigned Mode; // Mode to treat source module.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000402
Tanya Lattnercbb91402011-10-11 00:24:54 +0000403 // Set of items not to link in from source.
404 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000405
Tanya Lattner0a48b872011-11-02 00:24:56 +0000406 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000407 std::vector<Function*> LazilyLinkFunctions;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000408
409 bool SuppressWarnings;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000410
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000411 public:
412 std::string ErrorMsg;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000413
414 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
415 bool SuppressWarnings=false)
416 : DstM(dstM), SrcM(srcM), TypeMap(Set),
417 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
418 SuppressWarnings(SuppressWarnings) {}
419
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000420 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000421
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000422 private:
423 /// emitError - Helper method for setting a message and returning an error
424 /// code.
425 bool emitError(const Twine &Message) {
426 ErrorMsg = Message.str();
Chris Lattner99953022008-06-16 18:27:53 +0000427 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000428 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000429
David Majnemerdad0a642014-06-27 18:19:56 +0000430 bool getComdatLeader(Module *M, StringRef ComdatName,
431 const GlobalVariable *&GVar);
432 bool computeResultingSelectionKind(StringRef ComdatName,
433 Comdat::SelectionKind Src,
434 Comdat::SelectionKind Dst,
435 Comdat::SelectionKind &Result,
436 bool &LinkFromSrc);
437 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
438 ComdatsChosen;
439 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
440 bool &LinkFromSrc);
441
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000442 /// getLinkageResult - This analyzes the two global values and determines
443 /// what the result will look like in the destination module.
444 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000445 GlobalValue::LinkageTypes &LT,
446 GlobalValue::VisibilityTypes &Vis,
447 bool &LinkFromSrc);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000448
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000449 /// getLinkedToGlobal - Given a global in the source module, return the
450 /// global in the destination module that is being linked to, if any.
451 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
452 // If the source has no name it can't link. If it has local linkage,
453 // there is no name match-up going on.
454 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000455 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000456
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000457 // Otherwise see if we have a match in the destination module's symtab.
458 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
Craig Topper2617dcc2014-04-15 06:32:26 +0000459 if (!DGV) return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000460
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 // If we found a global with the same name in the dest module, but it has
462 // internal linkage, we are really not doing any linkage here.
463 if (DGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000464 return nullptr;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000465
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000466 // Otherwise, we do in fact link to the destination global.
467 return DGV;
468 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000469
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000470 void computeTypeMapping();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000471
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000472 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
473 bool linkGlobalProto(GlobalVariable *SrcGV);
474 bool linkFunctionProto(Function *SrcF);
475 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendling66f02412012-02-11 11:38:06 +0000476 bool linkModuleFlagsMetadata();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000477
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000478 void linkAppendingVarInit(const AppendingVarInfo &AVI);
479 void linkGlobalInits();
480 void linkFunctionBody(Function *Dst, Function *Src);
481 void linkAliasBodies();
482 void linkNamedMDNodes();
483 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000484}
485
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000486/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer90246aa2007-02-04 04:29:21 +0000487/// in the symbol table. This is good for all clients except for us. Go
488/// through the trouble to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000489static void forceRenaming(GlobalValue *GV, StringRef Name) {
490 // If the global doesn't force its name or if it already has the right name,
491 // there is nothing for us to do.
492 if (GV->hasLocalLinkage() || GV->getName() == Name)
493 return;
494
495 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000496
497 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000498 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000499 GV->takeName(ConflictGV);
500 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000501 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000502 } else {
503 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000504 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000505}
Reid Spencer90246aa2007-02-04 04:29:21 +0000506
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000507/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000508/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000509static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000510 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000511 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000512 unsigned Alignment;
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000513 if (DestGO)
514 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000515
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000516 DestGV->copyAttributesFrom(SrcGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000517
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000518 if (DestGO)
519 DestGO->setAlignment(Alignment);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000520
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000521 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000522}
523
Rafael Espindola23f8d642012-01-05 23:02:01 +0000524static bool isLessConstraining(GlobalValue::VisibilityTypes a,
525 GlobalValue::VisibilityTypes b) {
526 if (a == GlobalValue::HiddenVisibility)
527 return false;
528 if (b == GlobalValue::HiddenVisibility)
529 return true;
530 if (a == GlobalValue::ProtectedVisibility)
531 return false;
532 if (b == GlobalValue::ProtectedVisibility)
533 return true;
534 return false;
535}
536
James Molloyf6f121e2013-05-28 15:17:05 +0000537Value *ValueMaterializerTy::materializeValueFor(Value *V) {
538 Function *SF = dyn_cast<Function>(V);
539 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000540 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000541
542 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
543 SF->getLinkage(), SF->getName(), DstM);
544 copyGVAttributes(DF, SF);
545
546 LazilyLinkFunctions.push_back(SF);
547 return DF;
548}
549
David Majnemerdad0a642014-06-27 18:19:56 +0000550bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
551 const GlobalVariable *&GVar) {
552 const GlobalValue *GVal = M->getNamedValue(ComdatName);
553 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
554 GVal = GA->getBaseObject();
555 if (!GVal)
556 // We cannot resolve the size of the aliasee yet.
557 return emitError("Linking COMDATs named '" + ComdatName +
558 "': COMDAT key involves incomputable alias size.");
559 }
560
561 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
562 if (!GVar)
563 return emitError(
564 "Linking COMDATs named '" + ComdatName +
565 "': GlobalVariable required for data dependent selection!");
566
567 return false;
568}
569
570bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
571 Comdat::SelectionKind Src,
572 Comdat::SelectionKind Dst,
573 Comdat::SelectionKind &Result,
574 bool &LinkFromSrc) {
575 // The ability to mix Comdat::SelectionKind::Any with
576 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
577 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
578 Dst == Comdat::SelectionKind::Largest;
579 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
580 Src == Comdat::SelectionKind::Largest;
581 if (DstAnyOrLargest && SrcAnyOrLargest) {
582 if (Dst == Comdat::SelectionKind::Largest ||
583 Src == Comdat::SelectionKind::Largest)
584 Result = Comdat::SelectionKind::Largest;
585 else
586 Result = Comdat::SelectionKind::Any;
587 } else if (Src == Dst) {
588 Result = Dst;
589 } else {
590 return emitError("Linking COMDATs named '" + ComdatName +
591 "': invalid selection kinds!");
592 }
593
594 switch (Result) {
595 case Comdat::SelectionKind::Any:
596 // Go with Dst.
597 LinkFromSrc = false;
598 break;
599 case Comdat::SelectionKind::NoDuplicates:
600 return emitError("Linking COMDATs named '" + ComdatName +
601 "': noduplicates has been violated!");
602 case Comdat::SelectionKind::ExactMatch:
603 case Comdat::SelectionKind::Largest:
604 case Comdat::SelectionKind::SameSize: {
605 const GlobalVariable *DstGV;
606 const GlobalVariable *SrcGV;
607 if (getComdatLeader(DstM, ComdatName, DstGV) ||
608 getComdatLeader(SrcM, ComdatName, SrcGV))
609 return true;
610
611 const DataLayout *DstDL = DstM->getDataLayout();
612 const DataLayout *SrcDL = SrcM->getDataLayout();
613 if (!DstDL || !SrcDL) {
614 return emitError(
615 "Linking COMDATs named '" + ComdatName +
616 "': can't do size dependent selection without DataLayout!");
617 }
618 uint64_t DstSize =
619 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
620 uint64_t SrcSize =
621 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
622 if (Result == Comdat::SelectionKind::ExactMatch) {
623 if (SrcGV->getInitializer() != DstGV->getInitializer())
624 return emitError("Linking COMDATs named '" + ComdatName +
625 "': ExactMatch violated!");
626 LinkFromSrc = false;
627 } else if (Result == Comdat::SelectionKind::Largest) {
628 LinkFromSrc = SrcSize > DstSize;
629 } else if (Result == Comdat::SelectionKind::SameSize) {
630 if (SrcSize != DstSize)
631 return emitError("Linking COMDATs named '" + ComdatName +
632 "': SameSize violated!");
633 LinkFromSrc = false;
634 } else {
635 llvm_unreachable("unknown selection kind");
636 }
637 break;
638 }
639 }
640
641 return false;
642}
643
644bool ModuleLinker::getComdatResult(const Comdat *SrcC,
645 Comdat::SelectionKind &Result,
646 bool &LinkFromSrc) {
647 StringRef ComdatName = SrcC->getName();
648 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
649 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000650
651 if (DstCI == ComdatSymTab.end())
652 return false;
653
654 const Comdat *DstC = &DstCI->second;
655 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
656 Comdat::SelectionKind DSK = DstC->getSelectionKind();
657 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
658 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000659}
James Molloyf6f121e2013-05-28 15:17:05 +0000660
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000661/// getLinkageResult - This analyzes the two global values and determines what
Chris Lattnerfc61de32004-12-03 22:18:41 +0000662/// the result will look like in the destination module. In particular, it
Rafael Espindola23f8d642012-01-05 23:02:01 +0000663/// computes the resultant linkage type and visibility, computes whether the
664/// global in the source should be copied over to the destination (replacing
665/// the existing one), and computes whether this linkage is an error or not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000666bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000667 GlobalValue::LinkageTypes &LT,
668 GlobalValue::VisibilityTypes &Vis,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000669 bool &LinkFromSrc) {
670 assert(Dest && "Must have two globals being queried");
671 assert(!Src->hasLocalLinkage() &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000672 "If Src has internal linkage, Dest shouldn't be set!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000673
Peter Collingbourne8bb15d82011-10-30 17:46:34 +0000674 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
Chris Lattner0c134b52011-07-14 20:23:05 +0000675 bool DestIsDeclaration = Dest->isDeclaration();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000676
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000677 if (SrcIsDeclaration) {
Anton Korobeynikov1f93c502008-03-10 22:33:22 +0000678 // If Src is external or if both Src & Dest are external.. Just link the
Chris Lattnerfc61de32004-12-03 22:18:41 +0000679 // external globals, we aren't adding anything.
Nico Rieck7157bb72014-01-14 15:22:47 +0000680 if (Src->hasDLLImportStorageClass()) {
681 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000682 if (DestIsDeclaration) {
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000683 LinkFromSrc = true;
684 LT = Src->getLinkage();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000685 }
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000686 } else if (Dest->hasExternalWeakLinkage()) {
Duncan Sands12da8ce2009-03-07 15:45:40 +0000687 // If the Dest is weak, use the source linkage.
Andrew Lenharthe06036d2006-12-15 17:35:32 +0000688 LinkFromSrc = true;
689 LT = Src->getLinkage();
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000690 } else {
691 LinkFromSrc = false;
692 LT = Dest->getLinkage();
693 }
Nico Rieck7157bb72014-01-14 15:22:47 +0000694 } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000695 // If Dest is external but Src is not:
696 LinkFromSrc = true;
697 LT = Src->getLinkage();
Duncan Sandsd725c992009-03-08 13:35:23 +0000698 } else if (Src->isWeakForLinker()) {
Dale Johannesence4396b2008-05-14 20:12:51 +0000699 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
700 // or DLL* linkage.
Chris Lattner184f1be2009-04-13 05:44:34 +0000701 if (Dest->hasExternalWeakLinkage() ||
702 Dest->hasAvailableExternallyLinkage() ||
703 (Dest->hasLinkOnceLinkage() &&
704 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
Chris Lattnerfc61de32004-12-03 22:18:41 +0000705 LinkFromSrc = true;
706 LT = Src->getLinkage();
707 } else {
708 LinkFromSrc = false;
709 LT = Dest->getLinkage();
710 }
Duncan Sandsd725c992009-03-08 13:35:23 +0000711 } else if (Dest->isWeakForLinker()) {
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000712 // At this point we know that Src has External* or DLL* linkage.
713 if (Src->hasExternalWeakLinkage()) {
714 LinkFromSrc = false;
715 LT = Dest->getLinkage();
716 } else {
717 LinkFromSrc = true;
718 LT = GlobalValue::ExternalLinkage;
719 }
Chris Lattnerfc61de32004-12-03 22:18:41 +0000720 } else {
Nico Rieck7157bb72014-01-14 15:22:47 +0000721 assert((Dest->hasExternalLinkage() || Dest->hasExternalWeakLinkage()) &&
722 (Src->hasExternalLinkage() || Src->hasExternalWeakLinkage()) &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000723 "Unexpected linkage type!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000724 return emitError("Linking globals named '" + Src->getName() +
Chris Lattnerfc61de32004-12-03 22:18:41 +0000725 "': symbol multiply defined!");
726 }
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000727
Rafael Espindola23f8d642012-01-05 23:02:01 +0000728 // Compute the visibility. We follow the rules in the System V Application
729 // Binary Interface.
Duncan P. N. Exon Smithb2becfd2014-05-07 22:55:46 +0000730 assert(!GlobalValue::isLocalLinkage(LT) &&
731 "Symbols with local linkage should not be merged");
Rafael Espindola23f8d642012-01-05 23:02:01 +0000732 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
733 Dest->getVisibility() : Src->getVisibility();
Chris Lattnerfc61de32004-12-03 22:18:41 +0000734 return false;
735}
Reid Spencer361e5132004-11-12 20:37:43 +0000736
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000737/// computeTypeMapping - Loop over all of the linked values to compute type
738/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
739/// we have two struct types 'Foo' but one got renamed when the module was
740/// loaded into the same LLVMContext.
741void ModuleLinker::computeTypeMapping() {
742 // Incorporate globals.
743 for (Module::global_iterator I = SrcM->global_begin(),
744 E = SrcM->global_end(); I != E; ++I) {
745 GlobalValue *DGV = getLinkedToGlobal(I);
Craig Topper2617dcc2014-04-15 06:32:26 +0000746 if (!DGV) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000747
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000748 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
749 TypeMap.addTypeMapping(DGV->getType(), I->getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000750 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000751 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000752
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000753 // Unify the element type of appending arrays.
754 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
755 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
756 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000757 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000758
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000759 // Incorporate functions.
760 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
761 if (GlobalValue *DGV = getLinkedToGlobal(I))
762 TypeMap.addTypeMapping(DGV->getType(), I->getType());
763 }
Bill Wendling7b464612012-02-27 22:34:19 +0000764
Bill Wendlingd48b7782012-02-28 04:01:21 +0000765 // Incorporate types by name, scanning all the types in the source module.
766 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000767 // example. When the source module got loaded into the same LLVMContext, if
768 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000769 TypeFinder SrcStructTypes;
770 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000771 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
772 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000773
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000774 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
775 StructType *ST = SrcStructTypes[i];
776 if (!ST->hasName()) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000777
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000778 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000779 size_t DotPos = ST->getName().rfind('.');
780 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000781 ST->getName().back() == '.' ||
782 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000783 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000784
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000785 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000786 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000787 // Don't use it if this actually came from the source module. They're in
788 // the same LLVMContext after all. Also don't use it unless the type is
789 // actually used in the destination module. This can happen in situations
790 // like this:
791 //
792 // Module A Module B
793 // -------- --------
794 // %Z = type { %A } %B = type { %C.1 }
795 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
796 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
797 // %C = type { i8* } %B.3 = type { %C.1 }
798 //
799 // When we link Module B with Module A, the '%B' in Module B is
800 // used. However, that would then use '%C.1'. But when we process '%C.1',
801 // we prefer to take the '%C' version. So we are then left with both
802 // '%C.1' and '%C' being used for the same types. This leads to some
803 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000804 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000805 TypeMap.addTypeMapping(DST, ST);
806 }
807
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000808 // Don't bother incorporating aliases, they aren't generally typed well.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000809
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000810 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000811 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000812 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000813}
814
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000815/// linkAppendingVarProto - If there were any appending global variables, link
816/// them together now. Return true on error.
817bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
818 GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000819
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000820 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
821 return emitError("Linking globals named '" + SrcGV->getName() +
822 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000823
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000824 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
825 ArrayType *SrcTy =
826 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
827 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000828
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000829 // Check to see that they two arrays agree on type.
830 if (EltTy != SrcTy->getElementType())
831 return emitError("Appending variables with different element types!");
832 if (DstGV->isConstant() != SrcGV->isConstant())
833 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000834
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000835 if (DstGV->getAlignment() != SrcGV->getAlignment())
836 return emitError(
837 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000838
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000839 if (DstGV->getVisibility() != SrcGV->getVisibility())
840 return emitError(
841 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000842
843 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
844 return emitError(
845 "Appending variables with different unnamed_addr need to be linked!");
846
Rafael Espindola64c1e182014-06-03 02:41:57 +0000847 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000848 return emitError(
849 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000850
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000851 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
852 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000853
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000854 // Create the new global variable.
855 GlobalVariable *NG =
856 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000857 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000858 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000859 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000860
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000861 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000862 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000863
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000864 AppendingVarInfo AVI;
865 AVI.NewGV = NG;
866 AVI.DstInit = DstGV->getInitializer();
867 AVI.SrcInit = SrcGV->getInitializer();
868 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000869
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000870 // Replace any uses of the two global variables with uses of the new
871 // global.
872 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000873
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000874 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
875 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000876
Tanya Lattnercbb91402011-10-11 00:24:54 +0000877 // Track the source variable so we don't try to link it.
878 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000879
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000880 return false;
881}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000882
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000883/// linkGlobalProto - Loop through the global variables in the src module and
884/// merge them into the dest module.
885bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
886 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000887 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolad4885da2013-09-04 14:05:09 +0000888 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000889
David Majnemerdad0a642014-06-27 18:19:56 +0000890 bool LinkFromSrc = false;
891 Comdat *DC = nullptr;
892 if (const Comdat *SC = SGV->getComdat()) {
893 Comdat::SelectionKind SK;
894 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
895 DC = DstM->getOrInsertComdat(SC->getName());
896 DC->setSelectionKind(SK);
897 }
898
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000899 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000900 if (!DC) {
901 // Concatenation of appending linkage variables is magic and handled later.
902 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
903 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000904
David Majnemerdad0a642014-06-27 18:19:56 +0000905 // Determine whether linkage of these two globals follows the source
906 // module's definition or the destination module's definition.
907 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
908 GlobalValue::VisibilityTypes NV;
909 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
910 return true;
911 NewVisibility = NV;
912 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Reid Spencer361e5132004-11-12 20:37:43 +0000913
David Majnemerdad0a642014-06-27 18:19:56 +0000914 // If we're not linking from the source, then keep the definition that we
915 // have.
916 if (!LinkFromSrc) {
917 // Special case for const propagation.
918 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
919 if (DGVar->isDeclaration() && SGV->isConstant() &&
920 !DGVar->isConstant())
921 DGVar->setConstant(true);
922
923 // Set calculated linkage, visibility and unnamed_addr.
924 DGV->setLinkage(NewLinkage);
925 DGV->setVisibility(*NewVisibility);
926 DGV->setUnnamedAddr(HasUnnamedAddr);
927 }
928 }
929
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000930 if (!LinkFromSrc) {
Chris Lattner0ead7a52008-07-14 07:23:24 +0000931 // Make sure to remember this mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000932 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000933
934 // Track the source global so that we don't attempt to copy it over when
Tanya Lattnercbb91402011-10-11 00:24:54 +0000935 // processing global initializers.
936 DoNotLinkFromSource.insert(SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000937
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000938 return false;
Chris Lattner0ead7a52008-07-14 07:23:24 +0000939 }
Reid Spencer361e5132004-11-12 20:37:43 +0000940 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000941
David Majnemerdad0a642014-06-27 18:19:56 +0000942 // If the Comdat this variable was inside of wasn't selected, skip it.
943 if (DC && !DGV && !LinkFromSrc) {
944 DoNotLinkFromSource.insert(SGV);
945 return false;
946 }
947
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000948 // No linking to be performed or linking from the source: simply create an
949 // identical version of the symbol over in the dest module... the
950 // initializer will be filled in later by LinkGlobalInits.
951 GlobalVariable *NewDGV =
952 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
Craig Topper2617dcc2014-04-15 06:32:26 +0000953 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
954 SGV->getName(), /*insertbefore*/nullptr,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000955 SGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000956 SGV->getType()->getAddressSpace());
957 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000958 copyGVAttributes(NewDGV, SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000959 if (NewVisibility)
960 NewDGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +0000961 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000962
David Majnemerdad0a642014-06-27 18:19:56 +0000963 if (DC)
964 NewDGV->setComdat(DC);
965
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000966 if (DGV) {
967 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
968 DGV->eraseFromParent();
969 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000971 // Make sure to remember this mapping.
972 ValueMap[SGV] = NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +0000973 return false;
974}
975
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000976/// linkFunctionProto - Link the function in the source module into the
977/// destination module if needed, setting up mapping information.
978bool ModuleLinker::linkFunctionProto(Function *SF) {
979 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +0000980 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolafd9a9412013-09-04 14:59:03 +0000981 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000982
David Majnemerdad0a642014-06-27 18:19:56 +0000983 bool LinkFromSrc = false;
984 Comdat *DC = nullptr;
985 if (const Comdat *SC = SF->getComdat()) {
986 Comdat::SelectionKind SK;
987 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
988 DC = DstM->getOrInsertComdat(SC->getName());
989 DC->setSelectionKind(SK);
990 }
991
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000992 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000993 if (!DC) {
994 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
995 GlobalValue::VisibilityTypes NV;
996 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
997 return true;
998 NewVisibility = NV;
999 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1000
1001 if (!LinkFromSrc) {
1002 // Set calculated linkage
1003 DGV->setLinkage(NewLinkage);
1004 DGV->setVisibility(*NewVisibility);
1005 DGV->setUnnamedAddr(HasUnnamedAddr);
1006 }
1007 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001008
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001009 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001010 // Make sure to remember this mapping.
1011 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001012
1013 // Track the function from the source module so we don't attempt to remap
Tanya Lattnercbb91402011-10-11 00:24:54 +00001014 // it.
1015 DoNotLinkFromSource.insert(SF);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001016
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001017 return false;
1018 }
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001019 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001020
James Molloyf6f121e2013-05-28 15:17:05 +00001021 // If the function is to be lazily linked, don't create it just yet.
1022 // The ValueMaterializerTy will deal with creating it if it's used.
1023 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1024 SF->hasAvailableExternallyLinkage())) {
1025 DoNotLinkFromSource.insert(SF);
1026 return false;
1027 }
1028
David Majnemerdad0a642014-06-27 18:19:56 +00001029 // If the Comdat this function was inside of wasn't selected, skip it.
1030 if (DC && !DGV && !LinkFromSrc) {
1031 DoNotLinkFromSource.insert(SF);
1032 return false;
1033 }
1034
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001035 // If there is no linkage to be performed or we are linking from the source,
1036 // bring SF over.
1037 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1038 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001039 copyGVAttributes(NewDF, SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001040 if (NewVisibility)
1041 NewDF->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +00001042 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001043
David Majnemerdad0a642014-06-27 18:19:56 +00001044 if (DC)
1045 NewDF->setComdat(DC);
1046
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001047 if (DGV) {
1048 // Any uses of DF need to change to NewDF, with cast.
1049 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1050 DGV->eraseFromParent();
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001051 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001052
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001053 ValueMap[SF] = NewDF;
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001054 return false;
1055}
1056
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001057/// LinkAliasProto - Set up prototypes for any aliases that come over from the
1058/// source module.
1059bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1060 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001061 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001062 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
Rafael Espindola23f8d642012-01-05 23:02:01 +00001063
David Majnemerdad0a642014-06-27 18:19:56 +00001064 bool LinkFromSrc = false;
1065 Comdat *DC = nullptr;
1066 if (const Comdat *SC = SGA->getComdat()) {
1067 Comdat::SelectionKind SK;
1068 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1069 DC = DstM->getOrInsertComdat(SC->getName());
1070 DC->setSelectionKind(SK);
1071 }
1072
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001073 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001074 if (!DC) {
1075 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1076 GlobalValue::VisibilityTypes NV;
1077 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1078 return true;
1079 NewVisibility = NV;
1080 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1081
1082 if (!LinkFromSrc) {
1083 // Set calculated linkage.
1084 DGV->setLinkage(NewLinkage);
1085 DGV->setVisibility(*NewVisibility);
1086 DGV->setUnnamedAddr(HasUnnamedAddr);
1087 }
1088 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001089
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001090 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001091 // Make sure to remember this mapping.
1092 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001093
Tanya Lattnercbb91402011-10-11 00:24:54 +00001094 // Track the alias from the source module so we don't attempt to remap it.
1095 DoNotLinkFromSource.insert(SGA);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001096
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001097 return false;
1098 }
1099 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001100
David Majnemerdad0a642014-06-27 18:19:56 +00001101 // If the Comdat this alias was inside of wasn't selected, skip it.
1102 if (DC && !DGV && !LinkFromSrc) {
1103 DoNotLinkFromSource.insert(SGA);
1104 return false;
1105 }
1106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001107 // If there is no linkage to be performed or we're linking from the source,
1108 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +00001109 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001110 auto *NewDA =
1111 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1112 SGA->getLinkage(), SGA->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001113 copyGVAttributes(NewDA, SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001114 if (NewVisibility)
1115 NewDA->setVisibility(*NewVisibility);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001116 NewDA->setUnnamedAddr(HasUnnamedAddr);
Reid Spencer361e5132004-11-12 20:37:43 +00001117
Rafael Espindola64c1e182014-06-03 02:41:57 +00001118 if (DGV) {
1119 // Any uses of DGV need to change to NewDA, with cast.
1120 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1121 DGV->eraseFromParent();
1122 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001124 ValueMap[SGA] = NewDA;
1125 return false;
1126}
1127
Chris Lattner00245f42012-01-24 13:41:11 +00001128static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001129 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1130
1131 for (unsigned i = 0; i != NumElements; ++i)
1132 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001133}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001134
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001135void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1136 // Merge the initializer.
1137 SmallVector<Constant*, 16> Elements;
Chris Lattner00245f42012-01-24 13:41:11 +00001138 getArrayElements(AVI.DstInit, Elements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001139
James Molloyf6f121e2013-05-28 15:17:05 +00001140 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Chris Lattner00245f42012-01-24 13:41:11 +00001141 getArrayElements(SrcInit, Elements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001142
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001143 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1144 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
1145}
1146
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001147/// linkGlobalInits - Update the initializers in the Dest module now that all
1148/// globals that may be referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001149void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +00001150 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001151 for (Module::const_global_iterator I = SrcM->global_begin(),
1152 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001153
Tanya Lattnercbb91402011-10-11 00:24:54 +00001154 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001155 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1156
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001157 // Grab destination global variable.
1158 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1159 // Figure out what the initializer looks like in the dest module.
1160 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001161 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001162 }
Reid Spencer361e5132004-11-12 20:37:43 +00001163}
1164
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001165/// linkFunctionBody - Copy the source function over into the dest function and
1166/// fix up references to values. At this point we know that Dest is an external
1167/// function, and that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001168void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1169 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001170
Chris Lattner7391dde2004-11-16 17:12:38 +00001171 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001172 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001173 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +00001174 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001175 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001176
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001177 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +00001178 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001179 }
1180
Tanya Lattnercbb91402011-10-11 00:24:54 +00001181 if (Mode == Linker::DestroySource) {
1182 // Splice the body of the source function into the dest function.
1183 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001184
Tanya Lattnercbb91402011-10-11 00:24:54 +00001185 // At this point, all of the instructions and values of the function are now
1186 // copied over. The only problem is that they are still referencing values in
1187 // the Source function as operands. Loop through all of the operands of the
1188 // functions and patch them up to point to the local versions.
1189 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1190 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
James Molloyf6f121e2013-05-28 15:17:05 +00001191 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1192 &TypeMap, &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001193
Tanya Lattnercbb91402011-10-11 00:24:54 +00001194 } else {
1195 // Clone the body of the function into the dest function.
1196 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Craig Topper2617dcc2014-04-15 06:32:26 +00001197 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
James Molloyf6f121e2013-05-28 15:17:05 +00001198 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +00001199 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001200
Chris Lattner7391dde2004-11-16 17:12:38 +00001201 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001202 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1203 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001204 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001205
Reid Spencer361e5132004-11-12 20:37:43 +00001206}
1207
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001208/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001209void ModuleLinker::linkAliasBodies() {
1210 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001211 I != E; ++I) {
1212 if (DoNotLinkFromSource.count(I))
1213 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001214 if (Constant *Aliasee = I->getAliasee()) {
1215 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001216 Constant *Val =
1217 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Rafael Espindola64c1e182014-06-03 02:41:57 +00001218 DA->setAliasee(Val);
David Chisnall2c4a34a2010-01-09 16:27:31 +00001219 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001220 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001221}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001222
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001223/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001224/// module.
1225void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001226 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001227 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1228 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001229 // Don't link module flags here. Do them separately.
1230 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001231 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1232 // Add Src elements into Dest node.
1233 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1234 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001235 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001236 }
1237}
Bill Wendling66f02412012-02-11 11:38:06 +00001238
Bill Wendling66f02412012-02-11 11:38:06 +00001239/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1240/// module.
1241bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001242 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001243 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1244 if (!SrcModFlags) return false;
1245
Bill Wendling66f02412012-02-11 11:38:06 +00001246 // If the destination module doesn't have module flags yet, then just copy
1247 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001248 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001249 if (DstModFlags->getNumOperands() == 0) {
1250 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1251 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1252
1253 return false;
1254 }
1255
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001256 // First build a map of the existing module flags and requirements.
1257 DenseMap<MDString*, MDNode*> Flags;
1258 SmallSetVector<MDNode*, 16> Requirements;
1259 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1260 MDNode *Op = DstModFlags->getOperand(I);
1261 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1262 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001263
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001264 if (Behavior->getZExtValue() == Module::Require) {
1265 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1266 } else {
1267 Flags[ID] = Op;
1268 }
Bill Wendling66f02412012-02-11 11:38:06 +00001269 }
1270
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001271 // Merge in the flags from the source module, and also collect its set of
1272 // requirements.
1273 bool HasErr = false;
1274 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1275 MDNode *SrcOp = SrcModFlags->getOperand(I);
1276 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1277 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1278 MDNode *DstOp = Flags.lookup(ID);
1279 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001280
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001281 // If this is a requirement, add it and continue.
1282 if (SrcBehaviorValue == Module::Require) {
1283 // If the destination module does not already have this requirement, add
1284 // it.
1285 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1286 DstModFlags->addOperand(SrcOp);
1287 }
1288 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001289 }
1290
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001291 // If there is no existing flag with this ID, just add it.
1292 if (!DstOp) {
1293 Flags[ID] = SrcOp;
1294 DstModFlags->addOperand(SrcOp);
1295 continue;
1296 }
1297
1298 // Otherwise, perform a merge.
1299 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1300 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1301
1302 // If either flag has override behavior, handle it first.
1303 if (DstBehaviorValue == Module::Override) {
1304 // Diagnose inconsistent flags which both have override behavior.
1305 if (SrcBehaviorValue == Module::Override &&
1306 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1307 HasErr |= emitError("linking module flags '" + ID->getString() +
1308 "': IDs have conflicting override values");
1309 }
1310 continue;
1311 } else if (SrcBehaviorValue == Module::Override) {
1312 // Update the destination flag to that of the source.
1313 DstOp->replaceOperandWith(0, SrcBehavior);
1314 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1315 continue;
1316 }
1317
1318 // Diagnose inconsistent merge behavior types.
1319 if (SrcBehaviorValue != DstBehaviorValue) {
1320 HasErr |= emitError("linking module flags '" + ID->getString() +
1321 "': IDs have conflicting behaviors");
1322 continue;
1323 }
1324
1325 // Perform the merge for standard behavior types.
1326 switch (SrcBehaviorValue) {
1327 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001328 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001329 case Module::Error: {
1330 // Emit an error if the values differ.
1331 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1332 HasErr |= emitError("linking module flags '" + ID->getString() +
1333 "': IDs have conflicting values");
1334 }
1335 continue;
1336 }
1337 case Module::Warning: {
1338 // Emit a warning if the values differ.
1339 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001340 if (!SuppressWarnings) {
1341 errs() << "WARNING: linking module flags '" << ID->getString()
1342 << "': IDs have conflicting values";
1343 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001344 }
1345 continue;
1346 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001347 case Module::Append: {
1348 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1349 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1350 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1351 Value **VP, **Values = VP = new Value*[NumOps];
1352 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1353 *VP = DstValue->getOperand(i);
1354 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1355 *VP = SrcValue->getOperand(i);
1356 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1357 ArrayRef<Value*>(Values,
1358 NumOps)));
1359 delete[] Values;
1360 break;
1361 }
1362 case Module::AppendUnique: {
1363 SmallSetVector<Value*, 16> Elts;
1364 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1365 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1366 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1367 Elts.insert(DstValue->getOperand(i));
1368 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1369 Elts.insert(SrcValue->getOperand(i));
1370 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1371 ArrayRef<Value*>(Elts.begin(),
1372 Elts.end())));
1373 break;
1374 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001375 }
Bill Wendling66f02412012-02-11 11:38:06 +00001376 }
1377
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001378 // Check all of the requirements.
1379 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1380 MDNode *Requirement = Requirements[I];
1381 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1382 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001383
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001384 MDNode *Op = Flags[Flag];
1385 if (!Op || Op->getOperand(2) != ReqValue) {
1386 HasErr |= emitError("linking module flags '" + Flag->getString() +
1387 "': does not have the required value");
1388 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001389 }
1390 }
1391
1392 return HasErr;
1393}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001394
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001395bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001396 assert(DstM && "Null destination module");
1397 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001398
1399 // Inherit the target data from the source module if the destination module
1400 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001401 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001402 DstM->setDataLayout(SrcM->getDataLayout());
1403
1404 // Copy the target triple from the source to dest if the dest's is empty.
1405 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1406 DstM->setTargetTriple(SrcM->getTargetTriple());
1407
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001408 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001409 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001410 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001411 errs() << "WARNING: Linking two modules of different data layouts: '"
1412 << SrcM->getModuleIdentifier() << "' is '"
1413 << SrcM->getDataLayoutStr() << "' whereas '"
1414 << DstM->getModuleIdentifier() << "' is '"
1415 << DstM->getDataLayoutStr() << "'\n";
Eli Benderskye17f3702014-02-06 18:01:56 +00001416 }
1417 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001418 if (!SrcM->getTargetTriple().empty() &&
1419 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Eli Benderskye17f3702014-02-06 18:01:56 +00001420 if (!SuppressWarnings) {
JF Bastien026fc5f2014-03-05 21:26:42 +00001421 errs() << "WARNING: Linking two modules of different target triples: "
1422 << SrcM->getModuleIdentifier() << "' is '"
1423 << SrcM->getTargetTriple() << "' whereas '"
1424 << DstM->getModuleIdentifier() << "' is '"
Eli Benderskye17f3702014-02-06 18:01:56 +00001425 << DstM->getTargetTriple() << "'\n";
1426 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001427 }
1428
1429 // Append the module inline asm string.
1430 if (!SrcM->getModuleInlineAsm().empty()) {
1431 if (DstM->getModuleInlineAsm().empty())
1432 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1433 else
1434 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1435 SrcM->getModuleInlineAsm());
1436 }
1437
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001438 // Loop over all of the linked values to compute type mappings.
1439 computeTypeMapping();
1440
David Majnemerdad0a642014-06-27 18:19:56 +00001441 ComdatsChosen.clear();
1442 for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1443 const Comdat &C = SMEC.getValue();
1444 if (ComdatsChosen.count(&C))
1445 continue;
1446 Comdat::SelectionKind SK;
1447 bool LinkFromSrc;
1448 if (getComdatResult(&C, SK, LinkFromSrc))
1449 return true;
1450 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1451 }
1452
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001453 // Insert all of the globals in src into the DstM module... without linking
1454 // initializers (which could refer to functions not yet mapped over).
1455 for (Module::global_iterator I = SrcM->global_begin(),
1456 E = SrcM->global_end(); I != E; ++I)
1457 if (linkGlobalProto(I))
1458 return true;
1459
1460 // Link the functions together between the two modules, without doing function
1461 // bodies... this just adds external function prototypes to the DstM
1462 // function... We do this so that when we begin processing function bodies,
1463 // all of the global values that may be referenced are available in our
1464 // ValueMap.
1465 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1466 if (linkFunctionProto(I))
1467 return true;
1468
1469 // If there were any aliases, link them now.
1470 for (Module::alias_iterator I = SrcM->alias_begin(),
1471 E = SrcM->alias_end(); I != E; ++I)
1472 if (linkAliasProto(I))
1473 return true;
1474
1475 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1476 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001477
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001478 // Link in the function bodies that are defined in the source module into
1479 // DstM.
1480 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001481 // Skip if not linking from source.
1482 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001483
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001484 Function *DF = cast<Function>(ValueMap[SF]);
1485 if (SF->hasPrefixData()) {
1486 // Link in the prefix data.
1487 DF->setPrefixData(MapValue(
1488 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1489 }
1490
Tanya Lattnerea166d42011-10-14 22:17:46 +00001491 // Skip if no body (function is external) or materialize.
1492 if (SF->isDeclaration()) {
1493 if (!SF->isMaterializable())
1494 continue;
1495 if (SF->Materialize(&ErrorMsg))
1496 return true;
1497 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001498
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001499 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001500 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001501 }
1502
1503 // Resolve all uses of aliases with aliasees.
1504 linkAliasBodies();
1505
Bill Wendling66f02412012-02-11 11:38:06 +00001506 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001507 // after linking GlobalValues so that MDNodes that reference GlobalValues
1508 // are properly remapped.
1509 linkNamedMDNodes();
1510
Bill Wendling66f02412012-02-11 11:38:06 +00001511 // Merge the module flags into the DstM module.
1512 if (linkModuleFlagsMetadata())
1513 return true;
1514
Bill Wendling91686d62014-01-16 06:29:36 +00001515 // Update the initializers in the DstM module now that all globals that may
1516 // be referenced are in DstM.
1517 linkGlobalInits();
1518
Tanya Lattner0a48b872011-11-02 00:24:56 +00001519 // Process vector of lazily linked in functions.
1520 bool LinkedInAnyFunctions;
1521 do {
1522 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001523
Bill Wendlingfa2287822013-03-27 17:54:41 +00001524 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001525 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001526 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001527 if (!SF)
1528 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001529
James Molloyf6f121e2013-05-28 15:17:05 +00001530 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001531 if (SF->hasPrefixData()) {
1532 // Link in the prefix data.
1533 DF->setPrefixData(MapValue(SF->getPrefixData(),
1534 ValueMap,
1535 RF_None,
1536 &TypeMap,
1537 &ValMaterializer));
1538 }
James Molloyf6f121e2013-05-28 15:17:05 +00001539
1540 // Materialize if necessary.
1541 if (SF->isDeclaration()) {
1542 if (!SF->isMaterializable())
1543 continue;
1544 if (SF->Materialize(&ErrorMsg))
1545 return true;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001546 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001547
James Molloyf6f121e2013-05-28 15:17:05 +00001548 // Erase from vector *before* the function body is linked - linkFunctionBody could
1549 // invalidate I.
1550 LazilyLinkFunctions.erase(I);
1551
1552 // Link in function body.
1553 linkFunctionBody(DF, SF);
1554 SF->Dematerialize();
1555
1556 // Set flag to indicate we may have more functions to lazily link in
1557 // since we linked in a function.
1558 LinkedInAnyFunctions = true;
1559 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001560 }
1561 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001562
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001563 // Now that all of the types from the source are used, resolve any structs
1564 // copied over to the dest that didn't exist there.
1565 TypeMap.linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001566
Anton Korobeynikov26098882008-03-05 23:21:39 +00001567 return false;
1568}
Reid Spencer361e5132004-11-12 20:37:43 +00001569
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001570Linker::Linker(Module *M, bool SuppressWarnings)
1571 : Composite(M), SuppressWarnings(SuppressWarnings) {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001572 TypeFinder StructTypes;
1573 StructTypes.run(*M, true);
1574 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1575}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001576
1577Linker::~Linker() {
1578}
1579
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001580void Linker::deleteModule() {
1581 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001582 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001583}
1584
Rafael Espindola3df61b72013-05-04 03:48:37 +00001585bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
Eli Bendersky7da92ed2014-02-20 22:19:24 +00001586 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1587 SuppressWarnings);
Rafael Espindola287f18b2013-05-04 04:08:02 +00001588 if (TheLinker.run()) {
1589 if (ErrorMsg)
1590 *ErrorMsg = TheLinker.ErrorMsg;
1591 return true;
1592 }
1593 return false;
Rafael Espindola3df61b72013-05-04 03:48:37 +00001594}
1595
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001596//===----------------------------------------------------------------------===//
1597// LinkModules entrypoint.
1598//===----------------------------------------------------------------------===//
1599
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001600/// LinkModules - This function links two modules together, with the resulting
Eli Bendersky970cc632013-03-08 22:29:44 +00001601/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001602/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1603/// the problem. Upon failure, the Dest module could be in a modified state,
1604/// and shouldn't be relied on to be consistent.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001605bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
Tanya Lattnercbb91402011-10-11 00:24:54 +00001606 std::string *ErrorMsg) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001607 Linker L(Dest);
1608 return L.linkInModule(Src, Mode, ErrorMsg);
Reid Spencer361e5132004-11-12 20:37:43 +00001609}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001610
1611//===----------------------------------------------------------------------===//
1612// C API.
1613//===----------------------------------------------------------------------===//
1614
1615LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1616 LLVMLinkerMode Mode, char **OutMessages) {
1617 std::string Messages;
1618 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
Craig Topper2617dcc2014-04-15 06:32:26 +00001619 Mode, OutMessages? &Messages : nullptr);
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001620 if (OutMessages)
1621 *OutMessages = strdup(Messages.c_str());
1622 return Result;
1623}