blob: f54eb5548c00fcc1069b8adda6e5ce19094655c1 [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 Espindola18c89412014-10-27 02:35:46 +000039typedef SmallPtrSet<StructType *, 32> TypeSet;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000040
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000041class TypeMapTy : public ValueMapTypeRemapper {
Rafael Espindola18c89412014-10-27 02:35:46 +000042 /// This is a mapping from a source type to a destination type to use.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000043 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000044
Rafael Espindola18c89412014-10-27 02:35:46 +000045 /// When checking to see if two subgraphs are isomorphic, we speculatively
46 /// add types to MappedTypes, but keep track of them here in case we need to
47 /// roll back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000048 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000049
Rafael Espindola18c89412014-10-27 02:35:46 +000050 /// This is a list of non-opaque structs in the source module that are mapped
51 /// to an opaque struct in the destination module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000052 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000053
Rafael Espindola18c89412014-10-27 02:35:46 +000054 /// This is the set of opaque types in the destination modules who are
55 /// getting a body from the source module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000056 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000057
Chris Lattner56cdea62008-06-16 23:06:51 +000058public:
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000059 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
60
61 TypeSet &DstStructTypesSet;
Rafael Espindola18c89412014-10-27 02:35:46 +000062 /// Indicate that the specified type in the destination module is conceptually
63 /// equivalent to the specified type in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000064 void addTypeMapping(Type *DstTy, Type *SrcTy);
65
66 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
67 /// module from a type definition in the source module.
68 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000069
Rafael Espindola18c89412014-10-27 02:35:46 +000070 /// Return the mapped type to use for the specified input type from the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000071 /// source module.
72 Type *get(Type *SrcTy);
73
74 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
75
Rafael Espindola18c89412014-10-27 02:35:46 +000076 /// Dump out the type map for debugging purposes.
Bill Wendlingb6af2f32012-03-22 20:28:27 +000077 void dump() const {
78 for (DenseMap<Type*, Type*>::const_iterator
79 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
80 dbgs() << "TypeMap: ";
Justin Bognerc0087f32014-08-12 03:24:59 +000081 I->first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000082 dbgs() << " => ";
Justin Bognerc0087f32014-08-12 03:24:59 +000083 I->second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000084 dbgs() << '\n';
85 }
86 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000087
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000088private:
89 Type *getImpl(Type *T);
Rafael Espindola18c89412014-10-27 02:35:46 +000090 /// Implement the ValueMapTypeRemapper interface.
Craig Topper85482992014-03-05 07:52:44 +000091 Type *remapType(Type *SrcTy) override {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000092 return get(SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000093 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000095 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000096};
97}
98
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000099void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
100 Type *&Entry = MappedTypes[SrcTy];
101 if (Entry) return;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000102
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000103 if (DstTy == SrcTy) {
104 Entry = DstTy;
105 return;
106 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000107
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000108 // Check to see if these types are recursively isomorphic and establish a
109 // mapping between them if so.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000110 if (!areTypesIsomorphic(DstTy, SrcTy)) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000111 // Oops, they aren't isomorphic. Just discard this request by rolling out
112 // any speculative mappings we've established.
113 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
114 MappedTypes.erase(SpeculativeTypes[i]);
Bill Wendlingd48b7782012-02-28 04:01:21 +0000115 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000116 SpeculativeTypes.clear();
117}
Chris Lattnereee6f992008-06-16 21:00:18 +0000118
Rafael Espindola18c89412014-10-27 02:35:46 +0000119/// Recursively walk this pair of types, returning true if they are isomorphic,
120/// false if they are not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000121bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
122 // Two types with differing kinds are clearly not isomorphic.
123 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000124
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000125 // If we have an entry in the MappedTypes table, then we have our answer.
126 Type *&Entry = MappedTypes[SrcTy];
127 if (Entry)
128 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000129
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000130 // Two identical types are clearly isomorphic. Remember this
131 // non-speculatively.
132 if (DstTy == SrcTy) {
133 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000134 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000135 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000136
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000137 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000139 // If this is an opaque struct type, special case it.
140 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
141 // Mapping an opaque type to any struct, just keep the dest struct.
142 if (SSTy->isOpaque()) {
143 Entry = DstTy;
144 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000145 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000146 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000147
Chris Lattner5e3bd972011-12-20 00:03:52 +0000148 // Mapping a non-opaque source type to an opaque dest. If this is the first
149 // type that we're mapping onto this destination type then we succeed. Keep
150 // the dest, but fill it in later. This doesn't need to be speculative. If
151 // this is the second (different) type that we're trying to map onto the
152 // same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000153 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000154 // We can only map one source type onto the opaque destination type.
155 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
156 return false;
157 SrcDefinitionsToResolve.push_back(SSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000158 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000159 return true;
160 }
161 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000162
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000163 // If the number of subtypes disagree between the two types, then we fail.
164 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000165 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000166
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000167 // Fail if any of the extra properties (e.g. array size) of the type disagree.
168 if (isa<IntegerType>(DstTy))
169 return false; // bitwidth disagrees.
170 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
171 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
172 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000173
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000174 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
175 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
176 return false;
177 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
178 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000179 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000180 DSTy->isPacked() != SSTy->isPacked())
181 return false;
182 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
183 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
184 return false;
185 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000186 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000187 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000188 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000189
190 // Otherwise, we speculate that these two types will line up and recursively
191 // check the subelements.
192 Entry = DstTy;
193 SpeculativeTypes.push_back(SrcTy);
194
Bill Wendlingd48b7782012-02-28 04:01:21 +0000195 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
196 if (!areTypesIsomorphic(DstTy->getContainedType(i),
197 SrcTy->getContainedType(i)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000198 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000199
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000200 // If everything seems to have lined up, then everything is great.
201 return true;
202}
203
Rafael Espindola18c89412014-10-27 02:35:46 +0000204/// Produce a body for an opaque type in the dest module from a type definition
205/// in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000206void TypeMapTy::linkDefinedTypeBodies() {
207 SmallVector<Type*, 16> Elements;
208 SmallString<16> TmpName;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000209
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000210 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner5e3bd972011-12-20 00:03:52 +0000211 // entries to the SrcDefinitionsToResolve vector.
212 while (!SrcDefinitionsToResolve.empty()) {
213 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000214 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000215
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000216 // TypeMap is a many-to-one mapping, if there were multiple types that
217 // provide a body for DstSTy then previous iterations of this loop may have
218 // already handled it. Just ignore this case.
219 if (!DstSTy->isOpaque()) continue;
220 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000221
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000222 // Map the body of the source type over to a new body for the dest type.
223 Elements.resize(SrcSTy->getNumElements());
224 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
225 Elements[i] = getImpl(SrcSTy->getElementType(i));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000226
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000227 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000228
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000229 // If DstSTy has no name or has a longer name than STy, then viciously steal
230 // STy's name.
231 if (!SrcSTy->hasName()) continue;
232 StringRef SrcName = SrcSTy->getName();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000233
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000234 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
235 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
236 SrcSTy->setName("");
237 DstSTy->setName(TmpName.str());
238 TmpName.clear();
239 }
240 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000241
Chris Lattner5e3bd972011-12-20 00:03:52 +0000242 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000243}
244
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000245Type *TypeMapTy::get(Type *Ty) {
246 Type *Result = getImpl(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000247
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000248 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000249 if (!SrcDefinitionsToResolve.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000250 linkDefinedTypeBodies();
251 return Result;
252}
253
Rafael Espindola18c89412014-10-27 02:35:46 +0000254/// This is the recursive version of get().
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000255Type *TypeMapTy::getImpl(Type *Ty) {
256 // If we already have an entry for this type, return it.
257 Type **Entry = &MappedTypes[Ty];
258 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000259
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000260 // If this is not a named struct type, then just map all of the elements and
261 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000262 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000263 // If there are no element types to map, then the type is itself. This is
264 // true for the anonymous {} struct, things like 'float', integers, etc.
265 if (Ty->getNumContainedTypes() == 0)
266 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000267
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000268 // Remap all of the elements, keeping track of whether any of them change.
269 bool AnyChange = false;
270 SmallVector<Type*, 4> ElementTypes;
271 ElementTypes.resize(Ty->getNumContainedTypes());
272 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
273 ElementTypes[i] = getImpl(Ty->getContainedType(i));
274 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
275 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000276
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000277 // If we found our type while recursively processing stuff, just use it.
278 Entry = &MappedTypes[Ty];
279 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000280
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000281 // If all of the element types mapped directly over, then the type is usable
282 // as-is.
283 if (!AnyChange)
284 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000285
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000286 // Otherwise, rebuild a modified type.
287 switch (Ty->getTypeID()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000288 default: llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000289 case Type::ArrayTyID:
290 return *Entry = ArrayType::get(ElementTypes[0],
291 cast<ArrayType>(Ty)->getNumElements());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000292 case Type::VectorTyID:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000293 return *Entry = VectorType::get(ElementTypes[0],
294 cast<VectorType>(Ty)->getNumElements());
295 case Type::PointerTyID:
296 return *Entry = PointerType::get(ElementTypes[0],
297 cast<PointerType>(Ty)->getAddressSpace());
298 case Type::FunctionTyID:
299 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000300 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000301 cast<FunctionType>(Ty)->isVarArg());
302 case Type::StructTyID:
303 // Note that this is only reached for anonymous structs.
304 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
305 cast<StructType>(Ty)->isPacked());
306 }
307 }
308
309 // Otherwise, this is an unmapped named struct. If the struct can be directly
310 // mapped over, just use it as-is. This happens in a case when the linked-in
311 // module has something like:
312 // %T = type {%T*, i32}
313 // @GV = global %T* null
314 // where T does not exist at all in the destination module.
315 //
316 // The other case we watch for is when the type is not in the destination
317 // module, but that it has to be rebuilt because it refers to something that
318 // is already mapped. For example, if the destination module has:
319 // %A = type { i32 }
320 // and the source module has something like
321 // %A' = type { i32 }
322 // %B = type { %A'* }
323 // @GV = global %B* null
324 // then we want to create a new type: "%B = type { %A*}" and have it take the
325 // pristine "%B" name from the source module.
326 //
327 // To determine which case this is, we have to recursively walk the type graph
328 // speculating that we'll be able to reuse it unmodified. Only if this is
329 // safe would we map the entire thing over. Because this is an optimization,
330 // and is not required for the prettiness of the linked module, we just skip
331 // it and always rebuild a type here.
332 StructType *STy = cast<StructType>(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000333
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000334 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000335 if (STy->isOpaque()) {
336 // A named structure type from src module is used. Add it to the Set of
337 // identified structs in the destination module.
338 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000339 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000340 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000341
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000342 // Otherwise we create a new type and resolve its body later. This will be
343 // resolved by the top level of get().
Chris Lattner5e3bd972011-12-20 00:03:52 +0000344 SrcDefinitionsToResolve.push_back(STy);
345 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000346 // A new identified structure type was created. Add it to the set of
347 // identified structs in the destination module.
348 DstStructTypesSet.insert(DTy);
Chris Lattner5e3bd972011-12-20 00:03:52 +0000349 DstResolvedOpaqueTypes.insert(DTy);
350 return *Entry = DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000351}
352
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353//===----------------------------------------------------------------------===//
354// ModuleLinker implementation.
355//===----------------------------------------------------------------------===//
356
357namespace {
James Molloyf6f121e2013-05-28 15:17:05 +0000358 class ModuleLinker;
359
Rafael Espindola18c89412014-10-27 02:35:46 +0000360 /// Creates prototypes for functions that are lazily linked on the fly. This
361 /// speeds up linking for modules with many/ lazily linked functions of which
362 /// few get used.
James Molloyf6f121e2013-05-28 15:17:05 +0000363 class ValueMaterializerTy : public ValueMaterializer {
364 TypeMapTy &TypeMap;
365 Module *DstM;
366 std::vector<Function*> &LazilyLinkFunctions;
367 public:
368 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
369 std::vector<Function*> &LazilyLinkFunctions) :
370 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
371 LazilyLinkFunctions(LazilyLinkFunctions) {
372 }
373
Craig Topper85482992014-03-05 07:52:44 +0000374 Value *materializeValueFor(Value *V) override;
James Molloyf6f121e2013-05-28 15:17:05 +0000375 };
376
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000377 namespace {
378 class LinkDiagnosticInfo : public DiagnosticInfo {
379 const Twine &Msg;
380
381 public:
382 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
383 void print(DiagnosticPrinter &DP) const override;
384 };
385 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
386 const Twine &Msg)
387 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
388 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
389 }
390
Rafael Espindola18c89412014-10-27 02:35:46 +0000391 /// This is an implementation class for the LinkModules function, which is the
392 /// entrypoint for this file.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000393 class ModuleLinker {
394 Module *DstM, *SrcM;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000395
396 TypeMapTy TypeMap;
James Molloyf6f121e2013-05-28 15:17:05 +0000397 ValueMaterializerTy ValMaterializer;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000398
Rafael Espindola18c89412014-10-27 02:35:46 +0000399 /// Mapping of values from what they used to be in Src, to what they are now
400 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
401 /// due to the use of Value handles which the Linker doesn't actually need,
402 /// but this allows us to reuse the ValueMapper code.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403 ValueToValueMapTy ValueMap;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000404
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000405 struct AppendingVarInfo {
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000406 GlobalVariable *NewGV; // New aggregate global in dest module.
407 const Constant *DstInit; // Old initializer from dest module.
408 const Constant *SrcInit; // Old initializer from src module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 };
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000410
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000411 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000412
Tanya Lattnercbb91402011-10-11 00:24:54 +0000413 // Set of items not to link in from source.
414 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000415
Tanya Lattner0a48b872011-11-02 00:24:56 +0000416 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000417 std::vector<Function*> LazilyLinkFunctions;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000418
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000419 Linker::DiagnosticHandlerFunction DiagnosticHandler;
420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000421 public:
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000422 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000423 Linker::DiagnosticHandlerFunction DiagnosticHandler)
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000424 : DstM(dstM), SrcM(srcM), TypeMap(Set),
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000425 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000426 DiagnosticHandler(DiagnosticHandler) {}
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000427
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000428 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000429
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000430 private:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000431 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
432 const GlobalValue &Src);
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000433
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000434 /// Helper method for setting a message and returning an error code.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000435 bool emitError(const Twine &Message) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000436 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
Chris Lattner99953022008-06-16 18:27:53 +0000437 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000438 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000439
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000440 void emitWarning(const Twine &Message) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000441 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000442 }
443
David Majnemerdad0a642014-06-27 18:19:56 +0000444 bool getComdatLeader(Module *M, StringRef ComdatName,
445 const GlobalVariable *&GVar);
446 bool computeResultingSelectionKind(StringRef ComdatName,
447 Comdat::SelectionKind Src,
448 Comdat::SelectionKind Dst,
449 Comdat::SelectionKind &Result,
450 bool &LinkFromSrc);
451 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
452 ComdatsChosen;
453 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
454 bool &LinkFromSrc);
455
Rafael Espindola18c89412014-10-27 02:35:46 +0000456 /// This analyzes the two global values and determines what the result will
457 /// look like in the destination module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000458 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000459 GlobalValue::LinkageTypes &LT,
460 GlobalValue::VisibilityTypes &Vis,
461 bool &LinkFromSrc);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000462
Rafael Espindola18c89412014-10-27 02:35:46 +0000463 /// Given a global in the source module, return the global in the
464 /// destination module that is being linked to, if any.
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000465 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000466 // If the source has no name it can't link. If it has local linkage,
467 // there is no name match-up going on.
468 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000469 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000470
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000471 // Otherwise see if we have a match in the destination module's symtab.
472 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
Craig Topper2617dcc2014-04-15 06:32:26 +0000473 if (!DGV) return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000474
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000475 // If we found a global with the same name in the dest module, but it has
476 // internal linkage, we are really not doing any linkage here.
477 if (DGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000478 return nullptr;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000479
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000480 // Otherwise, we do in fact link to the destination global.
481 return DGV;
482 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000483
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000484 void computeTypeMapping();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000485
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000486 void upgradeMismatchedGlobalArray(StringRef Name);
487 void upgradeMismatchedGlobals();
488
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000489 bool linkAppendingVarProto(GlobalVariable *DstGV,
490 const GlobalVariable *SrcGV);
491 bool linkGlobalProto(const GlobalVariable *SrcGV);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000492 bool linkFunctionProto(Function *SrcF);
493 bool linkAliasProto(GlobalAlias *SrcA);
Bill Wendling66f02412012-02-11 11:38:06 +0000494 bool linkModuleFlagsMetadata();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000495
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000496 void linkAppendingVarInit(const AppendingVarInfo &AVI);
497 void linkGlobalInits();
498 void linkFunctionBody(Function *Dst, Function *Src);
499 void linkAliasBodies();
500 void linkNamedMDNodes();
501 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000502}
503
Rafael Espindola18c89412014-10-27 02:35:46 +0000504/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
505/// table. This is good for all clients except for us. Go through the trouble
506/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000507static void forceRenaming(GlobalValue *GV, StringRef Name) {
508 // If the global doesn't force its name or if it already has the right name,
509 // there is nothing for us to do.
510 if (GV->hasLocalLinkage() || GV->getName() == Name)
511 return;
512
513 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000514
515 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000516 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000517 GV->takeName(ConflictGV);
518 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000519 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000520 } else {
521 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000522 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000523}
Reid Spencer90246aa2007-02-04 04:29:21 +0000524
Rafael Espindola18c89412014-10-27 02:35:46 +0000525/// copy additional attributes (those not needed to construct a GlobalValue)
526/// from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000527static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000528 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000529 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000530 unsigned Alignment;
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000531 if (DestGO)
532 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000533
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000534 DestGV->copyAttributesFrom(SrcGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000535
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000536 if (DestGO)
537 DestGO->setAlignment(Alignment);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000538
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000539 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000540}
541
Rafael Espindola23f8d642012-01-05 23:02:01 +0000542static bool isLessConstraining(GlobalValue::VisibilityTypes a,
543 GlobalValue::VisibilityTypes b) {
544 if (a == GlobalValue::HiddenVisibility)
545 return false;
546 if (b == GlobalValue::HiddenVisibility)
547 return true;
548 if (a == GlobalValue::ProtectedVisibility)
549 return false;
550 if (b == GlobalValue::ProtectedVisibility)
551 return true;
552 return false;
553}
554
James Molloyf6f121e2013-05-28 15:17:05 +0000555Value *ValueMaterializerTy::materializeValueFor(Value *V) {
556 Function *SF = dyn_cast<Function>(V);
557 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000558 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000559
560 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
561 SF->getLinkage(), SF->getName(), DstM);
562 copyGVAttributes(DF, SF);
563
Rafael Espindola3931c282014-08-15 20:17:08 +0000564 if (Comdat *SC = SF->getComdat()) {
565 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
566 DF->setComdat(DC);
567 }
568
James Molloyf6f121e2013-05-28 15:17:05 +0000569 LazilyLinkFunctions.push_back(SF);
570 return DF;
571}
572
David Majnemerdad0a642014-06-27 18:19:56 +0000573bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
574 const GlobalVariable *&GVar) {
575 const GlobalValue *GVal = M->getNamedValue(ComdatName);
576 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
577 GVal = GA->getBaseObject();
578 if (!GVal)
579 // We cannot resolve the size of the aliasee yet.
580 return emitError("Linking COMDATs named '" + ComdatName +
581 "': COMDAT key involves incomputable alias size.");
582 }
583
584 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
585 if (!GVar)
586 return emitError(
587 "Linking COMDATs named '" + ComdatName +
588 "': GlobalVariable required for data dependent selection!");
589
590 return false;
591}
592
593bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
594 Comdat::SelectionKind Src,
595 Comdat::SelectionKind Dst,
596 Comdat::SelectionKind &Result,
597 bool &LinkFromSrc) {
598 // The ability to mix Comdat::SelectionKind::Any with
599 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
600 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
601 Dst == Comdat::SelectionKind::Largest;
602 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
603 Src == Comdat::SelectionKind::Largest;
604 if (DstAnyOrLargest && SrcAnyOrLargest) {
605 if (Dst == Comdat::SelectionKind::Largest ||
606 Src == Comdat::SelectionKind::Largest)
607 Result = Comdat::SelectionKind::Largest;
608 else
609 Result = Comdat::SelectionKind::Any;
610 } else if (Src == Dst) {
611 Result = Dst;
612 } else {
613 return emitError("Linking COMDATs named '" + ComdatName +
614 "': invalid selection kinds!");
615 }
616
617 switch (Result) {
618 case Comdat::SelectionKind::Any:
619 // Go with Dst.
620 LinkFromSrc = false;
621 break;
622 case Comdat::SelectionKind::NoDuplicates:
623 return emitError("Linking COMDATs named '" + ComdatName +
624 "': noduplicates has been violated!");
625 case Comdat::SelectionKind::ExactMatch:
626 case Comdat::SelectionKind::Largest:
627 case Comdat::SelectionKind::SameSize: {
628 const GlobalVariable *DstGV;
629 const GlobalVariable *SrcGV;
630 if (getComdatLeader(DstM, ComdatName, DstGV) ||
631 getComdatLeader(SrcM, ComdatName, SrcGV))
632 return true;
633
634 const DataLayout *DstDL = DstM->getDataLayout();
635 const DataLayout *SrcDL = SrcM->getDataLayout();
636 if (!DstDL || !SrcDL) {
637 return emitError(
638 "Linking COMDATs named '" + ComdatName +
639 "': can't do size dependent selection without DataLayout!");
640 }
641 uint64_t DstSize =
642 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
643 uint64_t SrcSize =
644 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
645 if (Result == Comdat::SelectionKind::ExactMatch) {
646 if (SrcGV->getInitializer() != DstGV->getInitializer())
647 return emitError("Linking COMDATs named '" + ComdatName +
648 "': ExactMatch violated!");
649 LinkFromSrc = false;
650 } else if (Result == Comdat::SelectionKind::Largest) {
651 LinkFromSrc = SrcSize > DstSize;
652 } else if (Result == Comdat::SelectionKind::SameSize) {
653 if (SrcSize != DstSize)
654 return emitError("Linking COMDATs named '" + ComdatName +
655 "': SameSize violated!");
656 LinkFromSrc = false;
657 } else {
658 llvm_unreachable("unknown selection kind");
659 }
660 break;
661 }
662 }
663
664 return false;
665}
666
667bool ModuleLinker::getComdatResult(const Comdat *SrcC,
668 Comdat::SelectionKind &Result,
669 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +0000670 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000671 StringRef ComdatName = SrcC->getName();
672 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
673 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000674
Rafael Espindolab16196a2014-08-11 17:07:34 +0000675 if (DstCI == ComdatSymTab.end()) {
676 // Use the comdat if it is only available in one of the modules.
677 LinkFromSrc = true;
678 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000679 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000680 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000681
682 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000683 Comdat::SelectionKind DSK = DstC->getSelectionKind();
684 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
685 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000686}
James Molloyf6f121e2013-05-28 15:17:05 +0000687
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000688bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
689 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000690 const GlobalValue &Src) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000691 bool SrcIsDeclaration = Src.isDeclarationForLinker();
692 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000693
694 if (SrcIsDeclaration) {
695 // If Src is external or if both Src & Dest are external.. Just link the
696 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000697 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000698 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000699 LinkFromSrc = DestIsDeclaration;
700 return false;
701 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000702 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000703 LinkFromSrc = Dest.hasExternalWeakLinkage();
704 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000705 }
706
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000707 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000708 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000709 LinkFromSrc = true;
710 return false;
711 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000712
Rafael Espindola09106052014-09-09 15:59:12 +0000713 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000714 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
715 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000716 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000717 }
718
719 if (!Dest.hasCommonLinkage()) {
720 LinkFromSrc = false;
721 return false;
722 }
Rafael Espindola09106052014-09-09 15:59:12 +0000723
Rafael Espindola0ae225b2014-10-31 04:46:38 +0000724 // FIXME: Make datalayout mandatory and just use getDataLayout().
725 DataLayout DL(Dest.getParent());
726
Rafael Espindola09106052014-09-09 15:59:12 +0000727 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
728 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000729 LinkFromSrc = SrcSize > DestSize;
730 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000731 }
732
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000733 if (Src.isWeakForLinker()) {
734 assert(!Dest.hasExternalWeakLinkage());
735 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000736
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000737 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
738 LinkFromSrc = true;
739 return false;
740 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000741
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000742 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000743 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000744 }
745
746 if (Dest.isWeakForLinker()) {
747 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000748 LinkFromSrc = true;
749 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000750 }
751
752 assert(!Src.hasExternalWeakLinkage());
753 assert(!Dest.hasExternalWeakLinkage());
754 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
755 "Unexpected linkage type!");
756 return emitError("Linking globals named '" + Src.getName() +
757 "': symbol multiply defined!");
758}
759
Rafael Espindola83a7ddb2014-09-09 14:07:40 +0000760/// This analyzes the two global values and determines what the result will look
761/// like in the destination module. In particular, it computes the resultant
762/// linkage type and visibility, computes whether the global in the source
763/// should be copied over to the destination (replacing the existing one), and
764/// computes whether this linkage is an error or not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000765bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Rafael Espindola23f8d642012-01-05 23:02:01 +0000766 GlobalValue::LinkageTypes &LT,
767 GlobalValue::VisibilityTypes &Vis,
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000768 bool &LinkFromSrc) {
769 assert(Dest && "Must have two globals being queried");
770 assert(!Src->hasLocalLinkage() &&
Chris Lattnerfc61de32004-12-03 22:18:41 +0000771 "If Src has internal linkage, Dest shouldn't be set!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000772
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000773 if (shouldLinkFromSource(LinkFromSrc, *Dest, *Src))
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000774 return true;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000775
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000776 if (LinkFromSrc)
Chris Lattnerfc61de32004-12-03 22:18:41 +0000777 LT = Src->getLinkage();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000778 else
779 LT = Dest->getLinkage();
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000780
Rafael Espindola23f8d642012-01-05 23:02:01 +0000781 // Compute the visibility. We follow the rules in the System V Application
782 // Binary Interface.
Duncan P. N. Exon Smithb2becfd2014-05-07 22:55:46 +0000783 assert(!GlobalValue::isLocalLinkage(LT) &&
784 "Symbols with local linkage should not be merged");
Rafael Espindola23f8d642012-01-05 23:02:01 +0000785 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
786 Dest->getVisibility() : Src->getVisibility();
Chris Lattnerfc61de32004-12-03 22:18:41 +0000787 return false;
788}
Reid Spencer361e5132004-11-12 20:37:43 +0000789
Rafael Espindola18c89412014-10-27 02:35:46 +0000790/// Loop over all of the linked values to compute type mappings. For example,
791/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
792/// types 'Foo' but one got renamed when the module was loaded into the same
793/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000794void ModuleLinker::computeTypeMapping() {
795 // Incorporate globals.
796 for (Module::global_iterator I = SrcM->global_begin(),
797 E = SrcM->global_end(); I != E; ++I) {
798 GlobalValue *DGV = getLinkedToGlobal(I);
Craig Topper2617dcc2014-04-15 06:32:26 +0000799 if (!DGV) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000800
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000801 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
802 TypeMap.addTypeMapping(DGV->getType(), I->getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000803 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000804 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000805
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000806 // Unify the element type of appending arrays.
807 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
808 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
809 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000810 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000811
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000812 // Incorporate functions.
813 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
814 if (GlobalValue *DGV = getLinkedToGlobal(I))
815 TypeMap.addTypeMapping(DGV->getType(), I->getType());
816 }
Bill Wendling7b464612012-02-27 22:34:19 +0000817
Bill Wendlingd48b7782012-02-28 04:01:21 +0000818 // Incorporate types by name, scanning all the types in the source module.
819 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000820 // example. When the source module got loaded into the same LLVMContext, if
821 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000822 TypeFinder SrcStructTypes;
823 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000824 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
825 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000826
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000827 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
828 StructType *ST = SrcStructTypes[i];
829 if (!ST->hasName()) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000830
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000831 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000832 size_t DotPos = ST->getName().rfind('.');
833 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000834 ST->getName().back() == '.' ||
835 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000836 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000837
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000838 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000839 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000840 // Don't use it if this actually came from the source module. They're in
841 // the same LLVMContext after all. Also don't use it unless the type is
842 // actually used in the destination module. This can happen in situations
843 // like this:
844 //
845 // Module A Module B
846 // -------- --------
847 // %Z = type { %A } %B = type { %C.1 }
848 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
849 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
850 // %C = type { i8* } %B.3 = type { %C.1 }
851 //
852 // When we link Module B with Module A, the '%B' in Module B is
853 // used. However, that would then use '%C.1'. But when we process '%C.1',
854 // we prefer to take the '%C' version. So we are then left with both
855 // '%C.1' and '%C' being used for the same types. This leads to some
856 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000857 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000858 TypeMap.addTypeMapping(DST, ST);
859 }
860
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000861 // Don't bother incorporating aliases, they aren't generally typed well.
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000862
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000863 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000864 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000865 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000866}
867
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000868static void upgradeGlobalArray(GlobalVariable *GV) {
869 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
870 StructType *OldTy = cast<StructType>(ATy->getElementType());
871 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
872
873 // Get the upgraded 3 element type.
874 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
875 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
876 VoidPtrTy};
877 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
878
879 // Build new constants with a null third field filled in.
880 Constant *OldInitC = GV->getInitializer();
881 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
882 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
883 // Invalid initializer; give up.
884 return;
885 std::vector<Constant *> Initializers;
886 if (OldInit && OldInit->getNumOperands()) {
887 Value *Null = Constant::getNullValue(VoidPtrTy);
888 for (Use &U : OldInit->operands()) {
889 ConstantStruct *Init = cast<ConstantStruct>(U.get());
890 Initializers.push_back(ConstantStruct::get(
891 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
892 }
893 }
894 assert(Initializers.size() == ATy->getNumElements() &&
895 "Failed to copy all array elements");
896
897 // Replace the old GV with a new one.
898 ATy = ArrayType::get(NewTy, Initializers.size());
899 Constant *NewInit = ConstantArray::get(ATy, Initializers);
900 GlobalVariable *NewGV = new GlobalVariable(
901 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
902 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
903 GV->isExternallyInitialized());
904 NewGV->copyAttributesFrom(GV);
905 NewGV->takeName(GV);
906 assert(GV->use_empty() && "program cannot use initializer list");
907 GV->eraseFromParent();
908}
909
910void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
911 // Look for the global arrays.
912 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
913 if (!DstGV)
914 return;
915 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
916 if (!SrcGV)
917 return;
918
919 // Check if the types already match.
920 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
921 auto *SrcTy =
922 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
923 if (DstTy == SrcTy)
924 return;
925
926 // Grab the element types. We can only upgrade an array of a two-field
927 // struct. Only bother if the other one has three-fields.
928 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
929 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
930 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
931 upgradeGlobalArray(DstGV);
932 return;
933 }
934 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
935 upgradeGlobalArray(SrcGV);
936
937 // We can't upgrade any other differences.
938}
939
940void ModuleLinker::upgradeMismatchedGlobals() {
941 upgradeMismatchedGlobalArray("llvm.global_ctors");
942 upgradeMismatchedGlobalArray("llvm.global_dtors");
943}
944
Rafael Espindola18c89412014-10-27 02:35:46 +0000945/// If there were any appending global variables, link them together now.
946/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000947bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000948 const GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000950 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
951 return emitError("Linking globals named '" + SrcGV->getName() +
952 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000953
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000954 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
955 ArrayType *SrcTy =
956 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
957 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000958
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000959 // Check to see that they two arrays agree on type.
960 if (EltTy != SrcTy->getElementType())
961 return emitError("Appending variables with different element types!");
962 if (DstGV->isConstant() != SrcGV->isConstant())
963 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000964
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000965 if (DstGV->getAlignment() != SrcGV->getAlignment())
966 return emitError(
967 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000968
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000969 if (DstGV->getVisibility() != SrcGV->getVisibility())
970 return emitError(
971 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000972
973 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
974 return emitError(
975 "Appending variables with different unnamed_addr need to be linked!");
976
Rafael Espindola64c1e182014-06-03 02:41:57 +0000977 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000978 return emitError(
979 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000980
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000981 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
982 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000983
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000984 // Create the new global variable.
985 GlobalVariable *NG =
986 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000987 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000988 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000989 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000990
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000991 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000992 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000993
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000994 AppendingVarInfo AVI;
995 AVI.NewGV = NG;
996 AVI.DstInit = DstGV->getInitializer();
997 AVI.SrcInit = SrcGV->getInitializer();
998 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000999
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001000 // Replace any uses of the two global variables with uses of the new
1001 // global.
1002 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +00001003
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001004 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1005 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001006
Tanya Lattnercbb91402011-10-11 00:24:54 +00001007 // Track the source variable so we don't try to link it.
1008 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001009
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001010 return false;
1011}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001012
Rafael Espindola18c89412014-10-27 02:35:46 +00001013/// Loop through the global variables in the src module and merge them into the
1014/// dest module.
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001015bool ModuleLinker::linkGlobalProto(const GlobalVariable *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001016 GlobalValue *DGV = getLinkedToGlobal(SGV);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001017 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolad4885da2013-09-04 14:05:09 +00001018 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001019 unsigned Alignment = SGV->getAlignment();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001020
David Majnemerdad0a642014-06-27 18:19:56 +00001021 bool LinkFromSrc = false;
1022 Comdat *DC = nullptr;
1023 if (const Comdat *SC = SGV->getComdat()) {
1024 Comdat::SelectionKind SK;
1025 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1026 DC = DstM->getOrInsertComdat(SC->getName());
1027 DC->setSelectionKind(SK);
1028 }
1029
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001030 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001031 if (!DC) {
1032 // Concatenation of appending linkage variables is magic and handled later.
1033 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
1034 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001035
David Majnemerdad0a642014-06-27 18:19:56 +00001036 // Determine whether linkage of these two globals follows the source
1037 // module's definition or the destination module's definition.
1038 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1039 GlobalValue::VisibilityTypes NV;
1040 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1041 return true;
1042 NewVisibility = NV;
1043 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001044 if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1045 Alignment = std::max(Alignment, DGV->getAlignment());
1046 else if (!LinkFromSrc)
1047 Alignment = DGV->getAlignment();
Reid Spencer361e5132004-11-12 20:37:43 +00001048
David Majnemerdad0a642014-06-27 18:19:56 +00001049 // If we're not linking from the source, then keep the definition that we
1050 // have.
1051 if (!LinkFromSrc) {
1052 // Special case for const propagation.
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001053 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
1054 DGVar->setAlignment(Alignment);
1055
Rafael Espindolad1e64b12014-10-30 20:50:23 +00001056 if (DGVar->isDeclaration() && !SGV->isConstant())
1057 DGVar->setConstant(false);
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001058 }
David Majnemerdad0a642014-06-27 18:19:56 +00001059
1060 // Set calculated linkage, visibility and unnamed_addr.
1061 DGV->setLinkage(NewLinkage);
1062 DGV->setVisibility(*NewVisibility);
1063 DGV->setUnnamedAddr(HasUnnamedAddr);
1064 }
1065 }
1066
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001067 if (!LinkFromSrc) {
Chris Lattner0ead7a52008-07-14 07:23:24 +00001068 // Make sure to remember this mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001069 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001070
1071 // Track the source global so that we don't attempt to copy it over when
Tanya Lattnercbb91402011-10-11 00:24:54 +00001072 // processing global initializers.
1073 DoNotLinkFromSource.insert(SGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001074
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001075 return false;
Chris Lattner0ead7a52008-07-14 07:23:24 +00001076 }
Reid Spencer361e5132004-11-12 20:37:43 +00001077 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001078
David Majnemerdad0a642014-06-27 18:19:56 +00001079 // If the Comdat this variable was inside of wasn't selected, skip it.
1080 if (DC && !DGV && !LinkFromSrc) {
1081 DoNotLinkFromSource.insert(SGV);
1082 return false;
1083 }
1084
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001085 // No linking to be performed or linking from the source: simply create an
1086 // identical version of the symbol over in the dest module... the
1087 // initializer will be filled in later by LinkGlobalInits.
1088 GlobalVariable *NewDGV =
1089 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
Craig Topper2617dcc2014-04-15 06:32:26 +00001090 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
1091 SGV->getName(), /*insertbefore*/nullptr,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001092 SGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001093 SGV->getType()->getAddressSpace());
1094 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001095 copyGVAttributes(NewDGV, SGV);
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001096 NewDGV->setAlignment(Alignment);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001097 if (NewVisibility)
1098 NewDGV->setVisibility(*NewVisibility);
Rafael Espindolad4885da2013-09-04 14:05:09 +00001099 NewDGV->setUnnamedAddr(HasUnnamedAddr);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001100
David Majnemerdad0a642014-06-27 18:19:56 +00001101 if (DC)
1102 NewDGV->setComdat(DC);
1103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001104 if (DGV) {
1105 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1106 DGV->eraseFromParent();
1107 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001108
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001109 // Make sure to remember this mapping.
1110 ValueMap[SGV] = NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001111 return false;
1112}
1113
Rafael Espindola18c89412014-10-27 02:35:46 +00001114/// Link the function in the source module into the destination module if
1115/// needed, setting up mapping information.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001116bool ModuleLinker::linkFunctionProto(Function *SF) {
1117 GlobalValue *DGV = getLinkedToGlobal(SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001118 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindolafd9a9412013-09-04 14:59:03 +00001119 bool HasUnnamedAddr = SF->hasUnnamedAddr();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001120
David Majnemerdad0a642014-06-27 18:19:56 +00001121 bool LinkFromSrc = false;
1122 Comdat *DC = nullptr;
1123 if (const Comdat *SC = SF->getComdat()) {
1124 Comdat::SelectionKind SK;
1125 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1126 DC = DstM->getOrInsertComdat(SC->getName());
1127 DC->setSelectionKind(SK);
1128 }
1129
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001130 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001131 if (!DC) {
1132 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1133 GlobalValue::VisibilityTypes NV;
1134 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
1135 return true;
1136 NewVisibility = NV;
1137 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1138
1139 if (!LinkFromSrc) {
1140 // Set calculated linkage
1141 DGV->setLinkage(NewLinkage);
1142 DGV->setVisibility(*NewVisibility);
1143 DGV->setUnnamedAddr(HasUnnamedAddr);
1144 }
1145 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001146
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001147 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001148 // Make sure to remember this mapping.
1149 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001150
1151 // Track the function from the source module so we don't attempt to remap
Tanya Lattnercbb91402011-10-11 00:24:54 +00001152 // it.
1153 DoNotLinkFromSource.insert(SF);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001154
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001155 return false;
1156 }
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001157 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001158
James Molloyf6f121e2013-05-28 15:17:05 +00001159 // If the function is to be lazily linked, don't create it just yet.
1160 // The ValueMaterializerTy will deal with creating it if it's used.
1161 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1162 SF->hasAvailableExternallyLinkage())) {
1163 DoNotLinkFromSource.insert(SF);
1164 return false;
1165 }
1166
David Majnemerdad0a642014-06-27 18:19:56 +00001167 // If the Comdat this function was inside of wasn't selected, skip it.
1168 if (DC && !DGV && !LinkFromSrc) {
1169 DoNotLinkFromSource.insert(SF);
1170 return false;
1171 }
1172
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001173 // If there is no linkage to be performed or we are linking from the source,
1174 // bring SF over.
1175 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1176 SF->getLinkage(), SF->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001177 copyGVAttributes(NewDF, SF);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001178 if (NewVisibility)
1179 NewDF->setVisibility(*NewVisibility);
Rafael Espindolafd9a9412013-09-04 14:59:03 +00001180 NewDF->setUnnamedAddr(HasUnnamedAddr);
Anton Korobeynikovdac5fa92008-03-05 22:22:46 +00001181
David Majnemerdad0a642014-06-27 18:19:56 +00001182 if (DC)
1183 NewDF->setComdat(DC);
1184
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001185 if (DGV) {
1186 // Any uses of DF need to change to NewDF, with cast.
1187 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1188 DGV->eraseFromParent();
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001189 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001190
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001191 ValueMap[SF] = NewDF;
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001192 return false;
1193}
1194
Rafael Espindola18c89412014-10-27 02:35:46 +00001195/// Set up prototypes for any aliases that come over from the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001196bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1197 GlobalValue *DGV = getLinkedToGlobal(SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001198 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001199 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
Rafael Espindola23f8d642012-01-05 23:02:01 +00001200
David Majnemerdad0a642014-06-27 18:19:56 +00001201 bool LinkFromSrc = false;
1202 Comdat *DC = nullptr;
1203 if (const Comdat *SC = SGA->getComdat()) {
1204 Comdat::SelectionKind SK;
1205 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1206 DC = DstM->getOrInsertComdat(SC->getName());
1207 DC->setSelectionKind(SK);
1208 }
1209
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001210 if (DGV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001211 if (!DC) {
1212 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1213 GlobalValue::VisibilityTypes NV;
1214 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1215 return true;
1216 NewVisibility = NV;
1217 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1218
1219 if (!LinkFromSrc) {
1220 // Set calculated linkage.
1221 DGV->setLinkage(NewLinkage);
1222 DGV->setVisibility(*NewVisibility);
1223 DGV->setUnnamedAddr(HasUnnamedAddr);
1224 }
1225 }
Rafael Espindola23f8d642012-01-05 23:02:01 +00001226
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001227 if (!LinkFromSrc) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001228 // Make sure to remember this mapping.
1229 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001230
Tanya Lattnercbb91402011-10-11 00:24:54 +00001231 // Track the alias from the source module so we don't attempt to remap it.
1232 DoNotLinkFromSource.insert(SGA);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001233
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001234 return false;
1235 }
1236 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001237
David Majnemerdad0a642014-06-27 18:19:56 +00001238 // If the Comdat this alias was inside of wasn't selected, skip it.
1239 if (DC && !DGV && !LinkFromSrc) {
1240 DoNotLinkFromSource.insert(SGA);
1241 return false;
1242 }
1243
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001244 // If there is no linkage to be performed or we're linking from the source,
1245 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +00001246 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001247 auto *NewDA =
1248 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1249 SGA->getLinkage(), SGA->getName(), DstM);
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001250 copyGVAttributes(NewDA, SGA);
Rafael Espindola23f8d642012-01-05 23:02:01 +00001251 if (NewVisibility)
1252 NewDA->setVisibility(*NewVisibility);
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001253 NewDA->setUnnamedAddr(HasUnnamedAddr);
Reid Spencer361e5132004-11-12 20:37:43 +00001254
Rafael Espindola64c1e182014-06-03 02:41:57 +00001255 if (DGV) {
1256 // Any uses of DGV need to change to NewDA, with cast.
1257 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1258 DGV->eraseFromParent();
1259 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001260
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001261 ValueMap[SGA] = NewDA;
1262 return false;
1263}
1264
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001265static void getArrayElements(const Constant *C,
1266 SmallVectorImpl<Constant *> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001267 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1268
1269 for (unsigned i = 0; i != NumElements; ++i)
1270 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001271}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001272
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001273void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1274 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001275 SmallVector<Constant *, 16> DstElements;
1276 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001277
Rafael Espindolad31dc042014-09-05 21:27:52 +00001278 SmallVector<Constant *, 16> SrcElements;
1279 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001280
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001281 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001282
1283 StringRef Name = AVI.NewGV->getName();
1284 bool IsNewStructor =
1285 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1286 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1287
1288 for (auto *V : SrcElements) {
1289 if (IsNewStructor) {
1290 Constant *Key = V->getAggregateElement(2);
1291 if (DoNotLinkFromSource.count(Key))
1292 continue;
1293 }
1294 DstElements.push_back(
1295 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1296 }
1297 if (IsNewStructor) {
1298 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1299 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1300 }
1301
1302 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001303}
1304
Rafael Espindola18c89412014-10-27 02:35:46 +00001305/// Update the initializers in the Dest module now that all globals that may be
1306/// referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001307void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +00001308 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001309 for (Module::const_global_iterator I = SrcM->global_begin(),
1310 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001311
Tanya Lattnercbb91402011-10-11 00:24:54 +00001312 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001313 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1314
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001315 // Grab destination global variable.
1316 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1317 // Figure out what the initializer looks like in the dest module.
1318 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001319 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001320 }
Reid Spencer361e5132004-11-12 20:37:43 +00001321}
1322
Rafael Espindola18c89412014-10-27 02:35:46 +00001323/// Copy the source function over into the dest function and fix up references
1324/// to values. At this point we know that Dest is an external function, and
1325/// that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001326void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1327 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001328
Chris Lattner7391dde2004-11-16 17:12:38 +00001329 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001330 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001331 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +00001332 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001333 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001334
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001335 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +00001336 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001337 }
1338
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001339 // Splice the body of the source function into the dest function.
1340 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001341
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001342 // At this point, all of the instructions and values of the function are now
1343 // copied over. The only problem is that they are still referencing values in
1344 // the Source function as operands. Loop through all of the operands of the
1345 // functions and patch them up to point to the local versions.
1346 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1347 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1348 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1349 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001350
Chris Lattner7391dde2004-11-16 17:12:38 +00001351 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001352 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1353 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001354 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001355
Reid Spencer361e5132004-11-12 20:37:43 +00001356}
1357
Rafael Espindola18c89412014-10-27 02:35:46 +00001358/// Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001359void ModuleLinker::linkAliasBodies() {
1360 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001361 I != E; ++I) {
1362 if (DoNotLinkFromSource.count(I))
1363 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001364 if (Constant *Aliasee = I->getAliasee()) {
1365 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001366 Constant *Val =
1367 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Rafael Espindola64c1e182014-06-03 02:41:57 +00001368 DA->setAliasee(Val);
David Chisnall2c4a34a2010-01-09 16:27:31 +00001369 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001370 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001371}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001372
Rafael Espindola18c89412014-10-27 02:35:46 +00001373/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001374void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001375 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001376 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1377 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001378 // Don't link module flags here. Do them separately.
1379 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001380 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1381 // Add Src elements into Dest node.
1382 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1383 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001384 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001385 }
1386}
Bill Wendling66f02412012-02-11 11:38:06 +00001387
Rafael Espindola18c89412014-10-27 02:35:46 +00001388/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001389bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001390 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001391 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1392 if (!SrcModFlags) return false;
1393
Bill Wendling66f02412012-02-11 11:38:06 +00001394 // If the destination module doesn't have module flags yet, then just copy
1395 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001396 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001397 if (DstModFlags->getNumOperands() == 0) {
1398 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1399 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1400
1401 return false;
1402 }
1403
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001404 // First build a map of the existing module flags and requirements.
1405 DenseMap<MDString*, MDNode*> Flags;
1406 SmallSetVector<MDNode*, 16> Requirements;
1407 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1408 MDNode *Op = DstModFlags->getOperand(I);
1409 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1410 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001411
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001412 if (Behavior->getZExtValue() == Module::Require) {
1413 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1414 } else {
1415 Flags[ID] = Op;
1416 }
Bill Wendling66f02412012-02-11 11:38:06 +00001417 }
1418
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001419 // Merge in the flags from the source module, and also collect its set of
1420 // requirements.
1421 bool HasErr = false;
1422 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1423 MDNode *SrcOp = SrcModFlags->getOperand(I);
1424 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1425 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1426 MDNode *DstOp = Flags.lookup(ID);
1427 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001428
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001429 // If this is a requirement, add it and continue.
1430 if (SrcBehaviorValue == Module::Require) {
1431 // If the destination module does not already have this requirement, add
1432 // it.
1433 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1434 DstModFlags->addOperand(SrcOp);
1435 }
1436 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001437 }
1438
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001439 // If there is no existing flag with this ID, just add it.
1440 if (!DstOp) {
1441 Flags[ID] = SrcOp;
1442 DstModFlags->addOperand(SrcOp);
1443 continue;
1444 }
1445
1446 // Otherwise, perform a merge.
1447 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1448 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1449
1450 // If either flag has override behavior, handle it first.
1451 if (DstBehaviorValue == Module::Override) {
1452 // Diagnose inconsistent flags which both have override behavior.
1453 if (SrcBehaviorValue == Module::Override &&
1454 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1455 HasErr |= emitError("linking module flags '" + ID->getString() +
1456 "': IDs have conflicting override values");
1457 }
1458 continue;
1459 } else if (SrcBehaviorValue == Module::Override) {
1460 // Update the destination flag to that of the source.
1461 DstOp->replaceOperandWith(0, SrcBehavior);
1462 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1463 continue;
1464 }
1465
1466 // Diagnose inconsistent merge behavior types.
1467 if (SrcBehaviorValue != DstBehaviorValue) {
1468 HasErr |= emitError("linking module flags '" + ID->getString() +
1469 "': IDs have conflicting behaviors");
1470 continue;
1471 }
1472
1473 // Perform the merge for standard behavior types.
1474 switch (SrcBehaviorValue) {
1475 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001476 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001477 case Module::Error: {
1478 // Emit an error if the values differ.
1479 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1480 HasErr |= emitError("linking module flags '" + ID->getString() +
1481 "': IDs have conflicting values");
1482 }
1483 continue;
1484 }
1485 case Module::Warning: {
1486 // Emit a warning if the values differ.
1487 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001488 emitWarning("linking module flags '" + ID->getString() +
1489 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001490 }
1491 continue;
1492 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001493 case Module::Append: {
1494 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1495 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1496 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1497 Value **VP, **Values = VP = new Value*[NumOps];
1498 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1499 *VP = DstValue->getOperand(i);
1500 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1501 *VP = SrcValue->getOperand(i);
1502 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1503 ArrayRef<Value*>(Values,
1504 NumOps)));
1505 delete[] Values;
1506 break;
1507 }
1508 case Module::AppendUnique: {
1509 SmallSetVector<Value*, 16> Elts;
1510 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1511 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1512 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1513 Elts.insert(DstValue->getOperand(i));
1514 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1515 Elts.insert(SrcValue->getOperand(i));
1516 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1517 ArrayRef<Value*>(Elts.begin(),
1518 Elts.end())));
1519 break;
1520 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001521 }
Bill Wendling66f02412012-02-11 11:38:06 +00001522 }
1523
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001524 // Check all of the requirements.
1525 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1526 MDNode *Requirement = Requirements[I];
1527 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1528 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001529
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001530 MDNode *Op = Flags[Flag];
1531 if (!Op || Op->getOperand(2) != ReqValue) {
1532 HasErr |= emitError("linking module flags '" + Flag->getString() +
1533 "': does not have the required value");
1534 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001535 }
1536 }
1537
1538 return HasErr;
1539}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001540
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001541bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001542 assert(DstM && "Null destination module");
1543 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001544
1545 // Inherit the target data from the source module if the destination module
1546 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001547 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001548 DstM->setDataLayout(SrcM->getDataLayout());
1549
1550 // Copy the target triple from the source to dest if the dest's is empty.
1551 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1552 DstM->setTargetTriple(SrcM->getTargetTriple());
1553
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001554 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001555 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001556 emitWarning("Linking two modules of different data layouts: '" +
1557 SrcM->getModuleIdentifier() + "' is '" +
1558 SrcM->getDataLayoutStr() + "' whereas '" +
1559 DstM->getModuleIdentifier() + "' is '" +
1560 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001561 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001562 if (!SrcM->getTargetTriple().empty() &&
1563 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001564 emitWarning("Linking two modules of different target triples: " +
1565 SrcM->getModuleIdentifier() + "' is '" +
1566 SrcM->getTargetTriple() + "' whereas '" +
1567 DstM->getModuleIdentifier() + "' is '" +
1568 DstM->getTargetTriple() + "'\n");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001569 }
1570
1571 // Append the module inline asm string.
1572 if (!SrcM->getModuleInlineAsm().empty()) {
1573 if (DstM->getModuleInlineAsm().empty())
1574 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1575 else
1576 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1577 SrcM->getModuleInlineAsm());
1578 }
1579
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001580 // Loop over all of the linked values to compute type mappings.
1581 computeTypeMapping();
1582
David Majnemerdad0a642014-06-27 18:19:56 +00001583 ComdatsChosen.clear();
1584 for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1585 const Comdat &C = SMEC.getValue();
1586 if (ComdatsChosen.count(&C))
1587 continue;
1588 Comdat::SelectionKind SK;
1589 bool LinkFromSrc;
1590 if (getComdatResult(&C, SK, LinkFromSrc))
1591 return true;
1592 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1593 }
1594
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001595 // Upgrade mismatched global arrays.
1596 upgradeMismatchedGlobals();
1597
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001598 // Insert all of the globals in src into the DstM module... without linking
1599 // initializers (which could refer to functions not yet mapped over).
1600 for (Module::global_iterator I = SrcM->global_begin(),
1601 E = SrcM->global_end(); I != E; ++I)
1602 if (linkGlobalProto(I))
1603 return true;
1604
1605 // Link the functions together between the two modules, without doing function
1606 // bodies... this just adds external function prototypes to the DstM
1607 // function... We do this so that when we begin processing function bodies,
1608 // all of the global values that may be referenced are available in our
1609 // ValueMap.
1610 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1611 if (linkFunctionProto(I))
1612 return true;
1613
1614 // If there were any aliases, link them now.
1615 for (Module::alias_iterator I = SrcM->alias_begin(),
1616 E = SrcM->alias_end(); I != E; ++I)
1617 if (linkAliasProto(I))
1618 return true;
1619
1620 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1621 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001622
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001623 // Link in the function bodies that are defined in the source module into
1624 // DstM.
1625 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001626 // Skip if not linking from source.
1627 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001628
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001629 Function *DF = cast<Function>(ValueMap[SF]);
1630 if (SF->hasPrefixData()) {
1631 // Link in the prefix data.
1632 DF->setPrefixData(MapValue(
1633 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1634 }
1635
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001636 // Materialize if needed.
1637 if (SF->isMaterializable()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001638 if (std::error_code EC = SF->materialize())
1639 return emitError(EC.message());
Tanya Lattnerea166d42011-10-14 22:17:46 +00001640 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001641
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001642 // Skip if no body (function is external).
1643 if (SF->isDeclaration())
1644 continue;
1645
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001646 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001647 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001648 }
1649
1650 // Resolve all uses of aliases with aliasees.
1651 linkAliasBodies();
1652
Bill Wendling66f02412012-02-11 11:38:06 +00001653 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001654 // after linking GlobalValues so that MDNodes that reference GlobalValues
1655 // are properly remapped.
1656 linkNamedMDNodes();
1657
Bill Wendling66f02412012-02-11 11:38:06 +00001658 // Merge the module flags into the DstM module.
1659 if (linkModuleFlagsMetadata())
1660 return true;
1661
Bill Wendling91686d62014-01-16 06:29:36 +00001662 // Update the initializers in the DstM module now that all globals that may
1663 // be referenced are in DstM.
1664 linkGlobalInits();
1665
Tanya Lattner0a48b872011-11-02 00:24:56 +00001666 // Process vector of lazily linked in functions.
1667 bool LinkedInAnyFunctions;
1668 do {
1669 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001670
Bill Wendlingfa2287822013-03-27 17:54:41 +00001671 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001672 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001673 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001674 if (!SF)
1675 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001676
James Molloyf6f121e2013-05-28 15:17:05 +00001677 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001678 if (SF->hasPrefixData()) {
1679 // Link in the prefix data.
1680 DF->setPrefixData(MapValue(SF->getPrefixData(),
1681 ValueMap,
1682 RF_None,
1683 &TypeMap,
1684 &ValMaterializer));
1685 }
James Molloyf6f121e2013-05-28 15:17:05 +00001686
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001687 // Materialize if needed.
1688 if (SF->isMaterializable()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001689 if (std::error_code EC = SF->materialize())
1690 return emitError(EC.message());
Tanya Lattner0a48b872011-11-02 00:24:56 +00001691 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001692
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001693 // Skip if no body (function is external).
1694 if (SF->isDeclaration())
1695 continue;
1696
James Molloyf6f121e2013-05-28 15:17:05 +00001697 // Erase from vector *before* the function body is linked - linkFunctionBody could
1698 // invalidate I.
1699 LazilyLinkFunctions.erase(I);
1700
1701 // Link in function body.
1702 linkFunctionBody(DF, SF);
1703 SF->Dematerialize();
1704
1705 // Set flag to indicate we may have more functions to lazily link in
1706 // since we linked in a function.
1707 LinkedInAnyFunctions = true;
1708 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001709 }
1710 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001711
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001712 // Now that all of the types from the source are used, resolve any structs
1713 // copied over to the dest that didn't exist there.
1714 TypeMap.linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001715
Anton Korobeynikov26098882008-03-05 23:21:39 +00001716 return false;
1717}
Reid Spencer361e5132004-11-12 20:37:43 +00001718
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001719Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler)
1720 : Composite(M), DiagnosticHandler(DiagnosticHandler) {}
1721
1722Linker::Linker(Module *M)
1723 : Composite(M), DiagnosticHandler([this](const DiagnosticInfo &DI) {
1724 Composite->getContext().diagnose(DI);
1725 }) {
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001726 TypeFinder StructTypes;
1727 StructTypes.run(*M, true);
1728 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1729}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001730
1731Linker::~Linker() {
1732}
1733
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001734void Linker::deleteModule() {
1735 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001736 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001737}
1738
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001739bool Linker::linkInModule(Module *Src) {
1740 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1741 DiagnosticHandler);
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001742 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +00001743}
1744
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001745//===----------------------------------------------------------------------===//
1746// LinkModules entrypoint.
1747//===----------------------------------------------------------------------===//
1748
Rafael Espindola18c89412014-10-27 02:35:46 +00001749/// This function links two modules together, with the resulting Dest module
1750/// modified to be the composite of the two input modules. If an error occurs,
1751/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1752/// Upon failure, the Dest module could be in a modified state, and shouldn't be
1753/// relied on to be consistent.
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001754bool Linker::LinkModules(Module *Dest, Module *Src,
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001755 DiagnosticHandlerFunction DiagnosticHandler) {
1756 Linker L(Dest, DiagnosticHandler);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001757 return L.linkInModule(Src);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001758}
1759
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001760bool Linker::LinkModules(Module *Dest, Module *Src) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001761 Linker L(Dest);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001762 return L.linkInModule(Src);
Reid Spencer361e5132004-11-12 20:37:43 +00001763}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001764
1765//===----------------------------------------------------------------------===//
1766// C API.
1767//===----------------------------------------------------------------------===//
1768
1769LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1770 LLVMLinkerMode Mode, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001771 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001772 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001773 raw_string_ostream Stream(Message);
1774 DiagnosticPrinterRawOStream DP(Stream);
1775
1776 LLVMBool Result = Linker::LinkModules(
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001777 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001778
1779 if (OutMessages && Result)
1780 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001781 return Result;
1782}