blob: 2467f67831615e32a217ee1c8cdd1ec18d9752be [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"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000020#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000024#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000025#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000026#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000027#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000028#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000029#include <cctype>
David Majnemer82d6ff62014-06-27 18:38:12 +000030#include <tuple>
Reid Spencer361e5132004-11-12 20:37:43 +000031using namespace llvm;
32
Eli Benderskye17f3702014-02-06 18:01:56 +000033
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000034//===----------------------------------------------------------------------===//
35// TypeMap implementation.
36//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000037
Chris Lattnereee6f992008-06-16 21:00:18 +000038namespace {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000039 typedef SmallPtrSet<StructType*, 32> TypeSet;
40
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000041class TypeMapTy : public ValueMapTypeRemapper {
42 /// MappedTypes - This is a mapping from a source type to a destination type
43 /// to use.
44 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000045
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000046 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
47 /// we speculatively add types to MappedTypes, but keep track of them here in
48 /// case we need to roll back.
49 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000050
Chris Lattner5e3bd972011-12-20 00:03:52 +000051 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
52 /// source module that are mapped to an opaque struct in the destination
53 /// module.
54 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000055
Chris Lattner5e3bd972011-12-20 00:03:52 +000056 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
57 /// destination modules who are getting a body from the source module.
58 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000059
Chris Lattner56cdea62008-06-16 23:06:51 +000060public:
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000061 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
62
63 TypeSet &DstStructTypesSet;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000064 /// addTypeMapping - Indicate that the specified type in the destination
65 /// module is conceptually equivalent to the specified type in the source
66 /// module.
67 void addTypeMapping(Type *DstTy, Type *SrcTy);
68
69 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
70 /// module from a type definition in the source module.
71 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000072
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000073 /// get - Return the mapped type to use for the specified input type from the
74 /// source module.
75 Type *get(Type *SrcTy);
76
77 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
78
Bill Wendlingb6af2f32012-03-22 20:28:27 +000079 /// dump - Dump out the type map for debugging purposes.
80 void dump() const {
81 for (DenseMap<Type*, Type*>::const_iterator
82 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
83 dbgs() << "TypeMap: ";
Justin Bognerc0087f32014-08-12 03:24:59 +000084 I->first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000085 dbgs() << " => ";
Justin Bognerc0087f32014-08-12 03:24:59 +000086 I->second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000087 dbgs() << '\n';
88 }
89 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000090
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000091private:
92 Type *getImpl(Type *T);
93 /// remapType - Implement the ValueMapTypeRemapper interface.
Craig Topper85482992014-03-05 07:52:44 +000094 Type *remapType(Type *SrcTy) override {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000095 return get(SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000096 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000097
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000098 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000099};
100}
101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000102void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
103 Type *&Entry = MappedTypes[SrcTy];
104 if (Entry) return;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000105
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000106 if (DstTy == SrcTy) {
107 Entry = DstTy;
108 return;
109 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000110
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000111 // Check to see if these types are recursively isomorphic and establish a
112 // mapping between them if so.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000113 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000114 // Oops, they aren't isomorphic. Just discard this request by rolling out
115 // any speculative mappings we've established.
116 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
117 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendlingd48b7782012-02-28 04:01:21 +0000118 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000119 SpeculativeTypes.clear();
120}
Chris Lattnereee6f992008-06-16 21:00:18 +0000121
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000122/// areTypesIsomorphic - Recursively walk this pair of types, returning true
123/// if they are isomorphic, false if they are not.
124bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
125 // Two types with differing kinds are clearly not isomorphic.
126 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000127
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000128 // If we have an entry in the MappedTypes table, then we have our answer.
129 Type *&Entry = MappedTypes[SrcTy];
130 if (Entry)
131 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000132
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000133 // Two identical types are clearly isomorphic. Remember this
134 // non-speculatively.
135 if (DstTy == SrcTy) {
136 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000137 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000138 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000139
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000140 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000141
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000142 // If this is an opaque struct type, special case it.
143 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
144 // Mapping an opaque type to any struct, just keep the dest struct.
145 if (SSTy->isOpaque()) {
146 Entry = DstTy;
147 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000148 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000149 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000150
Chris Lattner5e3bd972011-12-20 00:03:52 +0000151 // Mapping a non-opaque source type to an opaque dest. If this is the first
152 // type that we're mapping onto this destination type then we succeed. Keep
153 // the dest, but fill it in later. This doesn't need to be speculative. If
154 // this is the second (different) type that we're trying to map onto the
155 // same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000156 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000157 // We can only map one source type onto the opaque destination type.
158 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
159 return false;
160 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000161 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000162 return true;
163 }
164 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000165
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000166 // If the number of subtypes disagree between the two types, then we fail.
167 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000168 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000169
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000170 // Fail if any of the extra properties (e.g. array size) of the type disagree.
171 if (isa<IntegerType>(DstTy))
172 return false; // bitwidth disagrees.
173 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
175 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000176
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000177 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
179 return false;
180 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000182 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000183 DSTy->isPacked() != SSTy->isPacked())
184 return false;
185 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
187 return false;
188 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000189 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000190 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000191 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000192
193 // Otherwise, we speculate that these two types will line up and recursively
194 // check the subelements.
195 Entry = DstTy;
196 SpeculativeTypes.push_back(SrcTy);
197
Bill Wendlingd48b7782012-02-28 04:01:21 +0000198 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
199 if (!areTypesIsomorphic(DstTy->getContainedType(i),
200 SrcTy->getContainedType(i)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000201 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000202
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000203 // If everything seems to have lined up, then everything is great.
204 return true;
205}
206
207/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
208/// module from a type definition in the source module.
209void TypeMapTy::linkDefinedTypeBodies() {
210 SmallVector<Type*, 16> Elements;
211 SmallString<16> TmpName;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000212
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000213 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner5e3bd972011-12-20 00:03:52 +0000214 // entries to the SrcDefinitionsToResolve vector.
215 while (!SrcDefinitionsToResolve.empty()) {
216 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000217 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000218
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000219 // TypeMap is a many-to-one mapping, if there were multiple types that
220 // provide a body for DstSTy then previous iterations of this loop may have
221 // already handled it. Just ignore this case.
222 if (!DstSTy->isOpaque()) continue;
223 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000224
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000225 // Map the body of the source type over to a new body for the dest type.
226 Elements.resize(SrcSTy->getNumElements());
227 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
228 Elements[i] = getImpl(SrcSTy->getElementType(i));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000229
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000230 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000231
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000232 // If DstSTy has no name or has a longer name than STy, then viciously steal
233 // STy's name.
234 if (!SrcSTy->hasName()) continue;
235 StringRef SrcName = SrcSTy->getName();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000236
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000237 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
238 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
239 SrcSTy->setName("");
240 DstSTy->setName(TmpName.str());
241 TmpName.clear();
242 }
243 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000244
Chris Lattner5e3bd972011-12-20 00:03:52 +0000245 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000246}
247
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000248/// get - Return the mapped type to use for the specified input type from the
249/// source module.
250Type *TypeMapTy::get(Type *Ty) {
251 Type *Result = getImpl(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000252
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000253 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000254 if (!SrcDefinitionsToResolve.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000255 linkDefinedTypeBodies();
256 return Result;
257}
258
259/// getImpl - This is the recursive version of get().
260Type *TypeMapTy::getImpl(Type *Ty) {
261 // If we already have an entry for this type, return it.
262 Type **Entry = &MappedTypes[Ty];
263 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000264
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000265 // If this is not a named struct type, then just map all of the elements and
266 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000267 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000268 // If there are no element types to map, then the type is itself. This is
269 // true for the anonymous {} struct, things like 'float', integers, etc.
270 if (Ty->getNumContainedTypes() == 0)
271 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000272
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000273 // Remap all of the elements, keeping track of whether any of them change.
274 bool AnyChange = false;
275 SmallVector<Type*, 4> ElementTypes;
276 ElementTypes.resize(Ty->getNumContainedTypes());
277 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
278 ElementTypes[i] = getImpl(Ty->getContainedType(i));
279 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
280 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000281
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000282 // If we found our type while recursively processing stuff, just use it.
283 Entry = &MappedTypes[Ty];
284 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000285
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000286 // If all of the element types mapped directly over, then the type is usable
287 // as-is.
288 if (!AnyChange)
289 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000290
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000291 // Otherwise, rebuild a modified type.
292 switch (Ty->getTypeID()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000293 default: llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000294 case Type::ArrayTyID:
295 return *Entry = ArrayType::get(ElementTypes[0],
296 cast<ArrayType>(Ty)->getNumElements());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000297 case Type::VectorTyID:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000298 return *Entry = VectorType::get(ElementTypes[0],
299 cast<VectorType>(Ty)->getNumElements());
300 case Type::PointerTyID:
301 return *Entry = PointerType::get(ElementTypes[0],
302 cast<PointerType>(Ty)->getAddressSpace());
303 case Type::FunctionTyID:
304 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000305 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000306 cast<FunctionType>(Ty)->isVarArg());
307 case Type::StructTyID:
308 // Note that this is only reached for anonymous structs.
309 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
310 cast<StructType>(Ty)->isPacked());
311 }
312 }
313
314 // Otherwise, this is an unmapped named struct. If the struct can be directly
315 // mapped over, just use it as-is. This happens in a case when the linked-in
316 // module has something like:
317 // %T = type {%T*, i32}
318 // @GV = global %T* null
319 // where T does not exist at all in the destination module.
320 //
321 // The other case we watch for is when the type is not in the destination
322 // module, but that it has to be rebuilt because it refers to something that
323 // is already mapped. For example, if the destination module has:
324 // %A = type { i32 }
325 // and the source module has something like
326 // %A' = type { i32 }
327 // %B = type { %A'* }
328 // @GV = global %B* null
329 // then we want to create a new type: "%B = type { %A*}" and have it take the
330 // pristine "%B" name from the source module.
331 //
332 // To determine which case this is, we have to recursively walk the type graph
333 // speculating that we'll be able to reuse it unmodified. Only if this is
334 // safe would we map the entire thing over. Because this is an optimization,
335 // and is not required for the prettiness of the linked module, we just skip
336 // it and always rebuild a type here.
337 StructType *STy = cast<StructType>(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000338
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000339 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000340 if (STy->isOpaque()) {
341 // A named structure type from src module is used. Add it to the Set of
342 // identified structs in the destination module.
343 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000344 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000345 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000346
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000347 // Otherwise we create a new type and resolve its body later. This will be
348 // resolved by the top level of get().
Chris Lattner5e3bd972011-12-20 00:03:52 +0000349 SrcDefinitionsToResolve.push_back(STy);
350 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000351 // A new identified structure type was created. Add it to the set of
352 // identified structs in the destination module.
353 DstStructTypesSet.insert(DTy);
Chris Lattner5e3bd972011-12-20 00:03:52 +0000354 DstResolvedOpaqueTypes.insert(DTy);
355 return *Entry = DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000356}
357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000358//===----------------------------------------------------------------------===//
359// ModuleLinker implementation.
360//===----------------------------------------------------------------------===//
361
362namespace {
James Molloyf6f121e2013-05-28 15:17:05 +0000363 class ModuleLinker;
364
365 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
366 /// linked on the fly. This speeds up linking for modules with many
367 /// lazily linked functions of which few get used.
368 class ValueMaterializerTy : public ValueMaterializer {
369 TypeMapTy &TypeMap;
370 Module *DstM;
371 std::vector<Function*> &LazilyLinkFunctions;
372 public:
373 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
374 std::vector<Function*> &LazilyLinkFunctions) :
375 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
376 LazilyLinkFunctions(LazilyLinkFunctions) {
377 }
378
Craig Topper85482992014-03-05 07:52:44 +0000379 Value *materializeValueFor(Value *V) override;
James Molloyf6f121e2013-05-28 15:17:05 +0000380 };
381
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000382 namespace {
383 class LinkDiagnosticInfo : public DiagnosticInfo {
384 const Twine &Msg;
385
386 public:
387 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
388 void print(DiagnosticPrinter &DP) const override;
389 };
390 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
391 const Twine &Msg)
392 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
393 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
394 }
395
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000396 /// ModuleLinker - This is an implementation class for the LinkModules
397 /// function, which is the entrypoint for this file.
398 class ModuleLinker {
399 Module *DstM, *SrcM;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000400
401 TypeMapTy TypeMap;
James Molloyf6f121e2013-05-28 15:17:05 +0000402 ValueMaterializerTy ValMaterializer;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403
404 /// ValueMap - Mapping of values from what they used to be in Src, to what
405 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
406 /// some overhead due to the use of Value handles which the Linker doesn't
407 /// actually need, but this allows us to reuse the ValueMapper code.
408 ValueToValueMapTy ValueMap;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000410 struct AppendingVarInfo {
411 GlobalVariable *NewGV; // New aggregate global in dest module.
412 Constant *DstInit; // Old initializer from dest module.
413 Constant *SrcInit; // Old initializer from src module.
414 };
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000415
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000416 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000417
Tanya Lattnercbb91402011-10-11 00:24:54 +0000418 unsigned Mode; // Mode to treat source module.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000419
Tanya Lattnercbb91402011-10-11 00:24:54 +0000420 // Set of items not to link in from source.
421 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000422
Tanya Lattner0a48b872011-11-02 00:24:56 +0000423 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000424 std::vector<Function*> LazilyLinkFunctions;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000425
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000426 public:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000427 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000428 : DstM(dstM), SrcM(srcM), TypeMap(Set),
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000429 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode) {}
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000430
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000431 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000432
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000433 private:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000434 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
435 const GlobalValue &Src);
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000436
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000437 /// Helper method for setting a message and returning an error code.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000438 bool emitError(const Twine &Message) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000439 DstM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Chris Lattner99953022008-06-16 18:27:53 +0000440 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000441 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000442
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000443 void emitWarning(const Twine &Message) {
444 DstM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
445 }
446
David Majnemerdad0a642014-06-27 18:19:56 +0000447 bool getComdatLeader(Module *M, StringRef ComdatName,
448 const GlobalVariable *&GVar);
449 bool computeResultingSelectionKind(StringRef ComdatName,
450 Comdat::SelectionKind Src,
451 Comdat::SelectionKind Dst,
452 Comdat::SelectionKind &Result,
453 bool &LinkFromSrc);
454 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
455 ComdatsChosen;
456 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
457 bool &LinkFromSrc);
458
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000459 /// getLinkageResult - This analyzes the two global values and determines
460 /// what the result will look like in the destination module.
461 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000462 GlobalValue::LinkageTypes &LT,
463 GlobalValue::VisibilityTypes &Vis,
464 bool &LinkFromSrc);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000465
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000466 /// getLinkedToGlobal - Given a global in the source module, return the
467 /// global in the destination module that is being linked to, if any.
468 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
469 // If the source has no name it can't link. If it has local linkage,
470 // there is no name match-up going on.
471 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000472 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000473
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000474 // Otherwise see if we have a match in the destination module's symtab.
475 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
Craig Topper2617dcc2014-04-15 06:32:26 +0000476 if (!DGV) return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000477
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000478 // If we found a global with the same name in the dest module, but it has
479 // internal linkage, we are really not doing any linkage here.
480 if (DGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000481 return nullptr;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000482
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000483 // Otherwise, we do in fact link to the destination global.
484 return DGV;
485 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000486
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000487 void computeTypeMapping();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000488
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000489 void upgradeMismatchedGlobalArray(StringRef Name);
490 void upgradeMismatchedGlobals();
491
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000492 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
493 bool linkGlobalProto(GlobalVariable *SrcGV);
494 bool linkFunctionProto(Function *SrcF);
495 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendling66f02412012-02-11 11:38:06 +0000496 bool linkModuleFlagsMetadata();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000497
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000498 void linkAppendingVarInit(const AppendingVarInfo &AVI);
499 void linkGlobalInits();
500 void linkFunctionBody(Function *Dst, Function *Src);
501 void linkAliasBodies();
502 void linkNamedMDNodes();
503 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000504}
505
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000506/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
Reid Spencer90246aa2007-02-04 04:29:21 +0000507/// in the symbol table. This is good for all clients except for us. Go
508/// through the trouble to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000509static void forceRenaming(GlobalValue *GV, StringRef Name) {
510 // If the global doesn't force its name or if it already has the right name,
511 // there is nothing for us to do.
512 if (GV->hasLocalLinkage() || GV->getName() == Name)
513 return;
514
515 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000516
517 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000518 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000519 GV->takeName(ConflictGV);
520 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000521 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000522 } else {
523 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000524 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000525}
Reid Spencer90246aa2007-02-04 04:29:21 +0000526
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000527/// copyGVAttributes - copy additional attributes (those not needed to construct
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000528/// a GlobalValue) from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000529static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000530 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000531 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000532 unsigned Alignment;
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000533 if (DestGO)
534 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000535
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000536 DestGV->copyAttributesFrom(SrcGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000537
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000538 if (DestGO)
539 DestGO->setAlignment(Alignment);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000540
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000541 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000542}
543
Rafael Espindola23f8d642012-01-05 23:02:01 +0000544static bool isLessConstraining(GlobalValue::VisibilityTypes a,
545 GlobalValue::VisibilityTypes b) {
546 if (a == GlobalValue::HiddenVisibility)
547 return false;
548 if (b == GlobalValue::HiddenVisibility)
549 return true;
550 if (a == GlobalValue::ProtectedVisibility)
551 return false;
552 if (b == GlobalValue::ProtectedVisibility)
553 return true;
554 return false;
555}
556
James Molloyf6f121e2013-05-28 15:17:05 +0000557Value *ValueMaterializerTy::materializeValueFor(Value *V) {
558 Function *SF = dyn_cast<Function>(V);
559 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000560 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000561
562 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
563 SF->getLinkage(), SF->getName(), DstM);
564 copyGVAttributes(DF, SF);
565
Rafael Espindola3931c282014-08-15 20:17:08 +0000566 if (Comdat *SC = SF->getComdat()) {
567 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
568 DF->setComdat(DC);
569 }
570
James Molloyf6f121e2013-05-28 15:17:05 +0000571 LazilyLinkFunctions.push_back(SF);
572 return DF;
573}
574
David Majnemerdad0a642014-06-27 18:19:56 +0000575bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
576 const GlobalVariable *&GVar) {
577 const GlobalValue *GVal = M->getNamedValue(ComdatName);
578 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
579 GVal = GA->getBaseObject();
580 if (!GVal)
581 // We cannot resolve the size of the aliasee yet.
582 return emitError("Linking COMDATs named '" + ComdatName +
583 "': COMDAT key involves incomputable alias size.");
584 }
585
586 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
587 if (!GVar)
588 return emitError(
589 "Linking COMDATs named '" + ComdatName +
590 "': GlobalVariable required for data dependent selection!");
591
592 return false;
593}
594
595bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
596 Comdat::SelectionKind Src,
597 Comdat::SelectionKind Dst,
598 Comdat::SelectionKind &Result,
599 bool &LinkFromSrc) {
600 // The ability to mix Comdat::SelectionKind::Any with
601 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
602 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
603 Dst == Comdat::SelectionKind::Largest;
604 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
605 Src == Comdat::SelectionKind::Largest;
606 if (DstAnyOrLargest && SrcAnyOrLargest) {
607 if (Dst == Comdat::SelectionKind::Largest ||
608 Src == Comdat::SelectionKind::Largest)
609 Result = Comdat::SelectionKind::Largest;
610 else
611 Result = Comdat::SelectionKind::Any;
612 } else if (Src == Dst) {
613 Result = Dst;
614 } else {
615 return emitError("Linking COMDATs named '" + ComdatName +
616 "': invalid selection kinds!");
617 }
618
619 switch (Result) {
620 case Comdat::SelectionKind::Any:
621 // Go with Dst.
622 LinkFromSrc = false;
623 break;
624 case Comdat::SelectionKind::NoDuplicates:
625 return emitError("Linking COMDATs named '" + ComdatName +
626 "': noduplicates has been violated!");
627 case Comdat::SelectionKind::ExactMatch:
628 case Comdat::SelectionKind::Largest:
629 case Comdat::SelectionKind::SameSize: {
630 const GlobalVariable *DstGV;
631 const GlobalVariable *SrcGV;
632 if (getComdatLeader(DstM, ComdatName, DstGV) ||
633 getComdatLeader(SrcM, ComdatName, SrcGV))
634 return true;
635
636 const DataLayout *DstDL = DstM->getDataLayout();
637 const DataLayout *SrcDL = SrcM->getDataLayout();
638 if (!DstDL || !SrcDL) {
639 return emitError(
640 "Linking COMDATs named '" + ComdatName +
641 "': can't do size dependent selection without DataLayout!");
642 }
643 uint64_t DstSize =
644 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
645 uint64_t SrcSize =
646 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
647 if (Result == Comdat::SelectionKind::ExactMatch) {
648 if (SrcGV->getInitializer() != DstGV->getInitializer())
649 return emitError("Linking COMDATs named '" + ComdatName +
650 "': ExactMatch violated!");
651 LinkFromSrc = false;
652 } else if (Result == Comdat::SelectionKind::Largest) {
653 LinkFromSrc = SrcSize > DstSize;
654 } else if (Result == Comdat::SelectionKind::SameSize) {
655 if (SrcSize != DstSize)
656 return emitError("Linking COMDATs named '" + ComdatName +
657 "': SameSize violated!");
658 LinkFromSrc = false;
659 } else {
660 llvm_unreachable("unknown selection kind");
661 }
662 break;
663 }
664 }
665
666 return false;
667}
668
669bool ModuleLinker::getComdatResult(const Comdat *SrcC,
670 Comdat::SelectionKind &Result,
671 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +0000672 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000673 StringRef ComdatName = SrcC->getName();
674 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
675 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000676
Rafael Espindolab16196a2014-08-11 17:07:34 +0000677 if (DstCI == ComdatSymTab.end()) {
678 // Use the comdat if it is only available in one of the modules.
679 LinkFromSrc = true;
680 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000681 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000682 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000683
684 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000685 Comdat::SelectionKind DSK = DstC->getSelectionKind();
686 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
687 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000688}
James Molloyf6f121e2013-05-28 15:17:05 +0000689
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000690bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
691 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000692 const GlobalValue &Src) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000693 bool SrcIsDeclaration = Src.isDeclarationForLinker();
694 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000695
Rafael Espindola09106052014-09-09 15:59:12 +0000696 // FIXME: Make datalayout mandatory and just use getDataLayout().
697 DataLayout DL(Dest.getParent());
698
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000699 if (SrcIsDeclaration) {
700 // If Src is external or if both Src & Dest are external.. Just link the
701 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000702 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000703 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000704 LinkFromSrc = DestIsDeclaration;
705 return false;
706 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000707 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000708 LinkFromSrc = Dest.hasExternalWeakLinkage();
709 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000710 }
711
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000712 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000713 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000714 LinkFromSrc = true;
715 return false;
716 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000717
Rafael Espindola09106052014-09-09 15:59:12 +0000718 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000719 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
720 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000721 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000722 }
723
724 if (!Dest.hasCommonLinkage()) {
725 LinkFromSrc = false;
726 return false;
727 }
Rafael Espindola09106052014-09-09 15:59:12 +0000728
729 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
730 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000731 LinkFromSrc = SrcSize > DestSize;
732 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000733 }
734
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000735 if (Src.isWeakForLinker()) {
736 assert(!Dest.hasExternalWeakLinkage());
737 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000738
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000739 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
740 LinkFromSrc = true;
741 return false;
742 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000743
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000744 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000745 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000746 }
747
748 if (Dest.isWeakForLinker()) {
749 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000750 LinkFromSrc = true;
751 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000752 }
753
754 assert(!Src.hasExternalWeakLinkage());
755 assert(!Dest.hasExternalWeakLinkage());
756 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
757 "Unexpected linkage type!");
758 return emitError("Linking globals named '" + Src.getName() +
759 "': symbol multiply defined!");
760}
761
Rafael Espindola83a7ddb2014-09-09 14:07:40 +0000762/// This analyzes the two global values and determines what the result will look
763/// like in the destination module. In particular, it computes the resultant
764/// linkage type and visibility, computes whether the global in the source
765/// should be copied over to the destination (replacing the existing one), and
766/// computes whether this linkage is an error or not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000767bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000768 GlobalValue::LinkageTypes &LT,
769 GlobalValue::VisibilityTypes &Vis,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000770 bool &LinkFromSrc) {
771 assert(Dest && "Must have two globals being queried");
772 assert(!Src->hasLocalLinkage() &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000773 "If Src has internal linkage, Dest shouldn't be set!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000774
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000775 if (shouldLinkFromSource(LinkFromSrc, *Dest, *Src))
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000776 return true;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000777
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000778 if (LinkFromSrc)
Chris Lattnerfc61de32004-12-03 22:18:41 +0000779 LT = Src->getLinkage();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000780 else
781 LT = Dest->getLinkage();
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000782
Rafael Espindola23f8d642012-01-05 23:02:01 +0000783 // Compute the visibility. We follow the rules in the System V Application
784 // Binary Interface.
Duncan P. N. Exon Smithb2becfd2014-05-07 22:55:46 +0000785 assert(!GlobalValue::isLocalLinkage(LT) &&
786 "Symbols with local linkage should not be merged");
Rafael Espindola23f8d642012-01-05 23:02:01 +0000787 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
788 Dest->getVisibility() : Src->getVisibility();
Chris Lattnerfc61de32004-12-03 22:18:41 +0000789 return false;
790}
Reid Spencer361e5132004-11-12 20:37:43 +0000791
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000792/// computeTypeMapping - Loop over all of the linked values to compute type
793/// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
794/// we have two struct types 'Foo' but one got renamed when the module was
795/// loaded into the same LLVMContext.
796void ModuleLinker::computeTypeMapping() {
797 // Incorporate globals.
798 for (Module::global_iterator I = SrcM->global_begin(),
799 E = SrcM->global_end(); I != E; ++I) {
800 GlobalValue *DGV = getLinkedToGlobal(I);
Craig Topper2617dcc2014-04-15 06:32:26 +0000801 if (!DGV) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000802
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000803 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
804 TypeMap.addTypeMapping(DGV->getType(), I->getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000805 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000806 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000807
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000808 // Unify the element type of appending arrays.
809 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
810 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
811 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000812 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000813
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000814 // Incorporate functions.
815 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
816 if (GlobalValue *DGV = getLinkedToGlobal(I))
817 TypeMap.addTypeMapping(DGV->getType(), I->getType());
818 }
Bill Wendling7b464612012-02-27 22:34:19 +0000819
Bill Wendlingd48b7782012-02-28 04:01:21 +0000820 // Incorporate types by name, scanning all the types in the source module.
821 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000822 // example. When the source module got loaded into the same LLVMContext, if
823 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000824 TypeFinder SrcStructTypes;
825 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000826 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
827 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000828
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000829 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
830 StructType *ST = SrcStructTypes[i];
831 if (!ST->hasName()) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000832
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000833 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000834 size_t DotPos = ST->getName().rfind('.');
835 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000836 ST->getName().back() == '.' ||
837 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000838 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000839
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000840 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000841 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000842 // Don't use it if this actually came from the source module. They're in
843 // the same LLVMContext after all. Also don't use it unless the type is
844 // actually used in the destination module. This can happen in situations
845 // like this:
846 //
847 // Module A Module B
848 // -------- --------
849 // %Z = type { %A } %B = type { %C.1 }
850 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
851 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
852 // %C = type { i8* } %B.3 = type { %C.1 }
853 //
854 // When we link Module B with Module A, the '%B' in Module B is
855 // used. However, that would then use '%C.1'. But when we process '%C.1',
856 // we prefer to take the '%C' version. So we are then left with both
857 // '%C.1' and '%C' being used for the same types. This leads to some
858 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000859 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000860 TypeMap.addTypeMapping(DST, ST);
861 }
862
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000863 // Don't bother incorporating aliases, they aren't generally typed well.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000864
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000865 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000866 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000867 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000868}
869
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000870static void upgradeGlobalArray(GlobalVariable *GV) {
871 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
872 StructType *OldTy = cast<StructType>(ATy->getElementType());
873 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
874
875 // Get the upgraded 3 element type.
876 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
877 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
878 VoidPtrTy};
879 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
880
881 // Build new constants with a null third field filled in.
882 Constant *OldInitC = GV->getInitializer();
883 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
884 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
885 // Invalid initializer; give up.
886 return;
887 std::vector<Constant *> Initializers;
888 if (OldInit && OldInit->getNumOperands()) {
889 Value *Null = Constant::getNullValue(VoidPtrTy);
890 for (Use &U : OldInit->operands()) {
891 ConstantStruct *Init = cast<ConstantStruct>(U.get());
892 Initializers.push_back(ConstantStruct::get(
893 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
894 }
895 }
896 assert(Initializers.size() == ATy->getNumElements() &&
897 "Failed to copy all array elements");
898
899 // Replace the old GV with a new one.
900 ATy = ArrayType::get(NewTy, Initializers.size());
901 Constant *NewInit = ConstantArray::get(ATy, Initializers);
902 GlobalVariable *NewGV = new GlobalVariable(
903 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
904 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
905 GV->isExternallyInitialized());
906 NewGV->copyAttributesFrom(GV);
907 NewGV->takeName(GV);
908 assert(GV->use_empty() && "program cannot use initializer list");
909 GV->eraseFromParent();
910}
911
912void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
913 // Look for the global arrays.
914 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
915 if (!DstGV)
916 return;
917 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
918 if (!SrcGV)
919 return;
920
921 // Check if the types already match.
922 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
923 auto *SrcTy =
924 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
925 if (DstTy == SrcTy)
926 return;
927
928 // Grab the element types. We can only upgrade an array of a two-field
929 // struct. Only bother if the other one has three-fields.
930 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
931 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
932 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
933 upgradeGlobalArray(DstGV);
934 return;
935 }
936 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
937 upgradeGlobalArray(SrcGV);
938
939 // We can't upgrade any other differences.
940}
941
942void ModuleLinker::upgradeMismatchedGlobals() {
943 upgradeMismatchedGlobalArray("llvm.global_ctors");
944 upgradeMismatchedGlobalArray("llvm.global_dtors");
945}
946
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000947/// linkAppendingVarProto - If there were any appending global variables, link
948/// them together now. Return true on error.
949bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
950 GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000951
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000952 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
953 return emitError("Linking globals named '" + SrcGV->getName() +
954 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000955
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000956 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
957 ArrayType *SrcTy =
958 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
959 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000960
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000961 // Check to see that they two arrays agree on type.
962 if (EltTy != SrcTy->getElementType())
963 return emitError("Appending variables with different element types!");
964 if (DstGV->isConstant() != SrcGV->isConstant())
965 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000966
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000967 if (DstGV->getAlignment() != SrcGV->getAlignment())
968 return emitError(
969 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000971 if (DstGV->getVisibility() != SrcGV->getVisibility())
972 return emitError(
973 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000974
975 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
976 return emitError(
977 "Appending variables with different unnamed_addr need to be linked!");
978
Rafael Espindola64c1e182014-06-03 02:41:57 +0000979 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000980 return emitError(
981 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000982
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000983 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
984 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000985
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000986 // Create the new global variable.
987 GlobalVariable *NG =
988 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000989 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000990 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000991 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000992
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000993 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000994 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000995
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000996 AppendingVarInfo AVI;
997 AVI.NewGV = NG;
998 AVI.DstInit = DstGV->getInitializer();
999 AVI.SrcInit = SrcGV->getInitializer();
1000 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001001
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001002 // Replace any uses of the two global variables with uses of the new
1003 // global.
1004 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +00001005
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001006 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1007 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001008
Tanya Lattnercbb91402011-10-11 00:24:54 +00001009 // Track the source variable so we don't try to link it.
1010 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001011
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001012 return false;
1013}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001014
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001015/// linkGlobalProto - Loop through the global variables in the src module and
1016/// merge them into the dest module.
1017bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
1018 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001019 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolad4885da2013-09-04 14:05:09 +00001020 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001021 unsigned Alignment = SGV->getAlignment();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001022
David Majnemerdad0a642014-06-27 18:19:56 +00001023 bool LinkFromSrc = false;
1024 Comdat *DC = nullptr;
1025 if (const Comdat *SC = SGV->getComdat()) {
1026 Comdat::SelectionKind SK;
1027 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1028 DC = DstM->getOrInsertComdat(SC->getName());
1029 DC->setSelectionKind(SK);
1030 }
1031
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001032 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001033 if (!DC) {
1034 // Concatenation of appending linkage variables is magic and handled later.
1035 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
1036 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001037
David Majnemerdad0a642014-06-27 18:19:56 +00001038 // Determine whether linkage of these two globals follows the source
1039 // module's definition or the destination module's definition.
1040 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1041 GlobalValue::VisibilityTypes NV;
1042 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1043 return true;
1044 NewVisibility = NV;
1045 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001046 if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1047 Alignment = std::max(Alignment, DGV->getAlignment());
1048 else if (!LinkFromSrc)
1049 Alignment = DGV->getAlignment();
Reid Spencer361e5132004-11-12 20:37:43 +00001050
David Majnemerdad0a642014-06-27 18:19:56 +00001051 // If we're not linking from the source, then keep the definition that we
1052 // have.
1053 if (!LinkFromSrc) {
1054 // Special case for const propagation.
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001055 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
1056 DGVar->setAlignment(Alignment);
1057
David Majnemerdad0a642014-06-27 18:19:56 +00001058 if (DGVar->isDeclaration() && SGV->isConstant() &&
1059 !DGVar->isConstant())
1060 DGVar->setConstant(true);
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001061 }
David Majnemerdad0a642014-06-27 18:19:56 +00001062
1063 // Set calculated linkage, visibility and unnamed_addr.
1064 DGV->setLinkage(NewLinkage);
1065 DGV->setVisibility(*NewVisibility);
1066 DGV->setUnnamedAddr(HasUnnamedAddr);
1067 }
1068 }
1069
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001070 if (!LinkFromSrc) {
Chris Lattner0ead7a52008-07-14 07:23:24 +00001071 // Make sure to remember this mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001072 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001073
1074 // Track the source global so that we don't attempt to copy it over when
Tanya Lattnercbb91402011-10-11 00:24:54 +00001075 // processing global initializers.
1076 DoNotLinkFromSource.insert(SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001077
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001078 return false;
Chris Lattner0ead7a52008-07-14 07:23:24 +00001079 }
Reid Spencer361e5132004-11-12 20:37:43 +00001080 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001081
David Majnemerdad0a642014-06-27 18:19:56 +00001082 // If the Comdat this variable was inside of wasn't selected, skip it.
1083 if (DC && !DGV && !LinkFromSrc) {
1084 DoNotLinkFromSource.insert(SGV);
1085 return false;
1086 }
1087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001088 // No linking to be performed or linking from the source: simply create an
1089 // identical version of the symbol over in the dest module... the
1090 // initializer will be filled in later by LinkGlobalInits.
1091 GlobalVariable *NewDGV =
1092 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
Craig Topper2617dcc2014-04-15 06:32:26 +00001093 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
1094 SGV->getName(), /*insertbefore*/nullptr,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001095 SGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001096 SGV->getType()->getAddressSpace());
1097 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001098 copyGVAttributes(NewDGV, SGV);
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001099 NewDGV->setAlignment(Alignment);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001100 if (NewVisibility)
1101 NewDGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +00001102 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001103
David Majnemerdad0a642014-06-27 18:19:56 +00001104 if (DC)
1105 NewDGV->setComdat(DC);
1106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001107 if (DGV) {
1108 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1109 DGV->eraseFromParent();
1110 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001111
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001112 // Make sure to remember this mapping.
1113 ValueMap[SGV] = NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001114 return false;
1115}
1116
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001117/// linkFunctionProto - Link the function in the source module into the
1118/// destination module if needed, setting up mapping information.
1119bool ModuleLinker::linkFunctionProto(Function *SF) {
1120 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001121 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolafd9a9412013-09-04 14:59:03 +00001122 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001123
David Majnemerdad0a642014-06-27 18:19:56 +00001124 bool LinkFromSrc = false;
1125 Comdat *DC = nullptr;
1126 if (const Comdat *SC = SF->getComdat()) {
1127 Comdat::SelectionKind SK;
1128 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1129 DC = DstM->getOrInsertComdat(SC->getName());
1130 DC->setSelectionKind(SK);
1131 }
1132
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001133 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001134 if (!DC) {
1135 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1136 GlobalValue::VisibilityTypes NV;
1137 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
1138 return true;
1139 NewVisibility = NV;
1140 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1141
1142 if (!LinkFromSrc) {
1143 // Set calculated linkage
1144 DGV->setLinkage(NewLinkage);
1145 DGV->setVisibility(*NewVisibility);
1146 DGV->setUnnamedAddr(HasUnnamedAddr);
1147 }
1148 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001149
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001150 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001151 // Make sure to remember this mapping.
1152 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001153
1154 // Track the function from the source module so we don't attempt to remap
Tanya Lattnercbb91402011-10-11 00:24:54 +00001155 // it.
1156 DoNotLinkFromSource.insert(SF);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001157
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001158 return false;
1159 }
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001160 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001161
James Molloyf6f121e2013-05-28 15:17:05 +00001162 // If the function is to be lazily linked, don't create it just yet.
1163 // The ValueMaterializerTy will deal with creating it if it's used.
1164 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1165 SF->hasAvailableExternallyLinkage())) {
1166 DoNotLinkFromSource.insert(SF);
1167 return false;
1168 }
1169
David Majnemerdad0a642014-06-27 18:19:56 +00001170 // If the Comdat this function was inside of wasn't selected, skip it.
1171 if (DC && !DGV && !LinkFromSrc) {
1172 DoNotLinkFromSource.insert(SF);
1173 return false;
1174 }
1175
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001176 // If there is no linkage to be performed or we are linking from the source,
1177 // bring SF over.
1178 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1179 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001180 copyGVAttributes(NewDF, SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001181 if (NewVisibility)
1182 NewDF->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +00001183 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001184
David Majnemerdad0a642014-06-27 18:19:56 +00001185 if (DC)
1186 NewDF->setComdat(DC);
1187
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001188 if (DGV) {
1189 // Any uses of DF need to change to NewDF, with cast.
1190 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1191 DGV->eraseFromParent();
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001192 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001193
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001194 ValueMap[SF] = NewDF;
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001195 return false;
1196}
1197
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001198/// LinkAliasProto - Set up prototypes for any aliases that come over from the
1199/// source module.
1200bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1201 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001202 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001203 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
Rafael Espindola23f8d642012-01-05 23:02:01 +00001204
David Majnemerdad0a642014-06-27 18:19:56 +00001205 bool LinkFromSrc = false;
1206 Comdat *DC = nullptr;
1207 if (const Comdat *SC = SGA->getComdat()) {
1208 Comdat::SelectionKind SK;
1209 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1210 DC = DstM->getOrInsertComdat(SC->getName());
1211 DC->setSelectionKind(SK);
1212 }
1213
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001214 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001215 if (!DC) {
1216 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1217 GlobalValue::VisibilityTypes NV;
1218 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1219 return true;
1220 NewVisibility = NV;
1221 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1222
1223 if (!LinkFromSrc) {
1224 // Set calculated linkage.
1225 DGV->setLinkage(NewLinkage);
1226 DGV->setVisibility(*NewVisibility);
1227 DGV->setUnnamedAddr(HasUnnamedAddr);
1228 }
1229 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001230
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001231 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001232 // Make sure to remember this mapping.
1233 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001234
Tanya Lattnercbb91402011-10-11 00:24:54 +00001235 // Track the alias from the source module so we don't attempt to remap it.
1236 DoNotLinkFromSource.insert(SGA);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001237
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001238 return false;
1239 }
1240 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001241
David Majnemerdad0a642014-06-27 18:19:56 +00001242 // If the Comdat this alias was inside of wasn't selected, skip it.
1243 if (DC && !DGV && !LinkFromSrc) {
1244 DoNotLinkFromSource.insert(SGA);
1245 return false;
1246 }
1247
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001248 // If there is no linkage to be performed or we're linking from the source,
1249 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +00001250 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001251 auto *NewDA =
1252 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1253 SGA->getLinkage(), SGA->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001254 copyGVAttributes(NewDA, SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001255 if (NewVisibility)
1256 NewDA->setVisibility(*NewVisibility);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001257 NewDA->setUnnamedAddr(HasUnnamedAddr);
Reid Spencer361e5132004-11-12 20:37:43 +00001258
Rafael Espindola64c1e182014-06-03 02:41:57 +00001259 if (DGV) {
1260 // Any uses of DGV need to change to NewDA, with cast.
1261 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1262 DGV->eraseFromParent();
1263 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001264
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001265 ValueMap[SGA] = NewDA;
1266 return false;
1267}
1268
Chris Lattner00245f42012-01-24 13:41:11 +00001269static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001270 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1271
1272 for (unsigned i = 0; i != NumElements; ++i)
1273 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001274}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001275
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001276void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1277 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001278 SmallVector<Constant *, 16> DstElements;
1279 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001280
Rafael Espindolad31dc042014-09-05 21:27:52 +00001281 SmallVector<Constant *, 16> SrcElements;
1282 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001283
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001284 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001285
1286 StringRef Name = AVI.NewGV->getName();
1287 bool IsNewStructor =
1288 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1289 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1290
1291 for (auto *V : SrcElements) {
1292 if (IsNewStructor) {
1293 Constant *Key = V->getAggregateElement(2);
1294 if (DoNotLinkFromSource.count(Key))
1295 continue;
1296 }
1297 DstElements.push_back(
1298 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1299 }
1300 if (IsNewStructor) {
1301 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1302 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1303 }
1304
1305 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001306}
1307
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001308/// linkGlobalInits - Update the initializers in the Dest module now that all
1309/// globals that may be referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001310void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +00001311 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001312 for (Module::const_global_iterator I = SrcM->global_begin(),
1313 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001314
Tanya Lattnercbb91402011-10-11 00:24:54 +00001315 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001316 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1317
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001318 // Grab destination global variable.
1319 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1320 // Figure out what the initializer looks like in the dest module.
1321 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001322 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001323 }
Reid Spencer361e5132004-11-12 20:37:43 +00001324}
1325
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001326/// linkFunctionBody - Copy the source function over into the dest function and
1327/// fix up references to values. At this point we know that Dest is an external
1328/// function, and that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001329void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1330 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001331
Chris Lattner7391dde2004-11-16 17:12:38 +00001332 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001333 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001334 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +00001335 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001336 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001337
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001338 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +00001339 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001340 }
1341
Tanya Lattnercbb91402011-10-11 00:24:54 +00001342 if (Mode == Linker::DestroySource) {
1343 // Splice the body of the source function into the dest function.
1344 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001345
Tanya Lattnercbb91402011-10-11 00:24:54 +00001346 // At this point, all of the instructions and values of the function are now
1347 // copied over. The only problem is that they are still referencing values in
1348 // the Source function as operands. Loop through all of the operands of the
1349 // functions and patch them up to point to the local versions.
1350 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1351 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
James Molloyf6f121e2013-05-28 15:17:05 +00001352 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1353 &TypeMap, &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001354
Tanya Lattnercbb91402011-10-11 00:24:54 +00001355 } else {
1356 // Clone the body of the function into the dest function.
1357 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
Craig Topper2617dcc2014-04-15 06:32:26 +00001358 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
James Molloyf6f121e2013-05-28 15:17:05 +00001359 &TypeMap, &ValMaterializer);
Tanya Lattnercbb91402011-10-11 00:24:54 +00001360 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001361
Chris Lattner7391dde2004-11-16 17:12:38 +00001362 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001363 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1364 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001365 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001366
Reid Spencer361e5132004-11-12 20:37:43 +00001367}
1368
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001369/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001370void ModuleLinker::linkAliasBodies() {
1371 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001372 I != E; ++I) {
1373 if (DoNotLinkFromSource.count(I))
1374 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001375 if (Constant *Aliasee = I->getAliasee()) {
1376 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001377 Constant *Val =
1378 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Rafael Espindola64c1e182014-06-03 02:41:57 +00001379 DA->setAliasee(Val);
David Chisnall2c4a34a2010-01-09 16:27:31 +00001380 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001381 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001382}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001383
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001384/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001385/// module.
1386void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001387 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001388 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1389 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001390 // Don't link module flags here. Do them separately.
1391 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001392 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1393 // Add Src elements into Dest node.
1394 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1395 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001396 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001397 }
1398}
Bill Wendling66f02412012-02-11 11:38:06 +00001399
Bill Wendling66f02412012-02-11 11:38:06 +00001400/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1401/// module.
1402bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001403 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001404 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1405 if (!SrcModFlags) return false;
1406
Bill Wendling66f02412012-02-11 11:38:06 +00001407 // If the destination module doesn't have module flags yet, then just copy
1408 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001409 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001410 if (DstModFlags->getNumOperands() == 0) {
1411 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1412 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1413
1414 return false;
1415 }
1416
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001417 // First build a map of the existing module flags and requirements.
1418 DenseMap<MDString*, MDNode*> Flags;
1419 SmallSetVector<MDNode*, 16> Requirements;
1420 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1421 MDNode *Op = DstModFlags->getOperand(I);
1422 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1423 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001424
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001425 if (Behavior->getZExtValue() == Module::Require) {
1426 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1427 } else {
1428 Flags[ID] = Op;
1429 }
Bill Wendling66f02412012-02-11 11:38:06 +00001430 }
1431
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001432 // Merge in the flags from the source module, and also collect its set of
1433 // requirements.
1434 bool HasErr = false;
1435 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1436 MDNode *SrcOp = SrcModFlags->getOperand(I);
1437 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1438 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1439 MDNode *DstOp = Flags.lookup(ID);
1440 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001441
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001442 // If this is a requirement, add it and continue.
1443 if (SrcBehaviorValue == Module::Require) {
1444 // If the destination module does not already have this requirement, add
1445 // it.
1446 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1447 DstModFlags->addOperand(SrcOp);
1448 }
1449 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001450 }
1451
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001452 // If there is no existing flag with this ID, just add it.
1453 if (!DstOp) {
1454 Flags[ID] = SrcOp;
1455 DstModFlags->addOperand(SrcOp);
1456 continue;
1457 }
1458
1459 // Otherwise, perform a merge.
1460 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1461 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1462
1463 // If either flag has override behavior, handle it first.
1464 if (DstBehaviorValue == Module::Override) {
1465 // Diagnose inconsistent flags which both have override behavior.
1466 if (SrcBehaviorValue == Module::Override &&
1467 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1468 HasErr |= emitError("linking module flags '" + ID->getString() +
1469 "': IDs have conflicting override values");
1470 }
1471 continue;
1472 } else if (SrcBehaviorValue == Module::Override) {
1473 // Update the destination flag to that of the source.
1474 DstOp->replaceOperandWith(0, SrcBehavior);
1475 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1476 continue;
1477 }
1478
1479 // Diagnose inconsistent merge behavior types.
1480 if (SrcBehaviorValue != DstBehaviorValue) {
1481 HasErr |= emitError("linking module flags '" + ID->getString() +
1482 "': IDs have conflicting behaviors");
1483 continue;
1484 }
1485
1486 // Perform the merge for standard behavior types.
1487 switch (SrcBehaviorValue) {
1488 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001489 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001490 case Module::Error: {
1491 // Emit an error if the values differ.
1492 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1493 HasErr |= emitError("linking module flags '" + ID->getString() +
1494 "': IDs have conflicting values");
1495 }
1496 continue;
1497 }
1498 case Module::Warning: {
1499 // Emit a warning if the values differ.
1500 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001501 emitWarning("linking module flags '" + ID->getString() +
1502 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001503 }
1504 continue;
1505 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001506 case Module::Append: {
1507 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1508 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1509 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1510 Value **VP, **Values = VP = new Value*[NumOps];
1511 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1512 *VP = DstValue->getOperand(i);
1513 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1514 *VP = SrcValue->getOperand(i);
1515 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1516 ArrayRef<Value*>(Values,
1517 NumOps)));
1518 delete[] Values;
1519 break;
1520 }
1521 case Module::AppendUnique: {
1522 SmallSetVector<Value*, 16> Elts;
1523 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1524 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1525 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1526 Elts.insert(DstValue->getOperand(i));
1527 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1528 Elts.insert(SrcValue->getOperand(i));
1529 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1530 ArrayRef<Value*>(Elts.begin(),
1531 Elts.end())));
1532 break;
1533 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001534 }
Bill Wendling66f02412012-02-11 11:38:06 +00001535 }
1536
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001537 // Check all of the requirements.
1538 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1539 MDNode *Requirement = Requirements[I];
1540 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1541 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001542
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001543 MDNode *Op = Flags[Flag];
1544 if (!Op || Op->getOperand(2) != ReqValue) {
1545 HasErr |= emitError("linking module flags '" + Flag->getString() +
1546 "': does not have the required value");
1547 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001548 }
1549 }
1550
1551 return HasErr;
1552}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001553
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001554bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001555 assert(DstM && "Null destination module");
1556 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001557
1558 // Inherit the target data from the source module if the destination module
1559 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001560 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001561 DstM->setDataLayout(SrcM->getDataLayout());
1562
1563 // Copy the target triple from the source to dest if the dest's is empty.
1564 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1565 DstM->setTargetTriple(SrcM->getTargetTriple());
1566
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001567 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001568 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001569 emitWarning("Linking two modules of different data layouts: '" +
1570 SrcM->getModuleIdentifier() + "' is '" +
1571 SrcM->getDataLayoutStr() + "' whereas '" +
1572 DstM->getModuleIdentifier() + "' is '" +
1573 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001574 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001575 if (!SrcM->getTargetTriple().empty() &&
1576 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001577 emitWarning("Linking two modules of different target triples: " +
1578 SrcM->getModuleIdentifier() + "' is '" +
1579 SrcM->getTargetTriple() + "' whereas '" +
1580 DstM->getModuleIdentifier() + "' is '" +
1581 DstM->getTargetTriple() + "'\n");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001582 }
1583
1584 // Append the module inline asm string.
1585 if (!SrcM->getModuleInlineAsm().empty()) {
1586 if (DstM->getModuleInlineAsm().empty())
1587 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1588 else
1589 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1590 SrcM->getModuleInlineAsm());
1591 }
1592
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001593 // Loop over all of the linked values to compute type mappings.
1594 computeTypeMapping();
1595
David Majnemerdad0a642014-06-27 18:19:56 +00001596 ComdatsChosen.clear();
1597 for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1598 const Comdat &C = SMEC.getValue();
1599 if (ComdatsChosen.count(&C))
1600 continue;
1601 Comdat::SelectionKind SK;
1602 bool LinkFromSrc;
1603 if (getComdatResult(&C, SK, LinkFromSrc))
1604 return true;
1605 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1606 }
1607
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001608 // Upgrade mismatched global arrays.
1609 upgradeMismatchedGlobals();
1610
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001611 // Insert all of the globals in src into the DstM module... without linking
1612 // initializers (which could refer to functions not yet mapped over).
1613 for (Module::global_iterator I = SrcM->global_begin(),
1614 E = SrcM->global_end(); I != E; ++I)
1615 if (linkGlobalProto(I))
1616 return true;
1617
1618 // Link the functions together between the two modules, without doing function
1619 // bodies... this just adds external function prototypes to the DstM
1620 // function... We do this so that when we begin processing function bodies,
1621 // all of the global values that may be referenced are available in our
1622 // ValueMap.
1623 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1624 if (linkFunctionProto(I))
1625 return true;
1626
1627 // If there were any aliases, link them now.
1628 for (Module::alias_iterator I = SrcM->alias_begin(),
1629 E = SrcM->alias_end(); I != E; ++I)
1630 if (linkAliasProto(I))
1631 return true;
1632
1633 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1634 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001635
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001636 // Link in the function bodies that are defined in the source module into
1637 // DstM.
1638 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001639 // Skip if not linking from source.
1640 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001641
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001642 Function *DF = cast<Function>(ValueMap[SF]);
1643 if (SF->hasPrefixData()) {
1644 // Link in the prefix data.
1645 DF->setPrefixData(MapValue(
1646 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1647 }
1648
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001649 // Materialize if needed.
1650 if (SF->isMaterializable()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001651 if (std::error_code EC = SF->materialize())
1652 return emitError(EC.message());
Tanya Lattnerea166d42011-10-14 22:17:46 +00001653 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001654
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001655 // Skip if no body (function is external).
1656 if (SF->isDeclaration())
1657 continue;
1658
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001659 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001660 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001661 }
1662
1663 // Resolve all uses of aliases with aliasees.
1664 linkAliasBodies();
1665
Bill Wendling66f02412012-02-11 11:38:06 +00001666 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001667 // after linking GlobalValues so that MDNodes that reference GlobalValues
1668 // are properly remapped.
1669 linkNamedMDNodes();
1670
Bill Wendling66f02412012-02-11 11:38:06 +00001671 // Merge the module flags into the DstM module.
1672 if (linkModuleFlagsMetadata())
1673 return true;
1674
Bill Wendling91686d62014-01-16 06:29:36 +00001675 // Update the initializers in the DstM module now that all globals that may
1676 // be referenced are in DstM.
1677 linkGlobalInits();
1678
Tanya Lattner0a48b872011-11-02 00:24:56 +00001679 // Process vector of lazily linked in functions.
1680 bool LinkedInAnyFunctions;
1681 do {
1682 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001683
Bill Wendlingfa2287822013-03-27 17:54:41 +00001684 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001685 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001686 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001687 if (!SF)
1688 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001689
James Molloyf6f121e2013-05-28 15:17:05 +00001690 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001691 if (SF->hasPrefixData()) {
1692 // Link in the prefix data.
1693 DF->setPrefixData(MapValue(SF->getPrefixData(),
1694 ValueMap,
1695 RF_None,
1696 &TypeMap,
1697 &ValMaterializer));
1698 }
James Molloyf6f121e2013-05-28 15:17:05 +00001699
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001700 // Materialize if needed.
1701 if (SF->isMaterializable()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001702 if (std::error_code EC = SF->materialize())
1703 return emitError(EC.message());
Tanya Lattner0a48b872011-11-02 00:24:56 +00001704 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001705
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001706 // Skip if no body (function is external).
1707 if (SF->isDeclaration())
1708 continue;
1709
James Molloyf6f121e2013-05-28 15:17:05 +00001710 // Erase from vector *before* the function body is linked - linkFunctionBody could
1711 // invalidate I.
1712 LazilyLinkFunctions.erase(I);
1713
1714 // Link in function body.
1715 linkFunctionBody(DF, SF);
1716 SF->Dematerialize();
1717
1718 // Set flag to indicate we may have more functions to lazily link in
1719 // since we linked in a function.
1720 LinkedInAnyFunctions = true;
1721 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001722 }
1723 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001724
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001725 // Now that all of the types from the source are used, resolve any structs
1726 // copied over to the dest that didn't exist there.
1727 TypeMap.linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001728
Anton Korobeynikov26098882008-03-05 23:21:39 +00001729 return false;
1730}
Reid Spencer361e5132004-11-12 20:37:43 +00001731
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001732Linker::Linker(Module *M) : Composite(M) {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001733 TypeFinder StructTypes;
1734 StructTypes.run(*M, true);
1735 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1736}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001737
1738Linker::~Linker() {
1739}
1740
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001741void Linker::deleteModule() {
1742 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001743 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001744}
1745
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001746bool Linker::linkInModule(Module *Src, unsigned Mode) {
1747 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
1748 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +00001749}
1750
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001751//===----------------------------------------------------------------------===//
1752// LinkModules entrypoint.
1753//===----------------------------------------------------------------------===//
1754
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001755/// LinkModules - This function links two modules together, with the resulting
Eli Bendersky970cc632013-03-08 22:29:44 +00001756/// Dest module modified to be the composite of the two input modules. If an
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001757/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1758/// the problem. Upon failure, the Dest module could be in a modified state,
1759/// and shouldn't be relied on to be consistent.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001760bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001761 Linker L(Dest);
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001762 return L.linkInModule(Src, Mode);
Reid Spencer361e5132004-11-12 20:37:43 +00001763}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001764
1765//===----------------------------------------------------------------------===//
1766// C API.
1767//===----------------------------------------------------------------------===//
1768
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001769static void bindingDiagnosticHandler(const llvm::DiagnosticInfo &DI,
1770 void *Context) {
1771 if (DI.getSeverity() != DS_Error)
1772 return;
1773
1774 std::string *Message = (std::string *)Context;
1775 {
1776 raw_string_ostream Stream(*Message);
1777 DiagnosticPrinterRawOStream DP(Stream);
1778 DI.print(DP);
1779 }
1780}
1781
1782
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001783LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1784 LLVMLinkerMode Mode, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001785 Module *D = unwrap(Dest);
1786 LLVMContext &Ctx = D->getContext();
1787
1788 LLVMContext::DiagnosticHandlerTy OldHandler = Ctx.getDiagnosticHandler();
1789 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
1790 std::string Message;
1791 Ctx.setDiagnosticHandler(bindingDiagnosticHandler, &Message);
1792 LLVMBool Result = Linker::LinkModules(D, unwrap(Src), Mode);
1793 Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext);
1794
1795 if (OutMessages && Result)
1796 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001797 return Result;
1798}