blob: 4b1b9d21e428ef07bf7a031b6e51f42c0d74e257 [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 Espindola31ad4682014-12-03 22:36:37 +000016#include "llvm/ADT/Hashing.h"
Rafael Espindola23f8d642012-01-05 23:02:01 +000017#include "llvm/ADT/Optional.h"
Bill Wendling66f02412012-02-11 11:38:06 +000018#include "llvm/ADT/SetVector.h"
Eli Bendersky0f7fd362013-03-19 15:26:24 +000019#include "llvm/ADT/SmallString.h"
Rafael Espindola31ad4682014-12-03 22:36:37 +000020#include "llvm/ADT/Statistic.h"
Akira Hatanakac43df512015-02-13 00:40:41 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithfda0cee2014-12-18 01:05:33 +000023#include "llvm/IR/DebugInfo.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000024#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/DiagnosticPrinter.h"
26#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000028#include "llvm/IR/TypeFinder.h"
Eli Benderskye17f3702014-02-06 18:01:56 +000029#include "llvm/Support/CommandLine.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000030#include "llvm/Support/Debug.h"
Bill Wendlingb6af2f32012-03-22 20:28:27 +000031#include "llvm/Support/raw_ostream.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000032#include "llvm/Transforms/Utils/Cloning.h"
Will Dietz981af002013-10-12 00:55:57 +000033#include <cctype>
David Majnemer82d6ff62014-06-27 18:38:12 +000034#include <tuple>
Reid Spencer361e5132004-11-12 20:37:43 +000035using namespace llvm;
36
Eli Benderskye17f3702014-02-06 18:01:56 +000037
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000038//===----------------------------------------------------------------------===//
39// TypeMap implementation.
40//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000041
Chris Lattnereee6f992008-06-16 21:00:18 +000042namespace {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000043class TypeMapTy : public ValueMapTypeRemapper {
Rafael Espindola18c89412014-10-27 02:35:46 +000044 /// This is a mapping from a source type to a destination type to use.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000045 DenseMap<Type*, Type*> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000046
Rafael Espindola18c89412014-10-27 02:35:46 +000047 /// When checking to see if two subgraphs are isomorphic, we speculatively
48 /// add types to MappedTypes, but keep track of them here in case we need to
49 /// roll back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000050 SmallVector<Type*, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000051
Rafael Espindolaa96f2352014-11-28 16:41:24 +000052 SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
53
Rafael Espindola18c89412014-10-27 02:35:46 +000054 /// This is a list of non-opaque structs in the source module that are mapped
55 /// to an opaque struct in the destination module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000056 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000057
Rafael Espindola18c89412014-10-27 02:35:46 +000058 /// This is the set of opaque types in the destination modules who are
59 /// getting a body from the source module.
Chris Lattner5e3bd972011-12-20 00:03:52 +000060 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000061
Chris Lattner56cdea62008-06-16 23:06:51 +000062public:
Rafael Espindola31ad4682014-12-03 22:36:37 +000063 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
64 : DstStructTypesSet(DstStructTypesSet) {}
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000065
Rafael Espindola31ad4682014-12-03 22:36:37 +000066 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
Rafael Espindola18c89412014-10-27 02:35:46 +000067 /// Indicate that the specified type in the destination module is conceptually
68 /// equivalent to the specified type in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000069 void addTypeMapping(Type *DstTy, Type *SrcTy);
70
Rafael Espindolad2a13a22014-11-25 04:28:31 +000071 /// Produce a body for an opaque type in the dest module from a type
72 /// definition in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000073 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000074
Rafael Espindola18c89412014-10-27 02:35:46 +000075 /// Return the mapped type to use for the specified input type from the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000076 /// source module.
77 Type *get(Type *SrcTy);
Rafael Espindola31ad4682014-12-03 22:36:37 +000078 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
79
80 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000081
Rafael Espindola290e2cc2014-11-25 14:35:53 +000082 FunctionType *get(FunctionType *T) {
83 return cast<FunctionType>(get((Type *)T));
84 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000085
Rafael Espindola18c89412014-10-27 02:35:46 +000086 /// Dump out the type map for debugging purposes.
Bill Wendlingb6af2f32012-03-22 20:28:27 +000087 void dump() const {
Rafael Espindola8f144712014-11-25 06:16:27 +000088 for (auto &Pair : MappedTypes) {
Bill Wendlingb6af2f32012-03-22 20:28:27 +000089 dbgs() << "TypeMap: ";
Rafael Espindola8f144712014-11-25 06:16:27 +000090 Pair.first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000091 dbgs() << " => ";
Rafael Espindola8f144712014-11-25 06:16:27 +000092 Pair.second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000093 dbgs() << '\n';
94 }
95 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000096
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000097private:
Rafael Espindola290e2cc2014-11-25 14:35:53 +000098 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000099
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000100 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +0000101};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000102}
Chris Lattnereee6f992008-06-16 21:00:18 +0000103
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000104void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
Rafael Espindola3d097412014-11-28 16:26:14 +0000105 assert(SpeculativeTypes.empty());
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000106 assert(SpeculativeDstOpaqueTypes.empty());
Rafael Espindola3d097412014-11-28 16:26:14 +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.
Duncan P. N. Exon Smithc586eaa2014-11-27 17:01:10 +0000110 if (!areTypesIsomorphic(DstTy, SrcTy)) {
111 // Oops, they aren't isomorphic. Just discard this request by rolling out
112 // any speculative mappings we've established.
Rafael Espindola3d097412014-11-28 16:26:14 +0000113 for (Type *Ty : SpeculativeTypes)
114 MappedTypes.erase(Ty);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000115
116 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
117 SpeculativeDstOpaqueTypes.size());
118 for (StructType *Ty : SpeculativeDstOpaqueTypes)
119 DstResolvedOpaqueTypes.erase(Ty);
Rafael Espindola04a74af2014-12-01 04:15:59 +0000120 } else {
121 for (Type *Ty : SpeculativeTypes)
122 if (auto *STy = dyn_cast<StructType>(Ty))
123 if (STy->hasName())
124 STy->setName("");
Bill Wendlingd48b7782012-02-28 04:01:21 +0000125 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000126 SpeculativeTypes.clear();
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000127 SpeculativeDstOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000128}
Chris Lattnereee6f992008-06-16 21:00:18 +0000129
Rafael Espindola18c89412014-10-27 02:35:46 +0000130/// Recursively walk this pair of types, returning true if they are isomorphic,
131/// false if they are not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000132bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
133 // Two types with differing kinds are clearly not isomorphic.
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000134 if (DstTy->getTypeID() != SrcTy->getTypeID())
135 return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000136
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000137 // If we have an entry in the MappedTypes table, then we have our answer.
138 Type *&Entry = MappedTypes[SrcTy];
139 if (Entry)
140 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000141
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000142 // Two identical types are clearly isomorphic. Remember this
143 // non-speculatively.
144 if (DstTy == SrcTy) {
145 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000146 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000147 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000148
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000149 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000150
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000151 // If this is an opaque struct type, special case it.
152 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
153 // Mapping an opaque type to any struct, just keep the dest struct.
154 if (SSTy->isOpaque()) {
155 Entry = DstTy;
156 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000157 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000158 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000159
Chris Lattner5e3bd972011-12-20 00:03:52 +0000160 // Mapping a non-opaque source type to an opaque dest. If this is the first
161 // type that we're mapping onto this destination type then we succeed. Keep
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000162 // the dest, but fill it in later. If this is the second (different) type
163 // that we're trying to map onto the same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000164 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000165 // We can only map one source type onto the opaque destination type.
David Blaikie70573dc2014-11-19 07:49:26 +0000166 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
Chris Lattner5e3bd972011-12-20 00:03:52 +0000167 return false;
168 SrcDefinitionsToResolve.push_back(SSTy);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000169 SpeculativeTypes.push_back(SrcTy);
170 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000171 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000172 return true;
173 }
174 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000175
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000176 // If the number of subtypes disagree between the two types, then we fail.
177 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000178 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000179
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000180 // Fail if any of the extra properties (e.g. array size) of the type disagree.
181 if (isa<IntegerType>(DstTy))
182 return false; // bitwidth disagrees.
183 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
184 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
185 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000186
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000187 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
188 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
189 return false;
190 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
191 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000192 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000193 DSTy->isPacked() != SSTy->isPacked())
194 return false;
195 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
196 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
197 return false;
198 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000199 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000200 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000201 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000202
203 // Otherwise, we speculate that these two types will line up and recursively
204 // check the subelements.
205 Entry = DstTy;
206 SpeculativeTypes.push_back(SrcTy);
207
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000208 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
209 if (!areTypesIsomorphic(DstTy->getContainedType(I),
210 SrcTy->getContainedType(I)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000211 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000212
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000213 // If everything seems to have lined up, then everything is great.
214 return true;
215}
216
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000217void TypeMapTy::linkDefinedTypeBodies() {
218 SmallVector<Type*, 16> Elements;
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000219 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000220 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000221 assert(DstSTy->isOpaque());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000222
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000223 // Map the body of the source type over to a new body for the dest type.
224 Elements.resize(SrcSTy->getNumElements());
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000225 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000226 Elements[I] = get(SrcSTy->getElementType(I));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000228 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaa5b9e1c2015-03-06 00:50:21 +0000229 DstStructTypesSet.switchToNonOpaque(DstSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000230 }
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000231 SrcDefinitionsToResolve.clear();
Chris Lattner5e3bd972011-12-20 00:03:52 +0000232 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000233}
234
Rafael Espindola31ad4682014-12-03 22:36:37 +0000235void TypeMapTy::finishType(StructType *DTy, StructType *STy,
236 ArrayRef<Type *> ETypes) {
237 DTy->setBody(ETypes, STy->isPacked());
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000238
239 // Steal STy's name.
240 if (STy->hasName()) {
241 SmallString<16> TmpName = STy->getName();
242 STy->setName("");
243 DTy->setName(TmpName);
244 }
245
Rafael Espindola31ad4682014-12-03 22:36:37 +0000246 DstStructTypesSet.addNonOpaque(DTy);
247}
248
249Type *TypeMapTy::get(Type *Ty) {
250 SmallPtrSet<StructType *, 8> Visited;
251 return get(Ty, Visited);
252}
253
254Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
255 // If we already have an entry for this type, return it.
256 Type **Entry = &MappedTypes[Ty];
257 if (*Entry)
258 return *Entry;
259
260 // These are types that LLVM itself will unique.
261 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
262
263#ifndef NDEBUG
264 if (!IsUniqued) {
265 for (auto &Pair : MappedTypes) {
266 assert(!(Pair.first != Ty && Pair.second == Ty) &&
267 "mapping to a source type");
268 }
269 }
270#endif
271
272 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
273 StructType *DTy = StructType::create(Ty->getContext());
274 return *Entry = DTy;
275 }
276
277 // If this is not a recursive type, then just map all of the elements and
278 // then rebuild the type from inside out.
279 SmallVector<Type *, 4> ElementTypes;
280
281 // If there are no element types to map, then the type is itself. This is
282 // true for the anonymous {} struct, things like 'float', integers, etc.
283 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
284 return *Entry = Ty;
285
286 // Remap all of the elements, keeping track of whether any of them change.
287 bool AnyChange = false;
288 ElementTypes.resize(Ty->getNumContainedTypes());
289 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
290 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
291 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
292 }
293
294 // If we found our type while recursively processing stuff, just use it.
295 Entry = &MappedTypes[Ty];
296 if (*Entry) {
297 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
298 if (DTy->isOpaque()) {
299 auto *STy = cast<StructType>(Ty);
300 finishType(DTy, STy, ElementTypes);
301 }
302 }
303 return *Entry;
304 }
305
306 // If all of the element types mapped directly over and the type is not
307 // a nomed struct, then the type is usable as-is.
308 if (!AnyChange && IsUniqued)
309 return *Entry = Ty;
310
311 // Otherwise, rebuild a modified type.
312 switch (Ty->getTypeID()) {
313 default:
314 llvm_unreachable("unknown derived type to remap");
315 case Type::ArrayTyID:
316 return *Entry = ArrayType::get(ElementTypes[0],
317 cast<ArrayType>(Ty)->getNumElements());
318 case Type::VectorTyID:
319 return *Entry = VectorType::get(ElementTypes[0],
320 cast<VectorType>(Ty)->getNumElements());
321 case Type::PointerTyID:
322 return *Entry = PointerType::get(ElementTypes[0],
323 cast<PointerType>(Ty)->getAddressSpace());
324 case Type::FunctionTyID:
325 return *Entry = FunctionType::get(ElementTypes[0],
326 makeArrayRef(ElementTypes).slice(1),
327 cast<FunctionType>(Ty)->isVarArg());
328 case Type::StructTyID: {
329 auto *STy = cast<StructType>(Ty);
330 bool IsPacked = STy->isPacked();
331 if (IsUniqued)
332 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
333
334 // If the type is opaque, we can just use it directly.
335 if (STy->isOpaque()) {
336 DstStructTypesSet.addOpaque(STy);
337 return *Entry = Ty;
338 }
339
340 if (StructType *OldT =
341 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
342 STy->setName("");
343 return *Entry = OldT;
344 }
345
346 if (!AnyChange) {
347 DstStructTypesSet.addNonOpaque(STy);
348 return *Entry = Ty;
349 }
350
351 StructType *DTy = StructType::create(Ty->getContext());
352 finishType(DTy, STy, ElementTypes);
353 return *Entry = DTy;
354 }
355 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000356}
357
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000358//===----------------------------------------------------------------------===//
359// ModuleLinker implementation.
360//===----------------------------------------------------------------------===//
361
362namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +0000363class ModuleLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000364
Rafael Espindolac84f6082014-11-25 06:11:24 +0000365/// Creates prototypes for functions that are lazily linked on the fly. This
366/// speeds up linking for modules with many/ lazily linked functions of which
367/// few get used.
David Blaikie437aafd2015-10-19 22:15:55 +0000368class ValueMaterializerTy final : public ValueMaterializer {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000369 ModuleLinker *ModLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000370
Rafael Espindolac84f6082014-11-25 06:11:24 +0000371public:
Rafael Espindola19b52382015-11-27 20:28:19 +0000372 ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
Rafael Espindolac84f6082014-11-25 06:11:24 +0000373
Rafael Espindola19b52382015-11-27 20:28:19 +0000374 Value *materializeDeclFor(Value *V) override;
375 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
Rafael Espindolac84f6082014-11-25 06:11:24 +0000376};
377
378class LinkDiagnosticInfo : public DiagnosticInfo {
379 const Twine &Msg;
380
381public:
382 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
383 void print(DiagnosticPrinter &DP) const override;
384};
385LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
386 const Twine &Msg)
387 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
388void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
389
390/// This is an implementation class for the LinkModules function, which is the
391/// entrypoint for this file.
392class ModuleLinker {
393 Module *DstM, *SrcM;
394
395 TypeMapTy TypeMap;
396 ValueMaterializerTy ValMaterializer;
397
398 /// Mapping of values from what they used to be in Src, to what they are now
399 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
400 /// due to the use of Value handles which the Linker doesn't actually need,
401 /// but this allows us to reuse the ValueMapper code.
402 ValueToValueMapTy ValueMap;
403
404 struct AppendingVarInfo {
405 GlobalVariable *NewGV; // New aggregate global in dest module.
406 const Constant *DstInit; // Old initializer from dest module.
407 const Constant *SrcInit; // Old initializer from src module.
James Molloyf6f121e2013-05-28 15:17:05 +0000408 };
409
Rafael Espindolac84f6082014-11-25 06:11:24 +0000410 std::vector<AppendingVarInfo> AppendingVars;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000411
Rafael Espindolac84f6082014-11-25 06:11:24 +0000412 // Set of items not to link in from source.
413 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000414
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000415 DiagnosticHandlerFunction DiagnosticHandler;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000416
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000417 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +0000418 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000419
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000420 /// Function index passed into ModuleLinker for using in function
421 /// importing/exporting handling.
Mehdi Amini8220e8a2015-11-23 01:59:16 +0000422 const FunctionInfoIndex *ImportIndex;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000423
424 /// Function to import from source module, all other functions are
425 /// imported as declarations instead of definitions.
426 Function *ImportFunction;
427
428 /// Set to true if the given FunctionInfoIndex contains any functions
429 /// from this source module, in which case we must conservatively assume
430 /// that any of its functions may be imported into another module
431 /// as part of a different backend compilation process.
432 bool HasExportedFunctions;
433
Teresa Johnson10632932015-11-06 17:50:53 +0000434 /// Set to true when all global value body linking is complete (including
435 /// lazy linking). Used to prevent metadata linking from creating new
436 /// references.
437 bool DoneLinkingBodies;
438
Rafael Espindolac84f6082014-11-25 06:11:24 +0000439public:
Rafael Espindola31ad4682014-12-03 22:36:37 +0000440 ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000441 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
Mehdi Amini8220e8a2015-11-23 01:59:16 +0000442 const FunctionInfoIndex *Index = nullptr,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000443 Function *FuncToImport = nullptr)
Rafael Espindola19b52382015-11-27 20:28:19 +0000444 : DstM(dstM), SrcM(srcM), TypeMap(Set), ValMaterializer(this),
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000445 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
Teresa Johnson10632932015-11-06 17:50:53 +0000446 ImportFunction(FuncToImport), HasExportedFunctions(false),
447 DoneLinkingBodies(false) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000448 assert((ImportIndex || !ImportFunction) &&
449 "Expect a FunctionInfoIndex when importing");
450 // If we have a FunctionInfoIndex but no function to import,
451 // then this is the primary module being compiled in a ThinLTO
452 // backend compilation, and we need to see if it has functions that
453 // may be exported to another backend compilation.
454 if (ImportIndex && !ImportFunction)
455 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
456 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000457
Rafael Espindolac84f6082014-11-25 06:11:24 +0000458 bool run();
Rafael Espindola19b52382015-11-27 20:28:19 +0000459 Value *materializeDeclFor(Value *V);
460 void materializeInitFor(GlobalValue *New, GlobalValue *Old);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000461
Rafael Espindola19b52382015-11-27 20:28:19 +0000462private:
Artem Belevich020d4fb2015-09-01 17:55:55 +0000463 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
464 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
465 bool shouldInternalizeLinkedSymbols() {
466 return Flags & Linker::InternalizeLinkedSymbols;
467 }
468
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000469 /// Handles cloning of a global values from the source module into
470 /// the destination module, including setting the attributes and visibility.
471 GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
472 const GlobalValue *DGV = nullptr);
473
474 /// Check if we should promote the given local value to global scope.
475 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
476
Teresa Johnson10632932015-11-06 17:50:53 +0000477 /// Check if all global value body linking is complete.
478 bool doneLinkingBodies() { return DoneLinkingBodies; }
479
Rafael Espindolac84f6082014-11-25 06:11:24 +0000480 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
481 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000482
Rafael Espindolac84f6082014-11-25 06:11:24 +0000483 /// Helper method for setting a message and returning an error code.
484 bool emitError(const Twine &Message) {
485 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
486 return true;
487 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000488
Rafael Espindolac84f6082014-11-25 06:11:24 +0000489 void emitWarning(const Twine &Message) {
490 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
491 }
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000492
Rafael Espindolac84f6082014-11-25 06:11:24 +0000493 bool getComdatLeader(Module *M, StringRef ComdatName,
494 const GlobalVariable *&GVar);
495 bool computeResultingSelectionKind(StringRef ComdatName,
496 Comdat::SelectionKind Src,
497 Comdat::SelectionKind Dst,
498 Comdat::SelectionKind &Result,
499 bool &LinkFromSrc);
500 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
501 ComdatsChosen;
502 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
503 bool &LinkFromSrc);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +0000504 // Keep track of the global value members of each comdat in source.
505 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000506
Rafael Espindolac84f6082014-11-25 06:11:24 +0000507 /// Given a global in the source module, return the global in the
508 /// destination module that is being linked to, if any.
509 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
510 // If the source has no name it can't link. If it has local linkage,
511 // there is no name match-up going on.
Teresa Johnsonb098f0c2015-11-24 19:46:58 +0000512 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
Rafael Espindolac84f6082014-11-25 06:11:24 +0000513 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000514
Rafael Espindolac84f6082014-11-25 06:11:24 +0000515 // Otherwise see if we have a match in the destination module's symtab.
Teresa Johnsonb098f0c2015-11-24 19:46:58 +0000516 GlobalValue *DGV = DstM->getNamedValue(getName(SrcGV));
Rafael Espindolac84f6082014-11-25 06:11:24 +0000517 if (!DGV)
518 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000519
Rafael Espindolac84f6082014-11-25 06:11:24 +0000520 // If we found a global with the same name in the dest module, but it has
521 // internal linkage, we are really not doing any linkage here.
522 if (DGV->hasLocalLinkage())
523 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000524
Rafael Espindolac84f6082014-11-25 06:11:24 +0000525 // Otherwise, we do in fact link to the destination global.
526 return DGV;
527 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000528
Rafael Espindolac84f6082014-11-25 06:11:24 +0000529 void computeTypeMapping();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000530
Rafael Espindolac84f6082014-11-25 06:11:24 +0000531 void upgradeMismatchedGlobalArray(StringRef Name);
532 void upgradeMismatchedGlobals();
David Majnemerdad0a642014-06-27 18:19:56 +0000533
Rafael Espindolac84f6082014-11-25 06:11:24 +0000534 bool linkAppendingVarProto(GlobalVariable *DstGV,
535 const GlobalVariable *SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000536
Rafael Espindolac84f6082014-11-25 06:11:24 +0000537 bool linkGlobalValueProto(GlobalValue *GV);
Rafael Espindolac84f6082014-11-25 06:11:24 +0000538 bool linkModuleFlagsMetadata();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000539
Rafael Espindola9f30fac2015-11-29 03:21:30 +0000540 void linkAppendingVarInit(AppendingVarInfo &AVI);
Rafael Espindolaef237112014-12-08 18:45:16 +0000541
542 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
543 bool linkFunctionBody(Function &Dst, Function &Src);
544 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
545 bool linkGlobalValueBody(GlobalValue &Src);
546
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000547 /// Functions that take care of cloning a specific global value type
548 /// into the destination module.
549 GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
550 const GlobalVariable *SGVar);
551 Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
552 GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
553
554 /// Helper methods to check if we are importing from or potentially
555 /// exporting from the current source module.
556 bool isPerformingImport() { return ImportFunction != nullptr; }
557 bool isModuleExporting() { return HasExportedFunctions; }
558
559 /// If we are importing from the source module, checks if we should
560 /// import SGV as a definition, otherwise import as a declaration.
561 bool doImportAsDefinition(const GlobalValue *SGV);
562
563 /// Get the name for SGV that should be used in the linked destination
564 /// module. Specifically, this handles the case where we need to rename
565 /// a local that is being promoted to global scope.
566 std::string getName(const GlobalValue *SGV);
567
568 /// Get the new linkage for SGV that should be used in the linked destination
569 /// module. Specifically, for ThinLTO importing or exporting it may need
570 /// to be adjusted.
571 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
572
573 /// Copies the necessary global value attributes and name from the source
574 /// to the newly cloned global value.
575 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
576
577 /// Updates the visibility for the new global cloned from the source
578 /// and, if applicable, linked with an existing destination global.
579 /// Handles visibility change required for promoted locals.
580 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
581 const GlobalValue *DGV = nullptr);
582
Rafael Espindolac84f6082014-11-25 06:11:24 +0000583 void linkNamedMDNodes();
584};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000585}
Bill Wendlingd48b7782012-02-28 04:01:21 +0000586
Rafael Espindola18c89412014-10-27 02:35:46 +0000587/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
588/// table. This is good for all clients except for us. Go through the trouble
589/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000590static void forceRenaming(GlobalValue *GV, StringRef Name) {
591 // If the global doesn't force its name or if it already has the right name,
592 // there is nothing for us to do.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000593 // Note that any required local to global promotion should already be done,
594 // so promoted locals will not skip this handling as their linkage is no
595 // longer local.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000596 if (GV->hasLocalLinkage() || GV->getName() == Name)
597 return;
598
599 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000600
601 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000602 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000603 GV->takeName(ConflictGV);
604 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000605 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000606 } else {
607 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000608 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000609}
Reid Spencer90246aa2007-02-04 04:29:21 +0000610
Rafael Espindola18c89412014-10-27 02:35:46 +0000611/// copy additional attributes (those not needed to construct a GlobalValue)
612/// from the SrcGV to the DestGV.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000613void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
614 const GlobalValue *SrcGV) {
615 auto *GA = dyn_cast<GlobalAlias>(SrcGV);
616 // Check for the special case of converting an alias (definition) to a
617 // non-alias (declaration). This can happen when we are importing and
618 // encounter a weak_any alias (weak_any defs may not be imported, see
619 // comments in ModuleLinker::getLinkage) or an alias whose base object is
620 // being imported as a declaration. In that case copy the attributes from the
621 // base object.
622 if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
Teresa Johnson3cd81612015-11-10 18:20:11 +0000623 assert(isPerformingImport() && !doImportAsDefinition(GA));
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000624 NewGV->copyAttributesFrom(GA->getBaseObject());
625 } else
626 NewGV->copyAttributesFrom(SrcGV);
627 forceRenaming(NewGV, getName(SrcGV));
Reid Spencer361e5132004-11-12 20:37:43 +0000628}
629
Rafael Espindola23f8d642012-01-05 23:02:01 +0000630static bool isLessConstraining(GlobalValue::VisibilityTypes a,
631 GlobalValue::VisibilityTypes b) {
632 if (a == GlobalValue::HiddenVisibility)
633 return false;
634 if (b == GlobalValue::HiddenVisibility)
635 return true;
636 if (a == GlobalValue::ProtectedVisibility)
637 return false;
638 if (b == GlobalValue::ProtectedVisibility)
639 return true;
640 return false;
641}
642
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000643bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
644 if (!isPerformingImport())
645 return false;
Teresa Johnson3cd81612015-11-10 18:20:11 +0000646 auto *GA = dyn_cast<GlobalAlias>(SGV);
647 if (GA) {
648 if (GA->hasWeakAnyLinkage())
649 return false;
Rafael Espindola89345772015-11-26 19:22:59 +0000650 const GlobalObject *GO = GA->getBaseObject();
651 if (!GO->hasLinkOnceODRLinkage())
652 return false;
653 return doImportAsDefinition(GO);
Teresa Johnson3cd81612015-11-10 18:20:11 +0000654 }
Teresa Johnsondfbebc32015-11-10 18:26:31 +0000655 // Always import GlobalVariable definitions, except for the special
656 // case of WeakAny which are imported as ExternalWeak declarations
657 // (see comments in ModuleLinker::getLinkage). The linkage changes
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000658 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
659 // global variables with external linkage are transformed to
Teresa Johnson3cd81612015-11-10 18:20:11 +0000660 // available_externally definitions, which are ultimately turned into
661 // declarations after the EliminateAvailableExternally pass).
Craig Topper66059c92015-11-18 07:07:59 +0000662 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
Teresa Johnson3cd81612015-11-10 18:20:11 +0000663 !SGV->hasWeakAnyLinkage())
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000664 return true;
665 // Only import the function requested for importing.
666 auto *SF = dyn_cast<Function>(SGV);
667 if (SF && SF == ImportFunction)
668 return true;
669 // Otherwise no.
670 return false;
671}
672
673bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
674 assert(SGV->hasLocalLinkage());
675 // Both the imported references and the original local variable must
676 // be promoted.
677 if (!isPerformingImport() && !isModuleExporting())
678 return false;
679
680 // Local const variables never need to be promoted unless they are address
681 // taken. The imported uses can simply use the clone created in this module.
682 // For now we are conservative in determining which variables are not
683 // address taken by checking the unnamed addr flag. To be more aggressive,
684 // the address taken information must be checked earlier during parsing
685 // of the module and recorded in the function index for use when importing
686 // from that module.
687 auto *GVar = dyn_cast<GlobalVariable>(SGV);
688 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
689 return false;
690
691 // Eventually we only need to promote functions in the exporting module that
692 // are referenced by a potentially exported function (i.e. one that is in the
693 // function index).
694 return true;
695}
696
697std::string ModuleLinker::getName(const GlobalValue *SGV) {
698 // For locals that must be promoted to global scope, ensure that
699 // the promoted name uniquely identifies the copy in the original module,
700 // using the ID assigned during combined index creation. When importing,
701 // we rename all locals (not just those that are promoted) in order to
702 // avoid naming conflicts between locals imported from different modules.
703 if (SGV->hasLocalLinkage() &&
704 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
705 return FunctionInfoIndex::getGlobalNameForLocal(
706 SGV->getName(),
707 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
708 return SGV->getName();
709}
710
711GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
712 // Any local variable that is referenced by an exported function needs
713 // to be promoted to global scope. Since we don't currently know which
714 // functions reference which local variables/functions, we must treat
715 // all as potentially exported if this module is exporting anything.
716 if (isModuleExporting()) {
717 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
718 return GlobalValue::ExternalLinkage;
719 return SGV->getLinkage();
720 }
721
722 // Otherwise, if we aren't importing, no linkage change is needed.
723 if (!isPerformingImport())
724 return SGV->getLinkage();
725
726 switch (SGV->getLinkage()) {
727 case GlobalValue::ExternalLinkage:
728 // External defnitions are converted to available_externally
729 // definitions upon import, so that they are available for inlining
730 // and/or optimization, but are turned into declarations later
731 // during the EliminateAvailableExternally pass.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000732 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000733 return GlobalValue::AvailableExternallyLinkage;
734 // An imported external declaration stays external.
735 return SGV->getLinkage();
736
737 case GlobalValue::AvailableExternallyLinkage:
738 // An imported available_externally definition converts
739 // to external if imported as a declaration.
740 if (!doImportAsDefinition(SGV))
741 return GlobalValue::ExternalLinkage;
742 // An imported available_externally declaration stays that way.
743 return SGV->getLinkage();
744
745 case GlobalValue::LinkOnceAnyLinkage:
746 case GlobalValue::LinkOnceODRLinkage:
747 // These both stay the same when importing the definition.
748 // The ThinLTO pass will eventually force-import their definitions.
749 return SGV->getLinkage();
750
751 case GlobalValue::WeakAnyLinkage:
752 // Can't import weak_any definitions correctly, or we might change the
753 // program semantics, since the linker will pick the first weak_any
754 // definition and importing would change the order they are seen by the
755 // linker. The module linking caller needs to enforce this.
756 assert(!doImportAsDefinition(SGV));
757 // If imported as a declaration, it becomes external_weak.
758 return GlobalValue::ExternalWeakLinkage;
759
760 case GlobalValue::WeakODRLinkage:
761 // For weak_odr linkage, there is a guarantee that all copies will be
762 // equivalent, so the issue described above for weak_any does not exist,
763 // and the definition can be imported. It can be treated similarly
764 // to an imported externally visible global value.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000765 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000766 return GlobalValue::AvailableExternallyLinkage;
767 else
768 return GlobalValue::ExternalLinkage;
769
770 case GlobalValue::AppendingLinkage:
771 // It would be incorrect to import an appending linkage variable,
772 // since it would cause global constructors/destructors to be
773 // executed multiple times. This should have already been handled
774 // by linkGlobalValueProto.
Davide Italianof3d23292015-11-13 02:16:51 +0000775 llvm_unreachable("Cannot import appending linkage variable");
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000776
777 case GlobalValue::InternalLinkage:
778 case GlobalValue::PrivateLinkage:
779 // If we are promoting the local to global scope, it is handled
780 // similarly to a normal externally visible global.
781 if (doPromoteLocalToGlobal(SGV)) {
Teresa Johnson3cd81612015-11-10 18:20:11 +0000782 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000783 return GlobalValue::AvailableExternallyLinkage;
784 else
785 return GlobalValue::ExternalLinkage;
786 }
787 // A non-promoted imported local definition stays local.
788 // The ThinLTO pass will eventually force-import their definitions.
789 return SGV->getLinkage();
790
791 case GlobalValue::ExternalWeakLinkage:
792 // External weak doesn't apply to definitions, must be a declaration.
793 assert(!doImportAsDefinition(SGV));
794 // Linkage stays external_weak.
795 return SGV->getLinkage();
796
797 case GlobalValue::CommonLinkage:
798 // Linkage stays common on definitions.
799 // The ThinLTO pass will eventually force-import their definitions.
800 return SGV->getLinkage();
801 }
802
803 llvm_unreachable("unknown linkage type");
804}
805
Rafael Espindolaef237112014-12-08 18:45:16 +0000806/// Loop through the global variables in the src module and merge them into the
807/// dest module.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000808GlobalVariable *
809ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
810 const GlobalVariable *SGVar) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000811 // No linking to be performed or linking from the source: simply create an
812 // identical version of the symbol over in the dest module... the
813 // initializer will be filled in later by LinkGlobalInits.
814 GlobalVariable *NewDGV = new GlobalVariable(
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000815 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
816 SGVar->isConstant(), getLinkage(SGVar), /*init*/ nullptr, getName(SGVar),
817 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
Rafael Espindolaef237112014-12-08 18:45:16 +0000818 SGVar->getType()->getAddressSpace());
819
820 return NewDGV;
821}
822
823/// Link the function in the source module into the destination module if
824/// needed, setting up mapping information.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000825Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
826 const Function *SF) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000827 // If there is no linkage to be performed or we are linking from the source,
828 // bring SF over.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000829 return Function::Create(TypeMap.get(SF->getFunctionType()), getLinkage(SF),
830 getName(SF), DstM);
Rafael Espindolaef237112014-12-08 18:45:16 +0000831}
832
833/// Set up prototypes for any aliases that come over from the source module.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000834GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
835 const GlobalAlias *SGA) {
836 // If we are importing and encounter a weak_any alias, or an alias to
837 // an object being imported as a declaration, we must import the alias
838 // as a declaration as well, which involves converting it to a non-alias.
839 // See comments in ModuleLinker::getLinkage for why we cannot import
840 // weak_any defintions.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000841 if (isPerformingImport() && !doImportAsDefinition(SGA)) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000842 // Need to convert to declaration. All aliases must be definitions.
843 const GlobalValue *GVal = SGA->getBaseObject();
844 GlobalValue *NewGV;
845 if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
846 NewGV = copyGlobalVariableProto(TypeMap, GVar);
847 else {
848 auto *F = dyn_cast<Function>(GVal);
849 assert(F);
850 NewGV = copyFunctionProto(TypeMap, F);
851 }
Teresa Johnsonf1b0a6e2015-11-04 16:01:16 +0000852 // Set the linkage to External or ExternalWeak (see comments in
853 // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000854 if (SGA->hasWeakAnyLinkage())
855 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
Teresa Johnsonf1b0a6e2015-11-04 16:01:16 +0000856 else
857 NewGV->setLinkage(GlobalValue::ExternalLinkage);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000858 return NewGV;
859 }
Rafael Espindolaef237112014-12-08 18:45:16 +0000860 // If there is no linkage to be performed or we're linking from the source,
861 // bring over SGA.
David Blaikie6614d8d2015-09-14 20:29:26 +0000862 auto *Ty = TypeMap.get(SGA->getValueType());
863 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000864 getLinkage(SGA), getName(SGA), DstM);
Rafael Espindolaef237112014-12-08 18:45:16 +0000865}
866
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000867void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
868 const GlobalValue *DGV) {
869 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
870 if (DGV)
871 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
872 ? DGV->getVisibility()
873 : Visibility;
874 // For promoted locals, mark them hidden so that they can later be
875 // stripped from the symbol table to reduce bloat.
876 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
877 Visibility = GlobalValue::HiddenVisibility;
878 NewGV->setVisibility(Visibility);
879}
880
881GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
882 const GlobalValue *SGV,
883 const GlobalValue *DGV) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000884 GlobalValue *NewGV;
885 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000886 NewGV = copyGlobalVariableProto(TypeMap, SGVar);
Rafael Espindolaef237112014-12-08 18:45:16 +0000887 else if (auto *SF = dyn_cast<Function>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000888 NewGV = copyFunctionProto(TypeMap, SF);
Rafael Espindolaef237112014-12-08 18:45:16 +0000889 else
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000890 NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
Rafael Espindolaef237112014-12-08 18:45:16 +0000891 copyGVAttributes(NewGV, SGV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000892 setVisibility(NewGV, SGV, DGV);
Rafael Espindolaef237112014-12-08 18:45:16 +0000893 return NewGV;
894}
895
Rafael Espindola19b52382015-11-27 20:28:19 +0000896Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
897 return ModLinker->materializeDeclFor(V);
898}
899
900Value *ModuleLinker::materializeDeclFor(Value *V) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000901 auto *SGV = dyn_cast<GlobalValue>(V);
902 if (!SGV)
Craig Topper2617dcc2014-04-15 06:32:26 +0000903 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000904
Teresa Johnson10632932015-11-06 17:50:53 +0000905 // If we are done linking global value bodies (i.e. we are performing
906 // metadata linking), don't link in the global value due to this
907 // reference, simply map it to null.
Rafael Espindola19b52382015-11-27 20:28:19 +0000908 if (doneLinkingBodies())
Teresa Johnson10632932015-11-06 17:50:53 +0000909 return nullptr;
910
Rafael Espindola19b52382015-11-27 20:28:19 +0000911 GlobalValue *DGV = copyGlobalValueProto(TypeMap, SGV);
James Molloyf6f121e2013-05-28 15:17:05 +0000912
Rafael Espindolaef237112014-12-08 18:45:16 +0000913 if (Comdat *SC = SGV->getComdat()) {
914 if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
915 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
916 DGO->setComdat(DC);
917 }
Rafael Espindola3931c282014-08-15 20:17:08 +0000918 }
919
Rafael Espindolaef237112014-12-08 18:45:16 +0000920 return DGV;
James Molloyf6f121e2013-05-28 15:17:05 +0000921}
922
Rafael Espindola19b52382015-11-27 20:28:19 +0000923void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
924 GlobalValue *Old) {
925 return ModLinker->materializeInitFor(New, Old);
926}
927
928void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
929 if (isPerformingImport() && !doImportAsDefinition(Old))
930 return;
931
932 // Skip declarations that ValueMaterializer may have created in
933 // case we link in only some of SrcM.
934 if (shouldLinkOnlyNeeded() && Old->isDeclaration())
935 return;
936
937 assert(!Old->isDeclaration() && "users should not pass down decls");
938 linkGlobalValueBody(*Old);
939}
940
David Majnemerdad0a642014-06-27 18:19:56 +0000941bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
942 const GlobalVariable *&GVar) {
943 const GlobalValue *GVal = M->getNamedValue(ComdatName);
944 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
945 GVal = GA->getBaseObject();
946 if (!GVal)
947 // We cannot resolve the size of the aliasee yet.
948 return emitError("Linking COMDATs named '" + ComdatName +
949 "': COMDAT key involves incomputable alias size.");
950 }
951
952 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
953 if (!GVar)
954 return emitError(
955 "Linking COMDATs named '" + ComdatName +
956 "': GlobalVariable required for data dependent selection!");
957
958 return false;
959}
960
961bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
962 Comdat::SelectionKind Src,
963 Comdat::SelectionKind Dst,
964 Comdat::SelectionKind &Result,
965 bool &LinkFromSrc) {
966 // The ability to mix Comdat::SelectionKind::Any with
967 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
968 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
969 Dst == Comdat::SelectionKind::Largest;
970 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
971 Src == Comdat::SelectionKind::Largest;
972 if (DstAnyOrLargest && SrcAnyOrLargest) {
973 if (Dst == Comdat::SelectionKind::Largest ||
974 Src == Comdat::SelectionKind::Largest)
975 Result = Comdat::SelectionKind::Largest;
976 else
977 Result = Comdat::SelectionKind::Any;
978 } else if (Src == Dst) {
979 Result = Dst;
980 } else {
981 return emitError("Linking COMDATs named '" + ComdatName +
982 "': invalid selection kinds!");
983 }
984
985 switch (Result) {
986 case Comdat::SelectionKind::Any:
987 // Go with Dst.
988 LinkFromSrc = false;
989 break;
990 case Comdat::SelectionKind::NoDuplicates:
991 return emitError("Linking COMDATs named '" + ComdatName +
992 "': noduplicates has been violated!");
993 case Comdat::SelectionKind::ExactMatch:
994 case Comdat::SelectionKind::Largest:
995 case Comdat::SelectionKind::SameSize: {
996 const GlobalVariable *DstGV;
997 const GlobalVariable *SrcGV;
998 if (getComdatLeader(DstM, ComdatName, DstGV) ||
999 getComdatLeader(SrcM, ComdatName, SrcGV))
1000 return true;
1001
Mehdi Amini46a43552015-03-04 18:43:29 +00001002 const DataLayout &DstDL = DstM->getDataLayout();
1003 const DataLayout &SrcDL = SrcM->getDataLayout();
David Majnemerdad0a642014-06-27 18:19:56 +00001004 uint64_t DstSize =
Mehdi Amini46a43552015-03-04 18:43:29 +00001005 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +00001006 uint64_t SrcSize =
Mehdi Amini46a43552015-03-04 18:43:29 +00001007 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +00001008 if (Result == Comdat::SelectionKind::ExactMatch) {
1009 if (SrcGV->getInitializer() != DstGV->getInitializer())
1010 return emitError("Linking COMDATs named '" + ComdatName +
1011 "': ExactMatch violated!");
1012 LinkFromSrc = false;
1013 } else if (Result == Comdat::SelectionKind::Largest) {
1014 LinkFromSrc = SrcSize > DstSize;
1015 } else if (Result == Comdat::SelectionKind::SameSize) {
1016 if (SrcSize != DstSize)
1017 return emitError("Linking COMDATs named '" + ComdatName +
1018 "': SameSize violated!");
1019 LinkFromSrc = false;
1020 } else {
1021 llvm_unreachable("unknown selection kind");
1022 }
1023 break;
1024 }
1025 }
1026
1027 return false;
1028}
1029
1030bool ModuleLinker::getComdatResult(const Comdat *SrcC,
1031 Comdat::SelectionKind &Result,
1032 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +00001033 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +00001034 StringRef ComdatName = SrcC->getName();
1035 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
1036 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001037
Rafael Espindolab16196a2014-08-11 17:07:34 +00001038 if (DstCI == ComdatSymTab.end()) {
1039 // Use the comdat if it is only available in one of the modules.
1040 LinkFromSrc = true;
1041 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001042 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +00001043 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001044
1045 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001046 Comdat::SelectionKind DSK = DstC->getSelectionKind();
1047 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1048 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +00001049}
James Molloyf6f121e2013-05-28 15:17:05 +00001050
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001051bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1052 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001053 const GlobalValue &Src) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001054 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +00001055 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001056 LinkFromSrc = true;
1057 return false;
1058 }
1059
Rafael Espindola778fcc72014-11-02 13:28:57 +00001060 // We always have to add Src if it has appending linkage.
1061 if (Src.hasAppendingLinkage()) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001062 // Caller should have already determined that we can't link from source
1063 // when importing (see comments in linkGlobalValueProto).
1064 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +00001065 LinkFromSrc = true;
1066 return false;
1067 }
1068
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001069 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1070 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001071
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001072 if (isPerformingImport()) {
1073 if (isa<Function>(&Src)) {
1074 // For functions, LinkFromSrc iff this is the function requested
1075 // for importing. For variables, decide below normally.
1076 LinkFromSrc = (&Src == ImportFunction);
1077 return false;
1078 }
1079
1080 // Check if this is an alias with an already existing definition
1081 // in Dest, which must have come from a prior importing pass from
1082 // the same Src module. Unlike imported function and variable
1083 // definitions, which are imported as available_externally and are
1084 // not definitions for the linker, that is not a valid linkage for
1085 // imported aliases which must be definitions. Simply use the existing
1086 // Dest copy.
1087 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1088 assert(isa<GlobalAlias>(&Dest));
1089 LinkFromSrc = false;
1090 return false;
1091 }
1092 }
1093
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001094 if (SrcIsDeclaration) {
1095 // If Src is external or if both Src & Dest are external.. Just link the
1096 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001097 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001098 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001099 LinkFromSrc = DestIsDeclaration;
1100 return false;
1101 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001102 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001103 LinkFromSrc = Dest.hasExternalWeakLinkage();
1104 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001105 }
1106
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001107 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001108 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001109 LinkFromSrc = true;
1110 return false;
1111 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001112
Rafael Espindola09106052014-09-09 15:59:12 +00001113 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001114 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1115 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +00001116 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001117 }
1118
1119 if (!Dest.hasCommonLinkage()) {
1120 LinkFromSrc = false;
1121 return false;
1122 }
Rafael Espindola09106052014-09-09 15:59:12 +00001123
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001124 const DataLayout &DL = Dest.getParent()->getDataLayout();
Rafael Espindola09106052014-09-09 15:59:12 +00001125 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1126 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001127 LinkFromSrc = SrcSize > DestSize;
1128 return false;
Rafael Espindola09106052014-09-09 15:59:12 +00001129 }
1130
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001131 if (Src.isWeakForLinker()) {
1132 assert(!Dest.hasExternalWeakLinkage());
1133 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +00001134
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001135 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1136 LinkFromSrc = true;
1137 return false;
1138 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001139
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001140 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +00001141 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001142 }
1143
1144 if (Dest.isWeakForLinker()) {
1145 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001146 LinkFromSrc = true;
1147 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001148 }
1149
1150 assert(!Src.hasExternalWeakLinkage());
1151 assert(!Dest.hasExternalWeakLinkage());
1152 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1153 "Unexpected linkage type!");
1154 return emitError("Linking globals named '" + Src.getName() +
1155 "': symbol multiply defined!");
1156}
1157
Rafael Espindola18c89412014-10-27 02:35:46 +00001158/// Loop over all of the linked values to compute type mappings. For example,
1159/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1160/// types 'Foo' but one got renamed when the module was loaded into the same
1161/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001162void ModuleLinker::computeTypeMapping() {
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001163 for (GlobalValue &SGV : SrcM->globals()) {
1164 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1165 if (!DGV)
1166 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001167
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001168 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1169 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001170 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001171 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001172
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001173 // Unify the element type of appending arrays.
1174 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001175 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001176 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +00001177 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001178
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001179 for (GlobalValue &SGV : *SrcM) {
1180 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1181 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001182 }
Bill Wendling7b464612012-02-27 22:34:19 +00001183
Rafael Espindolae96d7eb2014-11-25 04:43:59 +00001184 for (GlobalValue &SGV : SrcM->aliases()) {
1185 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1186 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1187 }
1188
Bill Wendlingd48b7782012-02-28 04:01:21 +00001189 // Incorporate types by name, scanning all the types in the source module.
1190 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001191 // example. When the source module got loaded into the same LLVMContext, if
1192 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001193 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
1194 for (StructType *ST : Types) {
Rafael Espindola4d4c9382014-12-01 19:08:07 +00001195 if (!ST->hasName())
1196 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001197
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001198 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +00001199 size_t DotPos = ST->getName().rfind('.');
1200 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +00001201 ST->getName().back() == '.' ||
Rafael Espindola973b3612014-12-01 19:17:46 +00001202 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +00001203 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001204
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001205 // Check to see if the destination module has a struct with the prefix name.
Rafael Espindola973b3612014-12-01 19:17:46 +00001206 StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
1207 if (!DST)
1208 continue;
1209
1210 // Don't use it if this actually came from the source module. They're in
1211 // the same LLVMContext after all. Also don't use it unless the type is
1212 // actually used in the destination module. This can happen in situations
1213 // like this:
1214 //
1215 // Module A Module B
1216 // -------- --------
1217 // %Z = type { %A } %B = type { %C.1 }
1218 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1219 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1220 // %C = type { i8* } %B.3 = type { %C.1 }
1221 //
1222 // When we link Module B with Module A, the '%B' in Module B is
1223 // used. However, that would then use '%C.1'. But when we process '%C.1',
1224 // we prefer to take the '%C' version. So we are then left with both
1225 // '%C.1' and '%C' being used for the same types. This leads to some
1226 // variables using one type and some using the other.
Rafael Espindola31ad4682014-12-03 22:36:37 +00001227 if (TypeMap.DstStructTypesSet.hasType(DST))
Rafael Espindola973b3612014-12-01 19:17:46 +00001228 TypeMap.addTypeMapping(DST, ST);
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001229 }
1230
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001231 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001232 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001233 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +00001234}
1235
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001236static void upgradeGlobalArray(GlobalVariable *GV) {
1237 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
1238 StructType *OldTy = cast<StructType>(ATy->getElementType());
1239 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
1240
1241 // Get the upgraded 3 element type.
1242 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
1243 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
1244 VoidPtrTy};
1245 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
1246
1247 // Build new constants with a null third field filled in.
1248 Constant *OldInitC = GV->getInitializer();
1249 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
1250 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
1251 // Invalid initializer; give up.
1252 return;
1253 std::vector<Constant *> Initializers;
1254 if (OldInit && OldInit->getNumOperands()) {
1255 Value *Null = Constant::getNullValue(VoidPtrTy);
1256 for (Use &U : OldInit->operands()) {
1257 ConstantStruct *Init = cast<ConstantStruct>(U.get());
1258 Initializers.push_back(ConstantStruct::get(
1259 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
1260 }
1261 }
1262 assert(Initializers.size() == ATy->getNumElements() &&
1263 "Failed to copy all array elements");
1264
1265 // Replace the old GV with a new one.
1266 ATy = ArrayType::get(NewTy, Initializers.size());
1267 Constant *NewInit = ConstantArray::get(ATy, Initializers);
1268 GlobalVariable *NewGV = new GlobalVariable(
1269 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
1270 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
1271 GV->isExternallyInitialized());
1272 NewGV->copyAttributesFrom(GV);
1273 NewGV->takeName(GV);
1274 assert(GV->use_empty() && "program cannot use initializer list");
1275 GV->eraseFromParent();
1276}
1277
1278void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
1279 // Look for the global arrays.
1280 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
1281 if (!DstGV)
1282 return;
1283 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
1284 if (!SrcGV)
1285 return;
1286
1287 // Check if the types already match.
1288 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1289 auto *SrcTy =
1290 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1291 if (DstTy == SrcTy)
1292 return;
1293
1294 // Grab the element types. We can only upgrade an array of a two-field
1295 // struct. Only bother if the other one has three-fields.
1296 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
1297 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
1298 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
1299 upgradeGlobalArray(DstGV);
1300 return;
1301 }
1302 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
1303 upgradeGlobalArray(SrcGV);
1304
1305 // We can't upgrade any other differences.
1306}
1307
1308void ModuleLinker::upgradeMismatchedGlobals() {
1309 upgradeMismatchedGlobalArray("llvm.global_ctors");
1310 upgradeMismatchedGlobalArray("llvm.global_dtors");
1311}
1312
Rafael Espindola18c89412014-10-27 02:35:46 +00001313/// If there were any appending global variables, link them together now.
1314/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001315bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001316 const GlobalVariable *SrcGV) {
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001317
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001318 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1319 return emitError("Linking globals named '" + SrcGV->getName() +
1320 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001321
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001322 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1323 ArrayType *SrcTy =
1324 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1325 Type *EltTy = DstTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001326
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001327 // Check to see that they two arrays agree on type.
1328 if (EltTy != SrcTy->getElementType())
1329 return emitError("Appending variables with different element types!");
1330 if (DstGV->isConstant() != SrcGV->isConstant())
1331 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001332
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001333 if (DstGV->getAlignment() != SrcGV->getAlignment())
1334 return emitError(
1335 "Appending variables with different alignment need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001336
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001337 if (DstGV->getVisibility() != SrcGV->getVisibility())
1338 return emitError(
1339 "Appending variables with different visibility need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +00001340
1341 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1342 return emitError(
1343 "Appending variables with different unnamed_addr need to be linked!");
1344
Rafael Espindola64c1e182014-06-03 02:41:57 +00001345 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001346 return emitError(
1347 "Appending variables with different section name need to be linked!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001348
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001349 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
1350 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001351
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001352 // Create the new global variable.
1353 GlobalVariable *NG =
1354 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
Craig Topper2617dcc2014-04-15 06:32:26 +00001355 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001356 DstGV->getThreadLocalMode(),
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001357 DstGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001358
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001359 // Propagate alignment, visibility and section info.
Bill Wendlingb6af2f32012-03-22 20:28:27 +00001360 copyGVAttributes(NG, DstGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001361
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001362 AppendingVarInfo AVI;
1363 AVI.NewGV = NG;
1364 AVI.DstInit = DstGV->getInitializer();
1365 AVI.SrcInit = SrcGV->getInitializer();
1366 AppendingVars.push_back(AVI);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001367
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001368 // Replace any uses of the two global variables with uses of the new
1369 // global.
1370 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +00001371
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001372 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1373 DstGV->eraseFromParent();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001374
Tanya Lattnercbb91402011-10-11 00:24:54 +00001375 // Track the source variable so we don't try to link it.
1376 DoNotLinkFromSource.insert(SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001377
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001378 return false;
1379}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001380
Rafael Espindola778fcc72014-11-02 13:28:57 +00001381bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001382 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001383
Rafael Espindola778fcc72014-11-02 13:28:57 +00001384 // Handle the ultra special appending linkage case first.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001385 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1386 if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1387 // Don't want to append to global_ctors list, for example, when we
1388 // are importing for ThinLTO, otherwise the global ctors and dtors
1389 // get executed multiple times for local variables (the latter causing
1390 // double frees).
1391 DoNotLinkFromSource.insert(SGV);
1392 return false;
1393 }
Rafael Espindola778fcc72014-11-02 13:28:57 +00001394 if (DGV && DGV->hasAppendingLinkage())
1395 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1396 cast<GlobalVariable>(SGV));
1397
1398 bool LinkFromSrc = true;
1399 Comdat *C = nullptr;
Rafael Espindola778fcc72014-11-02 13:28:57 +00001400 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1401
David Majnemerdad0a642014-06-27 18:19:56 +00001402 if (const Comdat *SC = SGV->getComdat()) {
1403 Comdat::SelectionKind SK;
1404 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola778fcc72014-11-02 13:28:57 +00001405 C = DstM->getOrInsertComdat(SC->getName());
1406 C->setSelectionKind(SK);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +00001407 ComdatMembers[SC].push_back(SGV);
Rafael Espindola778fcc72014-11-02 13:28:57 +00001408 } else if (DGV) {
1409 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1410 return true;
1411 }
1412
1413 if (!LinkFromSrc) {
1414 // Track the source global so that we don't attempt to copy it over when
1415 // processing global initializers.
1416 DoNotLinkFromSource.insert(SGV);
1417
1418 if (DGV)
1419 // Make sure to remember this mapping.
1420 ValueMap[SGV] =
1421 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
David Majnemerdad0a642014-06-27 18:19:56 +00001422 }
1423
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001424 if (DGV)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001425 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001426
Rafael Espindola778fcc72014-11-02 13:28:57 +00001427 if (!LinkFromSrc && !DGV)
1428 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001429
Rafael Espindola778fcc72014-11-02 13:28:57 +00001430 GlobalValue *NewGV;
Rafael Espindola26c29512014-12-05 17:53:15 +00001431 if (!LinkFromSrc) {
1432 NewGV = DGV;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001433 // When linking from source we setVisibility from copyGlobalValueProto.
1434 setVisibility(NewGV, SGV, DGV);
Rafael Espindola26c29512014-12-05 17:53:15 +00001435 } else {
Rafael Espindolaef237112014-12-08 18:45:16 +00001436 // If the GV is to be lazily linked, don't create it just yet.
1437 // The ValueMaterializerTy will deal with creating it if it's used.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001438 if (!DGV && !shouldOverrideFromSrc() && SGV != ImportFunction &&
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001439 (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1440 SGV->hasAvailableExternallyLinkage())) {
Rafael Espindolaef237112014-12-08 18:45:16 +00001441 DoNotLinkFromSource.insert(SGV);
1442 return false;
1443 }
1444
Artem Belevich020d4fb2015-09-01 17:55:55 +00001445 // When we only want to link in unresolved dependencies, blacklist
1446 // the symbol unless unless DestM has a matching declaration (DGV).
1447 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration())) {
1448 DoNotLinkFromSource.insert(SGV);
1449 return false;
1450 }
1451
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001452 NewGV = copyGlobalValueProto(TypeMap, SGV, DGV);
Teresa Johnson3cd81612015-11-10 18:20:11 +00001453
1454 if (isPerformingImport() && !doImportAsDefinition(SGV))
1455 DoNotLinkFromSource.insert(SGV);
Rafael Espindola26c29512014-12-05 17:53:15 +00001456 }
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001457
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001458 NewGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola439835a2014-12-05 00:09:02 +00001459
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001460 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1461 if (C)
1462 NewGO->setComdat(C);
1463
1464 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1465 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1466 }
1467
Rafael Espindola879aeb72014-12-05 16:05:19 +00001468 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1469 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1470 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1471 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1472 (!DGVar->isConstant() || !SGVar->isConstant()))
1473 NewGVar->setConstant(false);
1474 }
1475
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001476 // Make sure to remember this mapping.
1477 if (NewGV != DGV) {
1478 if (DGV) {
1479 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1480 DGV->eraseFromParent();
Chandler Carruthfd38af22014-11-02 09:10:31 +00001481 }
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001482 ValueMap[SGV] = NewGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001483 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001484
Rafael Espindola778fcc72014-11-02 13:28:57 +00001485 return false;
1486}
1487
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001488static void getArrayElements(const Constant *C,
1489 SmallVectorImpl<Constant *> &Dest) {
Chris Lattner67058832012-01-25 06:48:06 +00001490 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1491
1492 for (unsigned i = 0; i != NumElements; ++i)
1493 Dest.push_back(C->getAggregateElement(i));
Chris Lattner00245f42012-01-24 13:41:11 +00001494}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001495
Rafael Espindola9f30fac2015-11-29 03:21:30 +00001496void ModuleLinker::linkAppendingVarInit(AppendingVarInfo &AVI) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001497 // Merge the initializer.
Rafael Espindolad31dc042014-09-05 21:27:52 +00001498 SmallVector<Constant *, 16> DstElements;
1499 getArrayElements(AVI.DstInit, DstElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001500
Rafael Espindolad31dc042014-09-05 21:27:52 +00001501 SmallVector<Constant *, 16> SrcElements;
1502 getArrayElements(AVI.SrcInit, SrcElements);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001503
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001504 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
Rafael Espindolad31dc042014-09-05 21:27:52 +00001505
1506 StringRef Name = AVI.NewGV->getName();
1507 bool IsNewStructor =
1508 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1509 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1510
1511 for (auto *V : SrcElements) {
1512 if (IsNewStructor) {
1513 Constant *Key = V->getAggregateElement(2);
1514 if (DoNotLinkFromSource.count(Key))
1515 continue;
1516 }
1517 DstElements.push_back(
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001518 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Rafael Espindolad31dc042014-09-05 21:27:52 +00001519 }
Rafael Espindola9f30fac2015-11-29 03:21:30 +00001520 if (DstElements.size() != NewType->getNumElements()) {
Rafael Espindolad31dc042014-09-05 21:27:52 +00001521 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
Rafael Espindola9f30fac2015-11-29 03:21:30 +00001522 GlobalVariable *Old = AVI.NewGV;
1523 GlobalVariable *NG = new GlobalVariable(
1524 *DstM, NewType, Old->isConstant(), Old->getLinkage(), /*init*/ nullptr,
1525 /*name*/ "", Old, Old->getThreadLocalMode(),
1526 Old->getType()->getAddressSpace());
1527 copyGVAttributes(NG, Old);
1528 AVI.NewGV->replaceAllUsesWith(
1529 ConstantExpr::getBitCast(NG, AVI.NewGV->getType()));
1530 AVI.NewGV->eraseFromParent();
1531 AVI.NewGV = NG;
Rafael Espindolad31dc042014-09-05 21:27:52 +00001532 }
1533
1534 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001535}
1536
Rafael Espindola18c89412014-10-27 02:35:46 +00001537/// Update the initializers in the Dest module now that all globals that may be
1538/// referenced are in Dest.
Rafael Espindolaef237112014-12-08 18:45:16 +00001539void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1540 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001541 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1542 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001543}
1544
Rafael Espindola18c89412014-10-27 02:35:46 +00001545/// Copy the source function over into the dest function and fix up references
1546/// to values. At this point we know that Dest is an external function, and
1547/// that Src is not.
Rafael Espindolaef237112014-12-08 18:45:16 +00001548bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1549 assert(Dst.isDeclaration() && !Src.isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001550
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001551 // Materialize if needed.
Rafael Espindola3519da82014-12-08 14:25:26 +00001552 if (std::error_code EC = Src.materialize())
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001553 return emitError(EC.message());
1554
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001555 // Link in the prefix data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001556 if (Src.hasPrefixData())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001557 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1558 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001559
1560 // Link in the prologue data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001561 if (Src.hasPrologueData())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001562 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1563 RF_MoveDistinctMDs, &TypeMap,
1564 &ValMaterializer));
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001565
David Majnemer7fddecc2015-06-17 20:52:32 +00001566 // Link in the personality function.
1567 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001568 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1569 RF_MoveDistinctMDs, &TypeMap,
1570 &ValMaterializer));
David Majnemer7fddecc2015-06-17 20:52:32 +00001571
Chris Lattner7391dde2004-11-16 17:12:38 +00001572 // Go through and convert function arguments over, remembering the mapping.
Rafael Espindolaef237112014-12-08 18:45:16 +00001573 Function::arg_iterator DI = Dst.arg_begin();
Rafael Espindola3519da82014-12-08 14:25:26 +00001574 for (Argument &Arg : Src.args()) {
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001575 DI->setName(Arg.getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001576
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001577 // Add a mapping to our mapping.
Duncan P. N. Exon Smith9934b262015-10-19 22:23:36 +00001578 ValueMap[&Arg] = &*DI;
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001579 ++DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001580 }
1581
Duncan P. N. Exon Smithc8d987b2015-04-24 22:07:31 +00001582 // Copy over the metadata attachments.
1583 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1584 Src.getAllMetadata(MDs);
1585 for (const auto &I : MDs)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001586 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1587 &TypeMap, &ValMaterializer));
Duncan P. N. Exon Smithc8d987b2015-04-24 22:07:31 +00001588
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001589 // Splice the body of the source function into the dest function.
Rafael Espindolaef237112014-12-08 18:45:16 +00001590 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001591
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001592 // At this point, all of the instructions and values of the function are now
1593 // copied over. The only problem is that they are still referencing values in
1594 // the Source function as operands. Loop through all of the operands of the
1595 // functions and patch them up to point to the local versions.
Rafael Espindolaef237112014-12-08 18:45:16 +00001596 for (BasicBlock &BB : Dst)
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001597 for (Instruction &I : BB)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001598 RemapInstruction(&I, ValueMap,
1599 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001600 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001601
Chris Lattner7391dde2004-11-16 17:12:38 +00001602 // There is no need to map the arguments anymore.
Rafael Espindola3519da82014-12-08 14:25:26 +00001603 for (Argument &Arg : Src.args())
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001604 ValueMap.erase(&Arg);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001605
Eric Christopher97cb5652015-05-15 18:20:14 +00001606 Src.dematerialize();
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001607 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001608}
1609
Rafael Espindolaef237112014-12-08 18:45:16 +00001610void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1611 Constant *Aliasee = Src.getAliasee();
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001612 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1613 &ValMaterializer);
Rafael Espindolaef237112014-12-08 18:45:16 +00001614 Dst.setAliasee(Val);
1615}
1616
1617bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1618 Value *Dst = ValueMap[&Src];
1619 assert(Dst);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +00001620 if (const Comdat *SC = Src.getComdat()) {
1621 // To ensure that we don't generate an incomplete comdat group,
1622 // we must materialize and map in any other members that are not
1623 // yet materialized in Dst, which also ensures their definitions
1624 // are linked in. Otherwise, linkonce and other lazy linked GVs will
1625 // not be materialized if they aren't referenced.
1626 for (auto *SGV : ComdatMembers[SC]) {
Rafael Espindola19b52382015-11-27 20:28:19 +00001627 auto *DGV = cast_or_null<GlobalValue>(ValueMap[SGV]);
1628 if (DGV && !DGV->isDeclaration())
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +00001629 continue;
Rafael Espindola19b52382015-11-27 20:28:19 +00001630 MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +00001631 }
1632 }
Artem Belevich020d4fb2015-09-01 17:55:55 +00001633 if (shouldInternalizeLinkedSymbols())
1634 if (auto *DGV = dyn_cast<GlobalValue>(Dst))
1635 DGV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaef237112014-12-08 18:45:16 +00001636 if (auto *F = dyn_cast<Function>(&Src))
1637 return linkFunctionBody(cast<Function>(*Dst), *F);
1638 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1639 linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1640 return false;
Tanya Lattnercbb91402011-10-11 00:24:54 +00001641 }
Rafael Espindolaef237112014-12-08 18:45:16 +00001642 linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1643 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001644}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001645
Rafael Espindola18c89412014-10-27 02:35:46 +00001646/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001647void ModuleLinker::linkNamedMDNodes() {
Bill Wendling66f02412012-02-11 11:38:06 +00001648 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001649 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Bill Wendling66f02412012-02-11 11:38:06 +00001650 // Don't link module flags here. Do them separately.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001651 if (&NMD == SrcModFlags)
1652 continue;
1653 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(NMD.getName());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 // Add Src elements into Dest node.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001655 for (const MDNode *op : NMD.operands())
Teresa Johnson83d03dd2015-11-15 14:50:14 +00001656 DestNMD->addOperand(MapMetadata(
1657 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1658 &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001659 }
1660}
Bill Wendling66f02412012-02-11 11:38:06 +00001661
Rafael Espindola18c89412014-10-27 02:35:46 +00001662/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001663bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001664 // If the source module has no module flags, we are done.
Bill Wendling66f02412012-02-11 11:38:06 +00001665 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1666 if (!SrcModFlags) return false;
1667
Bill Wendling66f02412012-02-11 11:38:06 +00001668 // If the destination module doesn't have module flags yet, then just copy
1669 // over the source module's flags.
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001670 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001671 if (DstModFlags->getNumOperands() == 0) {
1672 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1673 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1674
1675 return false;
1676 }
1677
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001678 // First build a map of the existing module flags and requirements.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001679 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001680 SmallSetVector<MDNode*, 16> Requirements;
1681 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001682 MDNode *Op = DstModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001683 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001684 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001685
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001686 if (Behavior->getZExtValue() == Module::Require) {
1687 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1688 } else {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001689 Flags[ID] = std::make_pair(Op, I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001690 }
Bill Wendling66f02412012-02-11 11:38:06 +00001691 }
1692
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001693 // Merge in the flags from the source module, and also collect its set of
1694 // requirements.
1695 bool HasErr = false;
1696 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001697 MDNode *SrcOp = SrcModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001698 ConstantInt *SrcBehavior =
1699 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001700 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001701 MDNode *DstOp;
1702 unsigned DstIndex;
1703 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001704 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001705
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001706 // If this is a requirement, add it and continue.
1707 if (SrcBehaviorValue == Module::Require) {
1708 // If the destination module does not already have this requirement, add
1709 // it.
1710 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1711 DstModFlags->addOperand(SrcOp);
1712 }
1713 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001714 }
1715
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001716 // If there is no existing flag with this ID, just add it.
1717 if (!DstOp) {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001718 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001719 DstModFlags->addOperand(SrcOp);
1720 continue;
1721 }
1722
1723 // Otherwise, perform a merge.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001724 ConstantInt *DstBehavior =
1725 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001726 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1727
1728 // If either flag has override behavior, handle it first.
1729 if (DstBehaviorValue == Module::Override) {
1730 // Diagnose inconsistent flags which both have override behavior.
1731 if (SrcBehaviorValue == Module::Override &&
1732 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1733 HasErr |= emitError("linking module flags '" + ID->getString() +
1734 "': IDs have conflicting override values");
1735 }
1736 continue;
1737 } else if (SrcBehaviorValue == Module::Override) {
1738 // Update the destination flag to that of the source.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001739 DstModFlags->setOperand(DstIndex, SrcOp);
1740 Flags[ID].first = SrcOp;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001741 continue;
1742 }
1743
1744 // Diagnose inconsistent merge behavior types.
1745 if (SrcBehaviorValue != DstBehaviorValue) {
1746 HasErr |= emitError("linking module flags '" + ID->getString() +
1747 "': IDs have conflicting behaviors");
1748 continue;
1749 }
1750
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001751 auto replaceDstValue = [&](MDNode *New) {
1752 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1753 MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
1754 DstModFlags->setOperand(DstIndex, Flag);
1755 Flags[ID].first = Flag;
1756 };
1757
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001758 // Perform the merge for standard behavior types.
1759 switch (SrcBehaviorValue) {
1760 case Module::Require:
Craig Topper2a30d782014-06-18 05:05:13 +00001761 case Module::Override: llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001762 case Module::Error: {
1763 // Emit an error if the values differ.
1764 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1765 HasErr |= emitError("linking module flags '" + ID->getString() +
1766 "': IDs have conflicting values");
1767 }
1768 continue;
1769 }
1770 case Module::Warning: {
1771 // Emit a warning if the values differ.
1772 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001773 emitWarning("linking module flags '" + ID->getString() +
1774 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001775 }
1776 continue;
1777 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001778 case Module::Append: {
1779 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1780 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001781 SmallVector<Metadata *, 8> MDs;
1782 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001783 MDs.append(DstValue->op_begin(), DstValue->op_end());
1784 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001785
1786 replaceDstValue(MDNode::get(DstM->getContext(), MDs));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001787 break;
1788 }
1789 case Module::AppendUnique: {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001790 SmallSetVector<Metadata *, 16> Elts;
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001791 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1792 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001793 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1794 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001795
1796 replaceDstValue(MDNode::get(DstM->getContext(),
1797 makeArrayRef(Elts.begin(), Elts.end())));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001798 break;
1799 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001800 }
Bill Wendling66f02412012-02-11 11:38:06 +00001801 }
1802
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001803 // Check all of the requirements.
1804 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1805 MDNode *Requirement = Requirements[I];
1806 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001807 Metadata *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001808
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001809 MDNode *Op = Flags[Flag].first;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001810 if (!Op || Op->getOperand(2) != ReqValue) {
1811 HasErr |= emitError("linking module flags '" + Flag->getString() +
1812 "': does not have the required value");
1813 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001814 }
1815 }
1816
1817 return HasErr;
1818}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001819
Akira Hatanakac43df512015-02-13 00:40:41 +00001820// This function returns true if the triples match.
1821static bool triplesMatch(const Triple &T0, const Triple &T1) {
1822 // If vendor is apple, ignore the version number.
1823 if (T0.getVendor() == Triple::Apple)
1824 return T0.getArch() == T1.getArch() &&
1825 T0.getSubArch() == T1.getSubArch() &&
1826 T0.getVendor() == T1.getVendor() &&
1827 T0.getOS() == T1.getOS();
1828
1829 return T0 == T1;
1830}
1831
1832// This function returns the merged triple.
1833static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
1834 // If vendor is apple, pick the triple with the larger version number.
1835 if (SrcTriple.getVendor() == Triple::Apple)
1836 if (DstTriple.isOSVersionLT(SrcTriple))
1837 return SrcTriple.str();
1838
1839 return DstTriple.str();
1840}
1841
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001842bool ModuleLinker::run() {
Bill Wendling66f02412012-02-11 11:38:06 +00001843 assert(DstM && "Null destination module");
1844 assert(SrcM && "Null source module");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001845
1846 // Inherit the target data from the source module if the destination module
1847 // doesn't have one already.
Mehdi Amini46a43552015-03-04 18:43:29 +00001848 if (DstM->getDataLayout().isDefault())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001849 DstM->setDataLayout(SrcM->getDataLayout());
1850
Mehdi Amini46a43552015-03-04 18:43:29 +00001851 if (SrcM->getDataLayout() != DstM->getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001852 emitWarning("Linking two modules of different data layouts: '" +
1853 SrcM->getModuleIdentifier() + "' is '" +
1854 SrcM->getDataLayoutStr() + "' whereas '" +
1855 DstM->getModuleIdentifier() + "' is '" +
1856 DstM->getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001857 }
Akira Hatanakac43df512015-02-13 00:40:41 +00001858
1859 // Copy the target triple from the source to dest if the dest's is empty.
1860 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1861 DstM->setTargetTriple(SrcM->getTargetTriple());
1862
1863 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
1864
1865 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001866 emitWarning("Linking two modules of different target triples: " +
1867 SrcM->getModuleIdentifier() + "' is '" +
1868 SrcM->getTargetTriple() + "' whereas '" +
1869 DstM->getModuleIdentifier() + "' is '" +
1870 DstM->getTargetTriple() + "'\n");
Akira Hatanakac43df512015-02-13 00:40:41 +00001871
1872 DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001873
1874 // Append the module inline asm string.
1875 if (!SrcM->getModuleInlineAsm().empty()) {
1876 if (DstM->getModuleInlineAsm().empty())
1877 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1878 else
1879 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1880 SrcM->getModuleInlineAsm());
1881 }
1882
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001883 // Loop over all of the linked values to compute type mappings.
1884 computeTypeMapping();
1885
David Majnemerdad0a642014-06-27 18:19:56 +00001886 ComdatsChosen.clear();
David Blaikie5106ce72014-11-19 05:49:42 +00001887 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +00001888 const Comdat &C = SMEC.getValue();
1889 if (ComdatsChosen.count(&C))
1890 continue;
1891 Comdat::SelectionKind SK;
1892 bool LinkFromSrc;
1893 if (getComdatResult(&C, SK, LinkFromSrc))
1894 return true;
1895 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1896 }
1897
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001898 // Upgrade mismatched global arrays.
1899 upgradeMismatchedGlobals();
1900
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001901 // Insert all of the globals in src into the DstM module... without linking
1902 // initializers (which could refer to functions not yet mapped over).
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001903 for (GlobalVariable &GV : SrcM->globals())
1904 if (linkGlobalValueProto(&GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001905 return true;
1906
1907 // Link the functions together between the two modules, without doing function
1908 // bodies... this just adds external function prototypes to the DstM
1909 // function... We do this so that when we begin processing function bodies,
1910 // all of the global values that may be referenced are available in our
1911 // ValueMap.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001912 for (Function &F :*SrcM)
1913 if (linkGlobalValueProto(&F))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001914 return true;
1915
1916 // If there were any aliases, link them now.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001917 for (GlobalAlias &GA : SrcM->aliases())
1918 if (linkGlobalValueProto(&GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001919 return true;
1920
Rafael Espindola9f30fac2015-11-29 03:21:30 +00001921 for (AppendingVarInfo &AppendingVar : AppendingVars)
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001922 linkAppendingVarInit(AppendingVar);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001923
Rafael Espindolabeadd562014-12-08 18:05:48 +00001924 for (const auto &Entry : DstM->getComdatSymbolTable()) {
1925 const Comdat &C = Entry.getValue();
1926 if (C.getSelectionKind() == Comdat::Any)
1927 continue;
1928 const GlobalValue *GV = SrcM->getNamedValue(C.getName());
Peter Collingbourneea45d832015-06-22 21:46:51 +00001929 if (GV)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001930 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
Rafael Espindolabeadd562014-12-08 18:05:48 +00001931 }
1932
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001933 // Link in the function bodies that are defined in the source module into
1934 // DstM.
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001935 for (Function &SF : *SrcM) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001936 // Skip if no body (function is external).
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001937 if (SF.isDeclaration())
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001938 continue;
1939
Rafael Espindolaf97d0cb2014-12-08 13:35:09 +00001940 // Skip if not linking from source.
1941 if (DoNotLinkFromSource.count(&SF))
1942 continue;
1943
Rafael Espindolaef237112014-12-08 18:45:16 +00001944 if (linkGlobalValueBody(SF))
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001945 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001946 }
1947
1948 // Resolve all uses of aliases with aliasees.
Rafael Espindolaef237112014-12-08 18:45:16 +00001949 for (GlobalAlias &Src : SrcM->aliases()) {
1950 if (DoNotLinkFromSource.count(&Src))
1951 continue;
1952 linkGlobalValueBody(Src);
1953 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001954
Bill Wendling91686d62014-01-16 06:29:36 +00001955 // Update the initializers in the DstM module now that all globals that may
1956 // be referenced are in DstM.
Rafael Espindolaef237112014-12-08 18:45:16 +00001957 for (GlobalVariable &Src : SrcM->globals()) {
1958 // Only process initialized GV's or ones not already in dest.
1959 if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1960 continue;
1961 linkGlobalValueBody(Src);
1962 }
Bill Wendling91686d62014-01-16 06:29:36 +00001963
Teresa Johnson10632932015-11-06 17:50:53 +00001964 // Note that we are done linking global value bodies. This prevents
1965 // metadata linking from creating new references.
1966 DoneLinkingBodies = true;
1967
Teresa Johnson189b2522015-11-06 17:50:48 +00001968 // Remap all of the named MDNodes in Src into the DstM module. We do this
1969 // after linking GlobalValues so that MDNodes that reference GlobalValues
1970 // are properly remapped.
1971 linkNamedMDNodes();
1972
1973 // Merge the module flags into the DstM module.
1974 if (linkModuleFlagsMetadata())
1975 return true;
1976
Anton Korobeynikov26098882008-03-05 23:21:39 +00001977 return false;
1978}
Reid Spencer361e5132004-11-12 20:37:43 +00001979
Rafael Espindola31ad4682014-12-03 22:36:37 +00001980Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1981 : ETypes(E), IsPacked(P) {}
1982
1983Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1984 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1985
1986bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1987 if (IsPacked != That.IsPacked)
1988 return false;
1989 if (ETypes != That.ETypes)
1990 return false;
1991 return true;
1992}
1993
1994bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1995 return !this->operator==(That);
1996}
1997
1998StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1999 return DenseMapInfo<StructType *>::getEmptyKey();
2000}
2001
2002StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
2003 return DenseMapInfo<StructType *>::getTombstoneKey();
2004}
2005
2006unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
2007 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
2008 Key.IsPacked);
2009}
2010
2011unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
2012 return getHashValue(KeyTy(ST));
2013}
2014
2015bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
2016 const StructType *RHS) {
2017 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
2018 return false;
2019 return LHS == KeyTy(RHS);
2020}
2021
2022bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
2023 const StructType *RHS) {
2024 if (RHS == getEmptyKey())
2025 return LHS == getEmptyKey();
2026
2027 if (RHS == getTombstoneKey())
2028 return LHS == getTombstoneKey();
2029
2030 return KeyTy(LHS) == KeyTy(RHS);
2031}
2032
2033void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
2034 assert(!Ty->isOpaque());
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00002035 NonOpaqueStructTypes.insert(Ty);
Rafael Espindola31ad4682014-12-03 22:36:37 +00002036}
2037
Rafael Espindolaa5b9e1c2015-03-06 00:50:21 +00002038void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
2039 assert(!Ty->isOpaque());
2040 NonOpaqueStructTypes.insert(Ty);
2041 bool Removed = OpaqueStructTypes.erase(Ty);
2042 (void)Removed;
2043 assert(Removed);
2044}
2045
Rafael Espindola31ad4682014-12-03 22:36:37 +00002046void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
2047 assert(Ty->isOpaque());
2048 OpaqueStructTypes.insert(Ty);
2049}
2050
2051StructType *
2052Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
2053 bool IsPacked) {
2054 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
2055 auto I = NonOpaqueStructTypes.find_as(Key);
2056 if (I == NonOpaqueStructTypes.end())
2057 return nullptr;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00002058 return *I;
Rafael Espindola31ad4682014-12-03 22:36:37 +00002059}
2060
2061bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
2062 if (Ty->isOpaque())
2063 return OpaqueStructTypes.count(Ty);
2064 auto I = NonOpaqueStructTypes.find(Ty);
2065 if (I == NonOpaqueStructTypes.end())
2066 return false;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00002067 return *I == Ty;
Rafael Espindola31ad4682014-12-03 22:36:37 +00002068}
2069
Rafael Espindola5cb9c822014-11-17 20:51:01 +00002070void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
2071 this->Composite = M;
2072 this->DiagnosticHandler = DiagnosticHandler;
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00002073
2074 TypeFinder StructTypes;
2075 StructTypes.run(*M, true);
Rafael Espindola31ad4682014-12-03 22:36:37 +00002076 for (StructType *Ty : StructTypes) {
2077 if (Ty->isOpaque())
2078 IdentifiedStructTypes.addOpaque(Ty);
2079 else
2080 IdentifiedStructTypes.addNonOpaque(Ty);
2081 }
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00002082}
Rafael Espindola3df61b72013-05-04 03:48:37 +00002083
Rafael Espindola5cb9c822014-11-17 20:51:01 +00002084Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
2085 init(M, DiagnosticHandler);
2086}
2087
2088Linker::Linker(Module *M) {
2089 init(M, [this](const DiagnosticInfo &DI) {
2090 Composite->getContext().diagnose(DI);
2091 });
2092}
2093
Bill Wendling91e6f6e2013-10-16 08:59:57 +00002094void Linker::deleteModule() {
2095 delete Composite;
Craig Topper2617dcc2014-04-15 06:32:26 +00002096 Composite = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +00002097}
2098
Mehdi Amini8220e8a2015-11-23 01:59:16 +00002099bool Linker::linkInModule(Module *Src, unsigned Flags,
2100 const FunctionInfoIndex *Index,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00002101 Function *FuncToImport) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00002102 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00002103 DiagnosticHandler, Flags, Index, FuncToImport);
Manman Rendab999d2015-01-20 19:24:59 +00002104 bool RetCode = TheLinker.run();
2105 Composite->dropTriviallyDeadConstantArrays();
2106 return RetCode;
Rafael Espindola3df61b72013-05-04 03:48:37 +00002107}
2108
Manman Ren6487ce92015-02-24 00:45:56 +00002109void Linker::setModule(Module *Dst) {
2110 init(Dst, DiagnosticHandler);
2111}
2112
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002113//===----------------------------------------------------------------------===//
2114// LinkModules entrypoint.
2115//===----------------------------------------------------------------------===//
2116
Rafael Espindola18c89412014-10-27 02:35:46 +00002117/// This function links two modules together, with the resulting Dest module
2118/// modified to be the composite of the two input modules. If an error occurs,
2119/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
2120/// Upon failure, the Dest module could be in a modified state, and shouldn't be
2121/// relied on to be consistent.
Rafael Espindola9f8eff32014-10-28 00:24:16 +00002122bool Linker::LinkModules(Module *Dest, Module *Src,
Artem Belevich020d4fb2015-09-01 17:55:55 +00002123 DiagnosticHandlerFunction DiagnosticHandler,
2124 unsigned Flags) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002125 Linker L(Dest, DiagnosticHandler);
Artem Belevich020d4fb2015-09-01 17:55:55 +00002126 return L.linkInModule(Src, Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002127}
2128
Artem Belevich020d4fb2015-09-01 17:55:55 +00002129bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Flags) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00002130 Linker L(Dest);
Artem Belevich020d4fb2015-09-01 17:55:55 +00002131 return L.linkInModule(Src, Flags);
Reid Spencer361e5132004-11-12 20:37:43 +00002132}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00002133
2134//===----------------------------------------------------------------------===//
2135// C API.
2136//===----------------------------------------------------------------------===//
2137
2138LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Juergen Ributzkaa57d5882015-03-02 18:59:38 +00002139 LLVMLinkerMode Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002140 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002141 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002142 raw_string_ostream Stream(Message);
2143 DiagnosticPrinterRawOStream DP(Stream);
2144
2145 LLVMBool Result = Linker::LinkModules(
Rafael Espindola9f8eff32014-10-28 00:24:16 +00002146 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002147
Eli Benderskyff715e22015-06-12 23:26:42 +00002148 if (OutMessages && Result) {
2149 Stream.flush();
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002150 *OutMessages = strdup(Message.c_str());
Eli Benderskyff715e22015-06-12 23:26:42 +00002151 }
Bill Wendlinga3aeb982012-05-09 08:55:40 +00002152 return Result;
2153}