blob: a8dc324daa215878ea2f52366bceca7c07c187c0 [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
Rafael Espindolad2a13a22014-11-25 04:28:31 +000066 /// Produce a body for an opaque type in the dest module from a type
67 /// definition in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000068 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.
David Blaikie70573dc2014-11-19 07:49:26 +0000155 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
Chris Lattner5e3bd972011-12-20 00:03:52 +0000156 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
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000204void TypeMapTy::linkDefinedTypeBodies() {
205 SmallVector<Type*, 16> Elements;
206 SmallString<16> TmpName;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000207
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000208 // Note that processing entries in this loop (calling 'get') can add new
Chris Lattner5e3bd972011-12-20 00:03:52 +0000209 // entries to the SrcDefinitionsToResolve vector.
210 while (!SrcDefinitionsToResolve.empty()) {
211 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000212 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000213
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000214 // TypeMap is a many-to-one mapping, if there were multiple types that
215 // provide a body for DstSTy then previous iterations of this loop may have
216 // already handled it. Just ignore this case.
217 if (!DstSTy->isOpaque()) continue;
218 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000219
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000220 // Map the body of the source type over to a new body for the dest type.
221 Elements.resize(SrcSTy->getNumElements());
222 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
223 Elements[i] = getImpl(SrcSTy->getElementType(i));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000224
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000225 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000226
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000227 // If DstSTy has no name or has a longer name than STy, then viciously steal
228 // STy's name.
229 if (!SrcSTy->hasName()) continue;
230 StringRef SrcName = SrcSTy->getName();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000231
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000232 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
233 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
234 SrcSTy->setName("");
235 DstSTy->setName(TmpName.str());
236 TmpName.clear();
237 }
238 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000239
Chris Lattner5e3bd972011-12-20 00:03:52 +0000240 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000241}
242
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000243Type *TypeMapTy::get(Type *Ty) {
244 Type *Result = getImpl(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000245
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000246 // If this caused a reference to any struct type, resolve it before returning.
Chris Lattner5e3bd972011-12-20 00:03:52 +0000247 if (!SrcDefinitionsToResolve.empty())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000248 linkDefinedTypeBodies();
249 return Result;
250}
251
Rafael Espindola18c89412014-10-27 02:35:46 +0000252/// This is the recursive version of get().
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000253Type *TypeMapTy::getImpl(Type *Ty) {
254 // If we already have an entry for this type, return it.
255 Type **Entry = &MappedTypes[Ty];
256 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000257
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000258 // If this is not a named struct type, then just map all of the elements and
259 // then rebuild the type from inside out.
Chris Lattner44f7ab42011-08-12 18:07:26 +0000260 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000261 // If there are no element types to map, then the type is itself. This is
262 // true for the anonymous {} struct, things like 'float', integers, etc.
263 if (Ty->getNumContainedTypes() == 0)
264 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000265
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000266 // Remap all of the elements, keeping track of whether any of them change.
267 bool AnyChange = false;
268 SmallVector<Type*, 4> ElementTypes;
269 ElementTypes.resize(Ty->getNumContainedTypes());
270 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
271 ElementTypes[i] = getImpl(Ty->getContainedType(i));
272 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
273 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000274
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000275 // If we found our type while recursively processing stuff, just use it.
276 Entry = &MappedTypes[Ty];
277 if (*Entry) return *Entry;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000278
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000279 // If all of the element types mapped directly over, then the type is usable
280 // as-is.
281 if (!AnyChange)
282 return *Entry = Ty;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000283
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000284 // Otherwise, rebuild a modified type.
285 switch (Ty->getTypeID()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000286 default: llvm_unreachable("unknown derived type to remap");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000287 case Type::ArrayTyID:
288 return *Entry = ArrayType::get(ElementTypes[0],
289 cast<ArrayType>(Ty)->getNumElements());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000290 case Type::VectorTyID:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000291 return *Entry = VectorType::get(ElementTypes[0],
292 cast<VectorType>(Ty)->getNumElements());
293 case Type::PointerTyID:
294 return *Entry = PointerType::get(ElementTypes[0],
295 cast<PointerType>(Ty)->getAddressSpace());
296 case Type::FunctionTyID:
297 return *Entry = FunctionType::get(ElementTypes[0],
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000298 makeArrayRef(ElementTypes).slice(1),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000299 cast<FunctionType>(Ty)->isVarArg());
300 case Type::StructTyID:
301 // Note that this is only reached for anonymous structs.
302 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
303 cast<StructType>(Ty)->isPacked());
304 }
305 }
306
307 // Otherwise, this is an unmapped named struct. If the struct can be directly
308 // mapped over, just use it as-is. This happens in a case when the linked-in
309 // module has something like:
310 // %T = type {%T*, i32}
311 // @GV = global %T* null
312 // where T does not exist at all in the destination module.
313 //
314 // The other case we watch for is when the type is not in the destination
315 // module, but that it has to be rebuilt because it refers to something that
316 // is already mapped. For example, if the destination module has:
317 // %A = type { i32 }
318 // and the source module has something like
319 // %A' = type { i32 }
320 // %B = type { %A'* }
321 // @GV = global %B* null
322 // then we want to create a new type: "%B = type { %A*}" and have it take the
323 // pristine "%B" name from the source module.
324 //
325 // To determine which case this is, we have to recursively walk the type graph
326 // speculating that we'll be able to reuse it unmodified. Only if this is
327 // safe would we map the entire thing over. Because this is an optimization,
328 // and is not required for the prettiness of the linked module, we just skip
329 // it and always rebuild a type here.
330 StructType *STy = cast<StructType>(Ty);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000331
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000332 // If the type is opaque, we can just use it directly.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000333 if (STy->isOpaque()) {
334 // A named structure type from src module is used. Add it to the Set of
335 // identified structs in the destination module.
336 DstStructTypesSet.insert(STy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000337 return *Entry = STy;
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000338 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000339
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000340 // Otherwise we create a new type and resolve its body later. This will be
341 // resolved by the top level of get().
Chris Lattner5e3bd972011-12-20 00:03:52 +0000342 SrcDefinitionsToResolve.push_back(STy);
343 StructType *DTy = StructType::create(STy->getContext());
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000344 // A new identified structure type was created. Add it to the set of
345 // identified structs in the destination module.
346 DstStructTypesSet.insert(DTy);
Chris Lattner5e3bd972011-12-20 00:03:52 +0000347 DstResolvedOpaqueTypes.insert(DTy);
348 return *Entry = DTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000349}
350
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000351//===----------------------------------------------------------------------===//
352// ModuleLinker implementation.
353//===----------------------------------------------------------------------===//
354
355namespace {
James Molloyf6f121e2013-05-28 15:17:05 +0000356 class ModuleLinker;
357
Rafael Espindola18c89412014-10-27 02:35:46 +0000358 /// Creates prototypes for functions that are lazily linked on the fly. This
359 /// speeds up linking for modules with many/ lazily linked functions of which
360 /// few get used.
James Molloyf6f121e2013-05-28 15:17:05 +0000361 class ValueMaterializerTy : public ValueMaterializer {
362 TypeMapTy &TypeMap;
363 Module *DstM;
364 std::vector<Function*> &LazilyLinkFunctions;
365 public:
366 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
367 std::vector<Function*> &LazilyLinkFunctions) :
368 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
369 LazilyLinkFunctions(LazilyLinkFunctions) {
370 }
371
Craig Topper85482992014-03-05 07:52:44 +0000372 Value *materializeValueFor(Value *V) override;
James Molloyf6f121e2013-05-28 15:17:05 +0000373 };
374
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000375 namespace {
376 class LinkDiagnosticInfo : public DiagnosticInfo {
377 const Twine &Msg;
378
379 public:
380 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
381 void print(DiagnosticPrinter &DP) const override;
382 };
383 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
384 const Twine &Msg)
385 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
386 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
387 }
388
Rafael Espindola18c89412014-10-27 02:35:46 +0000389 /// This is an implementation class for the LinkModules function, which is the
390 /// entrypoint for this file.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000391 class ModuleLinker {
392 Module *DstM, *SrcM;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000393
394 TypeMapTy TypeMap;
James Molloyf6f121e2013-05-28 15:17:05 +0000395 ValueMaterializerTy ValMaterializer;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000396
Rafael Espindola18c89412014-10-27 02:35:46 +0000397 /// Mapping of values from what they used to be in Src, to what they are now
398 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
399 /// due to the use of Value handles which the Linker doesn't actually need,
400 /// but this allows us to reuse the ValueMapper code.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000401 ValueToValueMapTy ValueMap;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000402
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000403 struct AppendingVarInfo {
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000404 GlobalVariable *NewGV; // New aggregate global in dest module.
405 const Constant *DstInit; // Old initializer from dest module.
406 const Constant *SrcInit; // Old initializer from src module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000407 };
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000408
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000409 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000410
Tanya Lattnercbb91402011-10-11 00:24:54 +0000411 // Set of items not to link in from source.
412 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000413
Tanya Lattner0a48b872011-11-02 00:24:56 +0000414 // Vector of functions to lazily link in.
Bill Wendlingfa2287822013-03-27 17:54:41 +0000415 std::vector<Function*> LazilyLinkFunctions;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000416
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000417 Linker::DiagnosticHandlerFunction DiagnosticHandler;
418
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000419 public:
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000420 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000421 Linker::DiagnosticHandlerFunction DiagnosticHandler)
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000422 : DstM(dstM), SrcM(srcM), TypeMap(Set),
Rafael Espindola9f8eff32014-10-28 00:24:16 +0000423 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000424 DiagnosticHandler(DiagnosticHandler) {}
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000425
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000426 bool run();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000427
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000428 private:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000429 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
430 const GlobalValue &Src);
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000431
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000432 /// Helper method for setting a message and returning an error code.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000433 bool emitError(const Twine &Message) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000434 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
Chris Lattner99953022008-06-16 18:27:53 +0000435 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000436 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000437
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000438 void emitWarning(const Twine &Message) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000439 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000440 }
441
David Majnemerdad0a642014-06-27 18:19:56 +0000442 bool getComdatLeader(Module *M, StringRef ComdatName,
443 const GlobalVariable *&GVar);
444 bool computeResultingSelectionKind(StringRef ComdatName,
445 Comdat::SelectionKind Src,
446 Comdat::SelectionKind Dst,
447 Comdat::SelectionKind &Result,
448 bool &LinkFromSrc);
449 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
450 ComdatsChosen;
451 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
452 bool &LinkFromSrc);
453
Rafael Espindola18c89412014-10-27 02:35:46 +0000454 /// Given a global in the source module, return the global in the
455 /// destination module that is being linked to, if any.
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000456 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000457 // If the source has no name it can't link. If it has local linkage,
458 // there is no name match-up going on.
459 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000460 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000461
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000462 // Otherwise see if we have a match in the destination module's symtab.
463 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
Craig Topper2617dcc2014-04-15 06:32:26 +0000464 if (!DGV) return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000465
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000466 // If we found a global with the same name in the dest module, but it has
467 // internal linkage, we are really not doing any linkage here.
468 if (DGV->hasLocalLinkage())
Craig Topper2617dcc2014-04-15 06:32:26 +0000469 return nullptr;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000470
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000471 // Otherwise, we do in fact link to the destination global.
472 return DGV;
473 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000474
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000475 void computeTypeMapping();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000476
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000477 void upgradeMismatchedGlobalArray(StringRef Name);
478 void upgradeMismatchedGlobals();
479
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000480 bool linkAppendingVarProto(GlobalVariable *DstGV,
481 const GlobalVariable *SrcGV);
Rafael Espindola778fcc72014-11-02 13:28:57 +0000482
483 bool linkGlobalValueProto(GlobalValue *GV);
484 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
485 GlobalValue *DGV, bool LinkFromSrc);
486 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
487 bool LinkFromSrc);
488 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
489 bool LinkFromSrc);
490
Bill Wendling66f02412012-02-11 11:38:06 +0000491 bool linkModuleFlagsMetadata();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000492
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000493 void linkAppendingVarInit(const AppendingVarInfo &AVI);
494 void linkGlobalInits();
495 void linkFunctionBody(Function *Dst, Function *Src);
496 void linkAliasBodies();
497 void linkNamedMDNodes();
498 };
Bill Wendlingd48b7782012-02-28 04:01:21 +0000499}
500
Rafael Espindola18c89412014-10-27 02:35:46 +0000501/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
502/// table. This is good for all clients except for us. Go through the trouble
503/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000504static void forceRenaming(GlobalValue *GV, StringRef Name) {
505 // If the global doesn't force its name or if it already has the right name,
506 // there is nothing for us to do.
507 if (GV->hasLocalLinkage() || GV->getName() == Name)
508 return;
509
510 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000511
512 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000513 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000514 GV->takeName(ConflictGV);
515 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000516 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000517 } else {
518 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000519 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000520}
Reid Spencer90246aa2007-02-04 04:29:21 +0000521
Rafael Espindola18c89412014-10-27 02:35:46 +0000522/// copy additional attributes (those not needed to construct a GlobalValue)
523/// from the SrcGV to the DestGV.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000524static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000525 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000526 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000527 unsigned Alignment;
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000528 if (DestGO)
529 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000530
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000531 DestGV->copyAttributesFrom(SrcGV);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000532
Rafael Espindola99e05cf2014-05-13 18:45:48 +0000533 if (DestGO)
534 DestGO->setAlignment(Alignment);
Rafael Espindolaa7d9c692014-05-06 14:51:36 +0000535
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000536 forceRenaming(DestGV, SrcGV->getName());
Reid Spencer361e5132004-11-12 20:37:43 +0000537}
538
Rafael Espindola23f8d642012-01-05 23:02:01 +0000539static bool isLessConstraining(GlobalValue::VisibilityTypes a,
540 GlobalValue::VisibilityTypes b) {
541 if (a == GlobalValue::HiddenVisibility)
542 return false;
543 if (b == GlobalValue::HiddenVisibility)
544 return true;
545 if (a == GlobalValue::ProtectedVisibility)
546 return false;
547 if (b == GlobalValue::ProtectedVisibility)
548 return true;
549 return false;
550}
551
James Molloyf6f121e2013-05-28 15:17:05 +0000552Value *ValueMaterializerTy::materializeValueFor(Value *V) {
553 Function *SF = dyn_cast<Function>(V);
554 if (!SF)
Craig Topper2617dcc2014-04-15 06:32:26 +0000555 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000556
557 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
558 SF->getLinkage(), SF->getName(), DstM);
559 copyGVAttributes(DF, SF);
560
Rafael Espindola3931c282014-08-15 20:17:08 +0000561 if (Comdat *SC = SF->getComdat()) {
562 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
563 DF->setComdat(DC);
564 }
565
James Molloyf6f121e2013-05-28 15:17:05 +0000566 LazilyLinkFunctions.push_back(SF);
567 return DF;
568}
569
David Majnemerdad0a642014-06-27 18:19:56 +0000570bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
571 const GlobalVariable *&GVar) {
572 const GlobalValue *GVal = M->getNamedValue(ComdatName);
573 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
574 GVal = GA->getBaseObject();
575 if (!GVal)
576 // We cannot resolve the size of the aliasee yet.
577 return emitError("Linking COMDATs named '" + ComdatName +
578 "': COMDAT key involves incomputable alias size.");
579 }
580
581 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
582 if (!GVar)
583 return emitError(
584 "Linking COMDATs named '" + ComdatName +
585 "': GlobalVariable required for data dependent selection!");
586
587 return false;
588}
589
590bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
591 Comdat::SelectionKind Src,
592 Comdat::SelectionKind Dst,
593 Comdat::SelectionKind &Result,
594 bool &LinkFromSrc) {
595 // The ability to mix Comdat::SelectionKind::Any with
596 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
597 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
598 Dst == Comdat::SelectionKind::Largest;
599 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
600 Src == Comdat::SelectionKind::Largest;
601 if (DstAnyOrLargest && SrcAnyOrLargest) {
602 if (Dst == Comdat::SelectionKind::Largest ||
603 Src == Comdat::SelectionKind::Largest)
604 Result = Comdat::SelectionKind::Largest;
605 else
606 Result = Comdat::SelectionKind::Any;
607 } else if (Src == Dst) {
608 Result = Dst;
609 } else {
610 return emitError("Linking COMDATs named '" + ComdatName +
611 "': invalid selection kinds!");
612 }
613
614 switch (Result) {
615 case Comdat::SelectionKind::Any:
616 // Go with Dst.
617 LinkFromSrc = false;
618 break;
619 case Comdat::SelectionKind::NoDuplicates:
620 return emitError("Linking COMDATs named '" + ComdatName +
621 "': noduplicates has been violated!");
622 case Comdat::SelectionKind::ExactMatch:
623 case Comdat::SelectionKind::Largest:
624 case Comdat::SelectionKind::SameSize: {
625 const GlobalVariable *DstGV;
626 const GlobalVariable *SrcGV;
627 if (getComdatLeader(DstM, ComdatName, DstGV) ||
628 getComdatLeader(SrcM, ComdatName, SrcGV))
629 return true;
630
631 const DataLayout *DstDL = DstM->getDataLayout();
632 const DataLayout *SrcDL = SrcM->getDataLayout();
633 if (!DstDL || !SrcDL) {
634 return emitError(
635 "Linking COMDATs named '" + ComdatName +
636 "': can't do size dependent selection without DataLayout!");
637 }
638 uint64_t DstSize =
639 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
640 uint64_t SrcSize =
641 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
642 if (Result == Comdat::SelectionKind::ExactMatch) {
643 if (SrcGV->getInitializer() != DstGV->getInitializer())
644 return emitError("Linking COMDATs named '" + ComdatName +
645 "': ExactMatch violated!");
646 LinkFromSrc = false;
647 } else if (Result == Comdat::SelectionKind::Largest) {
648 LinkFromSrc = SrcSize > DstSize;
649 } else if (Result == Comdat::SelectionKind::SameSize) {
650 if (SrcSize != DstSize)
651 return emitError("Linking COMDATs named '" + ComdatName +
652 "': SameSize violated!");
653 LinkFromSrc = false;
654 } else {
655 llvm_unreachable("unknown selection kind");
656 }
657 break;
658 }
659 }
660
661 return false;
662}
663
664bool ModuleLinker::getComdatResult(const Comdat *SrcC,
665 Comdat::SelectionKind &Result,
666 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +0000667 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000668 StringRef ComdatName = SrcC->getName();
669 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
670 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000671
Rafael Espindolab16196a2014-08-11 17:07:34 +0000672 if (DstCI == ComdatSymTab.end()) {
673 // Use the comdat if it is only available in one of the modules.
674 LinkFromSrc = true;
675 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000676 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000677 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000678
679 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000680 Comdat::SelectionKind DSK = DstC->getSelectionKind();
681 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
682 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000683}
James Molloyf6f121e2013-05-28 15:17:05 +0000684
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000685bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
686 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000687 const GlobalValue &Src) {
Rafael Espindola778fcc72014-11-02 13:28:57 +0000688 // We always have to add Src if it has appending linkage.
689 if (Src.hasAppendingLinkage()) {
690 LinkFromSrc = true;
691 return false;
692 }
693
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000694 bool SrcIsDeclaration = Src.isDeclarationForLinker();
695 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000696
697 if (SrcIsDeclaration) {
698 // If Src is external or if both Src & Dest are external.. Just link the
699 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000700 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000701 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000702 LinkFromSrc = DestIsDeclaration;
703 return false;
704 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000705 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000706 LinkFromSrc = Dest.hasExternalWeakLinkage();
707 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000708 }
709
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000710 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000711 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000712 LinkFromSrc = true;
713 return false;
714 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000715
Rafael Espindola09106052014-09-09 15:59:12 +0000716 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000717 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
718 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000719 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000720 }
721
722 if (!Dest.hasCommonLinkage()) {
723 LinkFromSrc = false;
724 return false;
725 }
Rafael Espindola09106052014-09-09 15:59:12 +0000726
Rafael Espindola0ae225b2014-10-31 04:46:38 +0000727 // FIXME: Make datalayout mandatory and just use getDataLayout().
728 DataLayout DL(Dest.getParent());
729
Rafael Espindola09106052014-09-09 15:59:12 +0000730 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
731 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000732 LinkFromSrc = SrcSize > DestSize;
733 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000734 }
735
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000736 if (Src.isWeakForLinker()) {
737 assert(!Dest.hasExternalWeakLinkage());
738 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000739
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000740 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
741 LinkFromSrc = true;
742 return false;
743 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000744
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000745 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000746 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000747 }
748
749 if (Dest.isWeakForLinker()) {
750 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000751 LinkFromSrc = true;
752 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000753 }
754
755 assert(!Src.hasExternalWeakLinkage());
756 assert(!Dest.hasExternalWeakLinkage());
757 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
758 "Unexpected linkage type!");
759 return emitError("Linking globals named '" + Src.getName() +
760 "': symbol multiply defined!");
761}
762
Rafael Espindola18c89412014-10-27 02:35:46 +0000763/// Loop over all of the linked values to compute type mappings. For example,
764/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
765/// types 'Foo' but one got renamed when the module was loaded into the same
766/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000767void ModuleLinker::computeTypeMapping() {
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000768 for (GlobalValue &SGV : SrcM->globals()) {
769 GlobalValue *DGV = getLinkedToGlobal(&SGV);
770 if (!DGV)
771 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000772
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000773 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
774 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000775 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000776 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000777
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000778 // Unify the element type of appending arrays.
779 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000780 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000781 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +0000782 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000783
Rafael Espindolac8a476e2014-11-25 04:26:19 +0000784 for (GlobalValue &SGV : *SrcM) {
785 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
786 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000787 }
Bill Wendling7b464612012-02-27 22:34:19 +0000788
Rafael Espindolae96d7eb2014-11-25 04:43:59 +0000789 for (GlobalValue &SGV : SrcM->aliases()) {
790 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
791 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
792 }
793
Bill Wendlingd48b7782012-02-28 04:01:21 +0000794 // Incorporate types by name, scanning all the types in the source module.
795 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000796 // example. When the source module got loaded into the same LLVMContext, if
797 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Bill Wendling8555a372012-08-03 00:30:35 +0000798 TypeFinder SrcStructTypes;
799 SrcStructTypes.run(*SrcM, true);
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000800 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
801 SrcStructTypes.end());
Bill Wendling87374802012-03-23 23:17:38 +0000802
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000803 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
804 StructType *ST = SrcStructTypes[i];
805 if (!ST->hasName()) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000806
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000807 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000808 size_t DotPos = ST->getName().rfind('.');
809 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +0000810 ST->getName().back() == '.' ||
811 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +0000812 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000813
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000814 // Check to see if the destination module has a struct with the prefix name.
Bill Wendlingd48b7782012-02-28 04:01:21 +0000815 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
Bill Wendling87374802012-03-23 23:17:38 +0000816 // Don't use it if this actually came from the source module. They're in
817 // the same LLVMContext after all. Also don't use it unless the type is
818 // actually used in the destination module. This can happen in situations
819 // like this:
820 //
821 // Module A Module B
822 // -------- --------
823 // %Z = type { %A } %B = type { %C.1 }
824 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
825 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
826 // %C = type { i8* } %B.3 = type { %C.1 }
827 //
828 // When we link Module B with Module A, the '%B' in Module B is
829 // used. However, that would then use '%C.1'. But when we process '%C.1',
830 // we prefer to take the '%C' version. So we are then left with both
831 // '%C.1' and '%C' being used for the same types. This leads to some
832 // variables using one type and some using the other.
Rafael Espindolaaa9918a2013-05-04 05:05:18 +0000833 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
Bill Wendling2b3f61a2012-02-27 23:48:30 +0000834 TypeMap.addTypeMapping(DST, ST);
835 }
836
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000837 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000838 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000839 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +0000840}
841
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +0000842static void upgradeGlobalArray(GlobalVariable *GV) {
843 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
844 StructType *OldTy = cast<StructType>(ATy->getElementType());
845 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
846
847 // Get the upgraded 3 element type.
848 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
849 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
850 VoidPtrTy};
851 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
852
853 // Build new constants with a null third field filled in.
854 Constant *OldInitC = GV->getInitializer();
855 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
856 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
857 // Invalid initializer; give up.
858 return;
859 std::vector<Constant *> Initializers;
860 if (OldInit && OldInit->getNumOperands()) {
861 Value *Null = Constant::getNullValue(VoidPtrTy);
862 for (Use &U : OldInit->operands()) {
863 ConstantStruct *Init = cast<ConstantStruct>(U.get());
864 Initializers.push_back(ConstantStruct::get(
865 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
866 }
867 }
868 assert(Initializers.size() == ATy->getNumElements() &&
869 "Failed to copy all array elements");
870
871 // Replace the old GV with a new one.
872 ATy = ArrayType::get(NewTy, Initializers.size());
873 Constant *NewInit = ConstantArray::get(ATy, Initializers);
874 GlobalVariable *NewGV = new GlobalVariable(
875 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
876 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
877 GV->isExternallyInitialized());
878 NewGV->copyAttributesFrom(GV);
879 NewGV->takeName(GV);
880 assert(GV->use_empty() && "program cannot use initializer list");
881 GV->eraseFromParent();
882}
883
884void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
885 // Look for the global arrays.
886 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
887 if (!DstGV)
888 return;
889 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
890 if (!SrcGV)
891 return;
892
893 // Check if the types already match.
894 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
895 auto *SrcTy =
896 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
897 if (DstTy == SrcTy)
898 return;
899
900 // Grab the element types. We can only upgrade an array of a two-field
901 // struct. Only bother if the other one has three-fields.
902 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
903 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
904 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
905 upgradeGlobalArray(DstGV);
906 return;
907 }
908 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
909 upgradeGlobalArray(SrcGV);
910
911 // We can't upgrade any other differences.
912}
913
914void ModuleLinker::upgradeMismatchedGlobals() {
915 upgradeMismatchedGlobalArray("llvm.global_ctors");
916 upgradeMismatchedGlobalArray("llvm.global_dtors");
917}
918
Rafael Espindola18c89412014-10-27 02:35:46 +0000919/// If there were any appending global variables, link them together now.
920/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000921bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +0000922 const GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000923
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000924 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
925 return emitError("Linking globals named '" + SrcGV->getName() +
926 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000927
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000928 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
929 ArrayType *SrcTy =
930 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
931 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000932
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000933 // Check to see that they two arrays agree on type.
934 if (EltTy != SrcTy->getElementType())
935 return emitError("Appending variables with different element types!");
936 if (DstGV->isConstant() != SrcGV->isConstant())
937 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000938
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000939 if (DstGV->getAlignment() != SrcGV->getAlignment())
940 return emitError(
941 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000942
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000943 if (DstGV->getVisibility() != SrcGV->getVisibility())
944 return emitError(
945 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +0000946
947 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
948 return emitError(
949 "Appending variables with different unnamed_addr need to be linked!");
950
Rafael Espindola64c1e182014-06-03 02:41:57 +0000951 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000952 return emitError(
953 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000954
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000955 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
956 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000957
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000958 // Create the new global variable.
959 GlobalVariable *NG =
960 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +0000961 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000962 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000963 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000964
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000965 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +0000966 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000967
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000968 AppendingVarInfo AVI;
969 AVI.NewGV = NG;
970 AVI.DstInit = DstGV->getInitializer();
971 AVI.SrcInit = SrcGV->getInitializer();
972 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000973
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000974 // Replace any uses of the two global variables with uses of the new
975 // global.
976 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +0000977
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000978 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
979 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000980
Tanya Lattnercbb91402011-10-11 00:24:54 +0000981 // Track the source variable so we don't try to link it.
982 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000983
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000984 return false;
985}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000986
Rafael Espindola778fcc72014-11-02 13:28:57 +0000987bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000988 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000989
Rafael Espindola778fcc72014-11-02 13:28:57 +0000990 // Handle the ultra special appending linkage case first.
991 if (DGV && DGV->hasAppendingLinkage())
992 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
993 cast<GlobalVariable>(SGV));
994
995 bool LinkFromSrc = true;
996 Comdat *C = nullptr;
997 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
998 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
999
David Majnemerdad0a642014-06-27 18:19:56 +00001000 if (const Comdat *SC = SGV->getComdat()) {
1001 Comdat::SelectionKind SK;
1002 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola778fcc72014-11-02 13:28:57 +00001003 C = DstM->getOrInsertComdat(SC->getName());
1004 C->setSelectionKind(SK);
1005 } else if (DGV) {
1006 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1007 return true;
1008 }
1009
1010 if (!LinkFromSrc) {
1011 // Track the source global so that we don't attempt to copy it over when
1012 // processing global initializers.
1013 DoNotLinkFromSource.insert(SGV);
1014
1015 if (DGV)
1016 // Make sure to remember this mapping.
1017 ValueMap[SGV] =
1018 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
David Majnemerdad0a642014-06-27 18:19:56 +00001019 }
1020
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001021 if (DGV) {
Rafael Espindola778fcc72014-11-02 13:28:57 +00001022 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1023 ? DGV->getVisibility()
1024 : Visibility;
1025 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1026 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001027
Rafael Espindola778fcc72014-11-02 13:28:57 +00001028 if (!LinkFromSrc && !DGV)
1029 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001030
Rafael Espindola778fcc72014-11-02 13:28:57 +00001031 GlobalValue *NewGV;
1032 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1033 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1034 if (!NewGV)
1035 return true;
1036 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1037 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1038 } else {
1039 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1040 }
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001041
Rafael Espindola778fcc72014-11-02 13:28:57 +00001042 if (NewGV) {
1043 if (NewGV != DGV)
1044 copyGVAttributes(NewGV, SGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001045
Rafael Espindola778fcc72014-11-02 13:28:57 +00001046 NewGV->setUnnamedAddr(HasUnnamedAddr);
1047 NewGV->setVisibility(Visibility);
1048
1049 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1050 if (C)
1051 NewGO->setComdat(C);
Chandler Carruthfd38af22014-11-02 09:10:31 +00001052 }
1053
Rafael Espindola778fcc72014-11-02 13:28:57 +00001054 // Make sure to remember this mapping.
1055 if (NewGV != DGV) {
1056 if (DGV) {
1057 DGV->replaceAllUsesWith(
1058 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1059 DGV->eraseFromParent();
1060 }
1061 ValueMap[SGV] = NewGV;
Chris Lattner0ead7a52008-07-14 07:23:24 +00001062 }
Reid Spencer361e5132004-11-12 20:37:43 +00001063 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001064
Rafael Espindola778fcc72014-11-02 13:28:57 +00001065 return false;
1066}
1067
1068/// Loop through the global variables in the src module and merge them into the
1069/// dest module.
1070GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1071 GlobalValue *DGV,
1072 bool LinkFromSrc) {
1073 unsigned Alignment = 0;
1074 bool ClearConstant = false;
1075
1076 if (DGV) {
1077 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1078 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1079
1080 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1081 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1082 ClearConstant = true;
1083 }
1084
1085 if (!LinkFromSrc) {
1086 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1087 if (Alignment)
1088 NewGVar->setAlignment(Alignment);
1089 if (NewGVar->isDeclaration() && ClearConstant)
1090 NewGVar->setConstant(false);
1091 }
1092 return DGV;
David Majnemerdad0a642014-06-27 18:19:56 +00001093 }
1094
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001095 // No linking to be performed or linking from the source: simply create an
1096 // identical version of the symbol over in the dest module... the
1097 // initializer will be filled in later by LinkGlobalInits.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001098 GlobalVariable *NewDGV = new GlobalVariable(
1099 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1100 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1101 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1102 SGVar->getType()->getAddressSpace());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001103
Rafael Espindola778fcc72014-11-02 13:28:57 +00001104 if (Alignment)
1105 NewDGV->setAlignment(Alignment);
David Majnemerdad0a642014-06-27 18:19:56 +00001106
Rafael Espindola778fcc72014-11-02 13:28:57 +00001107 return NewDGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001108}
1109
Rafael Espindola18c89412014-10-27 02:35:46 +00001110/// Link the function in the source module into the destination module if
1111/// needed, setting up mapping information.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001112GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1113 GlobalValue *DGV,
1114 bool LinkFromSrc) {
1115 if (!LinkFromSrc)
1116 return DGV;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001117
James Molloyf6f121e2013-05-28 15:17:05 +00001118 // If the function is to be lazily linked, don't create it just yet.
1119 // The ValueMaterializerTy will deal with creating it if it's used.
1120 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1121 SF->hasAvailableExternallyLinkage())) {
1122 DoNotLinkFromSource.insert(SF);
Rafael Espindola778fcc72014-11-02 13:28:57 +00001123 return nullptr;
David Majnemerdad0a642014-06-27 18:19:56 +00001124 }
1125
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001126 // If there is no linkage to be performed or we are linking from the source,
1127 // bring SF over.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001128 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1129 SF->getName(), DstM);
Lauro Ramos Venanciob00c9c02007-06-28 19:02:54 +00001130}
1131
Rafael Espindola18c89412014-10-27 02:35:46 +00001132/// Set up prototypes for any aliases that come over from the source module.
Rafael Espindola778fcc72014-11-02 13:28:57 +00001133GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1134 GlobalValue *DGV,
1135 bool LinkFromSrc) {
1136 if (!LinkFromSrc)
1137 return DGV;
David Majnemerdad0a642014-06-27 18:19:56 +00001138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001139 // If there is no linkage to be performed or we're linking from the source,
1140 // bring over SGA.
Rafael Espindola4fe00942014-05-16 13:34:04 +00001141 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
Rafael Espindola778fcc72014-11-02 13:28:57 +00001142 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1143 SGA->getLinkage(), SGA->getName(), DstM);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001144}
1145
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001146static void getArrayElements(const Constant *C,
1147 SmallVectorImpl<Constant *> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001148 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1149
1150 for (unsigned i = 0; i != NumElements; ++i)
1151 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001152}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001153
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001154void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1155 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001156 SmallVector<Constant *, 16> DstElements;
1157 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001158
Rafael Espindolad31dc042014-09-05 21:27:52 +00001159 SmallVector<Constant *, 16> SrcElements;
1160 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001161
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001162 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001163
1164 StringRef Name = AVI.NewGV->getName();
1165 bool IsNewStructor =
1166 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1167 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1168
1169 for (auto *V : SrcElements) {
1170 if (IsNewStructor) {
1171 Constant *Key = V->getAggregateElement(2);
1172 if (DoNotLinkFromSource.count(Key))
1173 continue;
1174 }
1175 DstElements.push_back(
1176 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1177 }
1178 if (IsNewStructor) {
1179 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1180 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1181 }
1182
1183 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001184}
1185
Rafael Espindola18c89412014-10-27 02:35:46 +00001186/// Update the initializers in the Dest module now that all globals that may be
1187/// referenced are in Dest.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001188void ModuleLinker::linkGlobalInits() {
Reid Spencer361e5132004-11-12 20:37:43 +00001189 // Loop over all of the globals in the src module, mapping them over as we go
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001190 for (Module::const_global_iterator I = SrcM->global_begin(),
1191 E = SrcM->global_end(); I != E; ++I) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001192
Tanya Lattnercbb91402011-10-11 00:24:54 +00001193 // Only process initialized GV's or ones not already in dest.
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001194 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1195
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001196 // Grab destination global variable.
1197 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1198 // Figure out what the initializer looks like in the dest module.
1199 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001200 RF_None, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001201 }
Reid Spencer361e5132004-11-12 20:37:43 +00001202}
1203
Rafael Espindola18c89412014-10-27 02:35:46 +00001204/// Copy the source function over into the dest function and fix up references
1205/// to values. At this point we know that Dest is an external function, and
1206/// that Src is not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001207void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1208 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001209
Chris Lattner7391dde2004-11-16 17:12:38 +00001210 // Go through and convert function arguments over, remembering the mapping.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001211 Function::arg_iterator DI = Dst->arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001212 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
Reid Spencer361e5132004-11-12 20:37:43 +00001213 I != E; ++I, ++DI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001214 DI->setName(I->getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001215
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001216 // Add a mapping to our mapping.
Anton Korobeynikov66a62712008-03-10 22:36:08 +00001217 ValueMap[I] = DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001218 }
1219
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001220 // Splice the body of the source function into the dest function.
1221 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001222
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001223 // At this point, all of the instructions and values of the function are now
1224 // copied over. The only problem is that they are still referencing values in
1225 // the Source function as operands. Loop through all of the operands of the
1226 // functions and patch them up to point to the local versions.
1227 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1229 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1230 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001231
Chris Lattner7391dde2004-11-16 17:12:38 +00001232 // There is no need to map the arguments anymore.
Chris Lattner44ab8ae2006-06-16 01:24:04 +00001233 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1234 I != E; ++I)
Reid Spencer3aaaa0b2007-02-05 20:47:22 +00001235 ValueMap.erase(I);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001236
Reid Spencer361e5132004-11-12 20:37:43 +00001237}
1238
Rafael Espindola18c89412014-10-27 02:35:46 +00001239/// Insert all of the aliases in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001240void ModuleLinker::linkAliasBodies() {
1241 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
Tanya Lattnercbb91402011-10-11 00:24:54 +00001242 I != E; ++I) {
1243 if (DoNotLinkFromSource.count(I))
1244 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001245 if (Constant *Aliasee = I->getAliasee()) {
1246 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
Rafael Espindola6b238632014-05-16 19:35:39 +00001247 Constant *Val =
1248 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
Rafael Espindola64c1e182014-06-03 02:41:57 +00001249 DA->setAliasee(Val);
David Chisnall2c4a34a2010-01-09 16:27:31 +00001250 }
Tanya Lattnercbb91402011-10-11 00:24:54 +00001251 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001252}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001253
Rafael Espindola18c89412014-10-27 02:35:46 +00001254/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001255void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001256 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001257 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1258 E = SrcM->named_metadata_end(); I != E; ++I) {
Bill Wendling66f02412012-02-11 11:38:06 +00001259 // Don't link module flags here. Do them separately.
1260 if (&*I == SrcModFlags) continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001261 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1262 // Add Src elements into Dest node.
1263 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1264 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
James Molloyf6f121e2013-05-28 15:17:05 +00001265 RF_None, &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001266 }
1267}
Bill Wendling66f02412012-02-11 11:38:06 +00001268
Rafael Espindola18c89412014-10-27 02:35:46 +00001269/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001270bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001271 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001272 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1273 if (!SrcModFlags) return false;
1274
Bill Wendling66f02412012-02-11 11:38:06 +00001275 // If the destination module doesn't have module flags yet, then just copy
1276 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001277 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001278 if (DstModFlags->getNumOperands() == 0) {
1279 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1280 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1281
1282 return false;
1283 }
1284
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001285 // First build a map of the existing module flags and requirements.
1286 DenseMap<MDString*, MDNode*> Flags;
1287 SmallSetVector<MDNode*, 16> Requirements;
1288 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001289 MDNode *Op = DstModFlags->getOperand(I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001290 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1291 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001292
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001293 if (Behavior->getZExtValue() == Module::Require) {
1294 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1295 } else {
1296 Flags[ID] = Op;
1297 }
Bill Wendling66f02412012-02-11 11:38:06 +00001298 }
1299
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001300 // Merge in the flags from the source module, and also collect its set of
1301 // requirements.
1302 bool HasErr = false;
1303 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001304 MDNode *SrcOp = SrcModFlags->getOperand(I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001305 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1306 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1307 MDNode *DstOp = Flags.lookup(ID);
1308 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001309
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001310 // If this is a requirement, add it and continue.
1311 if (SrcBehaviorValue == Module::Require) {
1312 // If the destination module does not already have this requirement, add
1313 // it.
1314 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1315 DstModFlags->addOperand(SrcOp);
1316 }
1317 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001318 }
1319
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001320 // If there is no existing flag with this ID, just add it.
1321 if (!DstOp) {
1322 Flags[ID] = SrcOp;
1323 DstModFlags->addOperand(SrcOp);
1324 continue;
1325 }
1326
1327 // Otherwise, perform a merge.
1328 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1329 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1330
1331 // If either flag has override behavior, handle it first.
1332 if (DstBehaviorValue == Module::Override) {
1333 // Diagnose inconsistent flags which both have override behavior.
1334 if (SrcBehaviorValue == Module::Override &&
1335 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1336 HasErr |= emitError("linking module flags '" + ID->getString() +
1337 "': IDs have conflicting override values");
1338 }
1339 continue;
1340 } else if (SrcBehaviorValue == Module::Override) {
1341 // Update the destination flag to that of the source.
1342 DstOp->replaceOperandWith(0, SrcBehavior);
1343 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1344 continue;
1345 }
1346
1347 // Diagnose inconsistent merge behavior types.
1348 if (SrcBehaviorValue != DstBehaviorValue) {
1349 HasErr |= emitError("linking module flags '" + ID->getString() +
1350 "': IDs have conflicting behaviors");
1351 continue;
1352 }
1353
1354 // Perform the merge for standard behavior types.
1355 switch (SrcBehaviorValue) {
1356 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001357 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001358 case Module::Error: {
1359 // Emit an error if the values differ.
1360 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1361 HasErr |= emitError("linking module flags '" + ID->getString() +
1362 "': IDs have conflicting values");
1363 }
1364 continue;
1365 }
1366 case Module::Warning: {
1367 // Emit a warning if the values differ.
1368 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001369 emitWarning("linking module flags '" + ID->getString() +
1370 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001371 }
1372 continue;
1373 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001374 case Module::Append: {
1375 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1376 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1377 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1378 Value **VP, **Values = VP = new Value*[NumOps];
1379 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1380 *VP = DstValue->getOperand(i);
1381 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1382 *VP = SrcValue->getOperand(i);
1383 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1384 ArrayRef<Value*>(Values,
1385 NumOps)));
1386 delete[] Values;
1387 break;
1388 }
1389 case Module::AppendUnique: {
1390 SmallSetVector<Value*, 16> Elts;
1391 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1392 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1393 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1394 Elts.insert(DstValue->getOperand(i));
1395 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1396 Elts.insert(SrcValue->getOperand(i));
1397 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1398 ArrayRef<Value*>(Elts.begin(),
1399 Elts.end())));
1400 break;
1401 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001402 }
Bill Wendling66f02412012-02-11 11:38:06 +00001403 }
1404
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001405 // Check all of the requirements.
1406 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1407 MDNode *Requirement = Requirements[I];
1408 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1409 Value *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001410
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001411 MDNode *Op = Flags[Flag];
1412 if (!Op || Op->getOperand(2) != ReqValue) {
1413 HasErr |= emitError("linking module flags '" + Flag->getString() +
1414 "': does not have the required value");
1415 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001416 }
1417 }
1418
1419 return HasErr;
1420}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001421
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001422bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001423 assert(DstM && "Null destination module");
1424 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001425
1426 // Inherit the target data from the source module if the destination module
1427 // doesn't have one already.
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001428 if (!DstM->getDataLayout() && SrcM->getDataLayout())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001429 DstM->setDataLayout(SrcM->getDataLayout());
1430
1431 // Copy the target triple from the source to dest if the dest's is empty.
1432 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1433 DstM->setTargetTriple(SrcM->getTargetTriple());
1434
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001435 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
Rafael Espindolaae593f12014-02-26 17:02:08 +00001436 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001437 emitWarning("Linking two modules of different data layouts: '" +
1438 SrcM->getModuleIdentifier() + "' is '" +
1439 SrcM->getDataLayoutStr() + "' whereas '" +
1440 DstM->getModuleIdentifier() + "' is '" +
1441 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001442 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001443 if (!SrcM->getTargetTriple().empty() &&
1444 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001445 emitWarning("Linking two modules of different target triples: " +
1446 SrcM->getModuleIdentifier() + "' is '" +
1447 SrcM->getTargetTriple() + "' whereas '" +
1448 DstM->getModuleIdentifier() + "' is '" +
1449 DstM->getTargetTriple() + "'\n");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001450 }
1451
1452 // Append the module inline asm string.
1453 if (!SrcM->getModuleInlineAsm().empty()) {
1454 if (DstM->getModuleInlineAsm().empty())
1455 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1456 else
1457 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1458 SrcM->getModuleInlineAsm());
1459 }
1460
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001461 // Loop over all of the linked values to compute type mappings.
1462 computeTypeMapping();
1463
David Majnemerdad0a642014-06-27 18:19:56 +00001464 ComdatsChosen.clear();
David Blaikie5106ce72014-11-19 05:49:42 +00001465 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +00001466 const Comdat &C = SMEC.getValue();
1467 if (ComdatsChosen.count(&C))
1468 continue;
1469 Comdat::SelectionKind SK;
1470 bool LinkFromSrc;
1471 if (getComdatResult(&C, SK, LinkFromSrc))
1472 return true;
1473 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1474 }
1475
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001476 // Upgrade mismatched global arrays.
1477 upgradeMismatchedGlobals();
1478
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001479 // Insert all of the globals in src into the DstM module... without linking
1480 // initializers (which could refer to functions not yet mapped over).
1481 for (Module::global_iterator I = SrcM->global_begin(),
1482 E = SrcM->global_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001483 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001484 return true;
1485
1486 // Link the functions together between the two modules, without doing function
1487 // bodies... this just adds external function prototypes to the DstM
1488 // function... We do this so that when we begin processing function bodies,
1489 // all of the global values that may be referenced are available in our
1490 // ValueMap.
1491 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001492 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001493 return true;
1494
1495 // If there were any aliases, link them now.
1496 for (Module::alias_iterator I = SrcM->alias_begin(),
1497 E = SrcM->alias_end(); I != E; ++I)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001498 if (linkGlobalValueProto(I))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001499 return true;
1500
1501 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1502 linkAppendingVarInit(AppendingVars[i]);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001503
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001504 // Link in the function bodies that are defined in the source module into
1505 // DstM.
1506 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
Tanya Lattnerea166d42011-10-14 22:17:46 +00001507 // Skip if not linking from source.
1508 if (DoNotLinkFromSource.count(SF)) continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001509
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001510 Function *DF = cast<Function>(ValueMap[SF]);
1511 if (SF->hasPrefixData()) {
1512 // Link in the prefix data.
1513 DF->setPrefixData(MapValue(
1514 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1515 }
1516
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001517 // Materialize if needed.
Rafael Espindola246c4fb2014-11-01 16:46:18 +00001518 if (std::error_code EC = SF->materialize())
1519 return emitError(EC.message());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001520
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001521 // Skip if no body (function is external).
1522 if (SF->isDeclaration())
1523 continue;
1524
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001525 linkFunctionBody(DF, SF);
Bill Wendling00623782012-03-23 07:22:49 +00001526 SF->Dematerialize();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001527 }
1528
1529 // Resolve all uses of aliases with aliasees.
1530 linkAliasBodies();
1531
Bill Wendling66f02412012-02-11 11:38:06 +00001532 // Remap all of the named MDNodes in Src into the DstM module. We do this
Devang Patel6ddbb2e2011-08-04 19:44:28 +00001533 // after linking GlobalValues so that MDNodes that reference GlobalValues
1534 // are properly remapped.
1535 linkNamedMDNodes();
1536
Bill Wendling66f02412012-02-11 11:38:06 +00001537 // Merge the module flags into the DstM module.
1538 if (linkModuleFlagsMetadata())
1539 return true;
1540
Bill Wendling91686d62014-01-16 06:29:36 +00001541 // Update the initializers in the DstM module now that all globals that may
1542 // be referenced are in DstM.
1543 linkGlobalInits();
1544
Tanya Lattner0a48b872011-11-02 00:24:56 +00001545 // Process vector of lazily linked in functions.
1546 bool LinkedInAnyFunctions;
1547 do {
1548 LinkedInAnyFunctions = false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001549
Bill Wendlingfa2287822013-03-27 17:54:41 +00001550 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001551 E = LazilyLinkFunctions.end(); I != E; ++I) {
Bill Wendlingfa2287822013-03-27 17:54:41 +00001552 Function *SF = *I;
James Molloyf6f121e2013-05-28 15:17:05 +00001553 if (!SF)
1554 continue;
Bill Wendling00623782012-03-23 07:22:49 +00001555
James Molloyf6f121e2013-05-28 15:17:05 +00001556 Function *DF = cast<Function>(ValueMap[SF]);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00001557 if (SF->hasPrefixData()) {
1558 // Link in the prefix data.
1559 DF->setPrefixData(MapValue(SF->getPrefixData(),
1560 ValueMap,
1561 RF_None,
1562 &TypeMap,
1563 &ValMaterializer));
1564 }
James Molloyf6f121e2013-05-28 15:17:05 +00001565
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001566 // Materialize if needed.
Rafael Espindola246c4fb2014-11-01 16:46:18 +00001567 if (std::error_code EC = SF->materialize())
1568 return emitError(EC.message());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001569
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001570 // Skip if no body (function is external).
1571 if (SF->isDeclaration())
1572 continue;
1573
James Molloyf6f121e2013-05-28 15:17:05 +00001574 // Erase from vector *before* the function body is linked - linkFunctionBody could
1575 // invalidate I.
1576 LazilyLinkFunctions.erase(I);
1577
1578 // Link in function body.
1579 linkFunctionBody(DF, SF);
1580 SF->Dematerialize();
1581
1582 // Set flag to indicate we may have more functions to lazily link in
1583 // since we linked in a function.
1584 LinkedInAnyFunctions = true;
1585 break;
Tanya Lattner0a48b872011-11-02 00:24:56 +00001586 }
1587 } while (LinkedInAnyFunctions);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001588
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001589 // Now that all of the types from the source are used, resolve any structs
1590 // copied over to the dest that didn't exist there.
1591 TypeMap.linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001592
Anton Korobeynikov26098882008-03-05 23:21:39 +00001593 return false;
1594}
Reid Spencer361e5132004-11-12 20:37:43 +00001595
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001596void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1597 this->Composite = M;
1598 this->DiagnosticHandler = DiagnosticHandler;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001599
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00001600 TypeFinder StructTypes;
1601 StructTypes.run(*M, true);
1602 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1603}
Rafael Espindola3df61b72013-05-04 03:48:37 +00001604
Rafael Espindola5cb9c822014-11-17 20:51:01 +00001605Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1606 init(M, DiagnosticHandler);
1607}
1608
1609Linker::Linker(Module *M) {
1610 init(M, [this](const DiagnosticInfo &DI) {
1611 Composite->getContext().diagnose(DI);
1612 });
1613}
1614
Rafael Espindola3df61b72013-05-04 03:48:37 +00001615Linker::~Linker() {
1616}
1617
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001618void Linker::deleteModule() {
1619 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00001620 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00001621}
1622
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001623bool Linker::linkInModule(Module *Src) {
1624 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1625 DiagnosticHandler);
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001626 return TheLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +00001627}
1628
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001629//===----------------------------------------------------------------------===//
1630// LinkModules entrypoint.
1631//===----------------------------------------------------------------------===//
1632
Rafael Espindola18c89412014-10-27 02:35:46 +00001633/// This function links two modules together, with the resulting Dest module
1634/// modified to be the composite of the two input modules. If an error occurs,
1635/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1636/// Upon failure, the Dest module could be in a modified state, and shouldn't be
1637/// relied on to be consistent.
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001638bool Linker::LinkModules(Module *Dest, Module *Src,
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001639 DiagnosticHandlerFunction DiagnosticHandler) {
1640 Linker L(Dest, DiagnosticHandler);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001641 return L.linkInModule(Src);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001642}
1643
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001644bool Linker::LinkModules(Module *Dest, Module *Src) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00001645 Linker L(Dest);
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001646 return L.linkInModule(Src);
Reid Spencer361e5132004-11-12 20:37:43 +00001647}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001648
1649//===----------------------------------------------------------------------===//
1650// C API.
1651//===----------------------------------------------------------------------===//
1652
1653LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1654 LLVMLinkerMode Mode, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001655 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001656 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00001657 raw_string_ostream Stream(Message);
1658 DiagnosticPrinterRawOStream DP(Stream);
1659
1660 LLVMBool Result = Linker::LinkModules(
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001661 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00001662
1663 if (OutMessages && Result)
1664 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +00001665 return Result;
1666}