blob: 1a82bbc7c90e7462180ece687b027bf250b643ce [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"
Bill Wendling66f02412012-02-11 11:38:06 +000016#include "llvm/ADT/SetVector.h"
Eli Bendersky0f7fd362013-03-19 15:26:24 +000017#include "llvm/ADT/SmallString.h"
Akira Hatanakac43df512015-02-13 00:40:41 +000018#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000020#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
Chandler Carruthdcb603f2013-01-07 15:43:51 +000024#include "llvm/IR/TypeFinder.h"
Tanya Lattnercbb91402011-10-11 00:24:54 +000025#include "llvm/Transforms/Utils/Cloning.h"
Reid Spencer361e5132004-11-12 20:37:43 +000026using namespace llvm;
27
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000028//===----------------------------------------------------------------------===//
29// TypeMap implementation.
30//===----------------------------------------------------------------------===//
Reid Spencer361e5132004-11-12 20:37:43 +000031
Chris Lattnereee6f992008-06-16 21:00:18 +000032namespace {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000033class TypeMapTy : public ValueMapTypeRemapper {
Rafael Espindola18c89412014-10-27 02:35:46 +000034 /// This is a mapping from a source type to a destination type to use.
Rafael Espindolae3a933a2015-12-01 20:11:43 +000035 DenseMap<Type *, Type *> MappedTypes;
Mikhail Glushenkov766d4892009-03-03 07:22:23 +000036
Rafael Espindola18c89412014-10-27 02:35:46 +000037 /// When checking to see if two subgraphs are isomorphic, we speculatively
38 /// add types to MappedTypes, but keep track of them here in case we need to
39 /// roll back.
Rafael Espindolae3a933a2015-12-01 20:11:43 +000040 SmallVector<Type *, 16> SpeculativeTypes;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000041
Rafael Espindolae3a933a2015-12-01 20:11:43 +000042 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
Rafael Espindolaa96f2352014-11-28 16:41:24 +000043
Rafael Espindola18c89412014-10-27 02:35:46 +000044 /// This is a list of non-opaque structs in the source module that are mapped
45 /// to an opaque struct in the destination module.
Rafael Espindolae3a933a2015-12-01 20:11:43 +000046 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000047
Rafael Espindola18c89412014-10-27 02:35:46 +000048 /// This is the set of opaque types in the destination modules who are
49 /// getting a body from the source module.
Rafael Espindolae3a933a2015-12-01 20:11:43 +000050 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
Bill Wendling8c2cc412012-03-22 20:30:41 +000051
Chris Lattner56cdea62008-06-16 23:06:51 +000052public:
Rafael Espindola31ad4682014-12-03 22:36:37 +000053 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
54 : DstStructTypesSet(DstStructTypesSet) {}
Rafael Espindolaaa9918a2013-05-04 05:05:18 +000055
Rafael Espindola31ad4682014-12-03 22:36:37 +000056 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
Rafael Espindola18c89412014-10-27 02:35:46 +000057 /// Indicate that the specified type in the destination module is conceptually
58 /// equivalent to the specified type in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000059 void addTypeMapping(Type *DstTy, Type *SrcTy);
60
Rafael Espindolad2a13a22014-11-25 04:28:31 +000061 /// Produce a body for an opaque type in the dest module from a type
62 /// definition in the source module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000063 void linkDefinedTypeBodies();
Rafael Espindolaed6dc372014-05-09 14:39:25 +000064
Rafael Espindola18c89412014-10-27 02:35:46 +000065 /// Return the mapped type to use for the specified input type from the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000066 /// source module.
67 Type *get(Type *SrcTy);
Rafael Espindola31ad4682014-12-03 22:36:37 +000068 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
69
70 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000071
Rafael Espindola290e2cc2014-11-25 14:35:53 +000072 FunctionType *get(FunctionType *T) {
73 return cast<FunctionType>(get((Type *)T));
74 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000075
Rafael Espindola18c89412014-10-27 02:35:46 +000076 /// Dump out the type map for debugging purposes.
Bill Wendlingb6af2f32012-03-22 20:28:27 +000077 void dump() const {
Rafael Espindola8f144712014-11-25 06:16:27 +000078 for (auto &Pair : MappedTypes) {
Bill Wendlingb6af2f32012-03-22 20:28:27 +000079 dbgs() << "TypeMap: ";
Rafael Espindola8f144712014-11-25 06:16:27 +000080 Pair.first->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000081 dbgs() << " => ";
Rafael Espindola8f144712014-11-25 06:16:27 +000082 Pair.second->print(dbgs());
Bill Wendlingb6af2f32012-03-22 20:28:27 +000083 dbgs() << '\n';
84 }
85 }
Bill Wendlingb6af2f32012-03-22 20:28:27 +000086
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000087private:
Rafael Espindola290e2cc2014-11-25 14:35:53 +000088 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000089
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000090 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
Chris Lattnereee6f992008-06-16 21:00:18 +000091};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000092}
Chris Lattnereee6f992008-06-16 21:00:18 +000093
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000094void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
Rafael Espindola3d097412014-11-28 16:26:14 +000095 assert(SpeculativeTypes.empty());
Rafael Espindolaa96f2352014-11-28 16:41:24 +000096 assert(SpeculativeDstOpaqueTypes.empty());
Rafael Espindola3d097412014-11-28 16:26:14 +000097
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000098 // Check to see if these types are recursively isomorphic and establish a
99 // mapping between them if so.
Duncan P. N. Exon Smithc586eaa2014-11-27 17:01:10 +0000100 if (!areTypesIsomorphic(DstTy, SrcTy)) {
101 // Oops, they aren't isomorphic. Just discard this request by rolling out
102 // any speculative mappings we've established.
Rafael Espindola3d097412014-11-28 16:26:14 +0000103 for (Type *Ty : SpeculativeTypes)
104 MappedTypes.erase(Ty);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000105
106 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
107 SpeculativeDstOpaqueTypes.size());
108 for (StructType *Ty : SpeculativeDstOpaqueTypes)
109 DstResolvedOpaqueTypes.erase(Ty);
Rafael Espindola04a74af2014-12-01 04:15:59 +0000110 } else {
111 for (Type *Ty : SpeculativeTypes)
112 if (auto *STy = dyn_cast<StructType>(Ty))
113 if (STy->hasName())
114 STy->setName("");
Bill Wendlingd48b7782012-02-28 04:01:21 +0000115 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000116 SpeculativeTypes.clear();
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000117 SpeculativeDstOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000118}
Chris Lattnereee6f992008-06-16 21:00:18 +0000119
Rafael Espindola18c89412014-10-27 02:35:46 +0000120/// Recursively walk this pair of types, returning true if they are isomorphic,
121/// false if they are not.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000122bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
123 // Two types with differing kinds are clearly not isomorphic.
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000124 if (DstTy->getTypeID() != SrcTy->getTypeID())
125 return false;
Misha Brukman10468d82005-04-21 22:55:34 +0000126
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000127 // If we have an entry in the MappedTypes table, then we have our answer.
128 Type *&Entry = MappedTypes[SrcTy];
129 if (Entry)
130 return Entry == DstTy;
Misha Brukman10468d82005-04-21 22:55:34 +0000131
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000132 // Two identical types are clearly isomorphic. Remember this
133 // non-speculatively.
134 if (DstTy == SrcTy) {
135 Entry = DstTy;
Chris Lattnerfe677e92008-06-16 20:03:01 +0000136 return true;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000137 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000138
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000139 // Okay, we have two types with identical kinds that we haven't seen before.
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000140
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000141 // If this is an opaque struct type, special case it.
142 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
143 // Mapping an opaque type to any struct, just keep the dest struct.
144 if (SSTy->isOpaque()) {
145 Entry = DstTy;
146 SpeculativeTypes.push_back(SrcTy);
Reid Spencer361e5132004-11-12 20:37:43 +0000147 return true;
Chris Lattner9be15892008-06-16 21:17:12 +0000148 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000149
Chris Lattner5e3bd972011-12-20 00:03:52 +0000150 // Mapping a non-opaque source type to an opaque dest. If this is the first
151 // type that we're mapping onto this destination type then we succeed. Keep
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000152 // the dest, but fill it in later. If this is the second (different) type
153 // that we're trying to map onto the same opaque type then we fail.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000154 if (cast<StructType>(DstTy)->isOpaque()) {
Chris Lattner5e3bd972011-12-20 00:03:52 +0000155 // We can only map one source type onto the opaque destination type.
David Blaikie70573dc2014-11-19 07:49:26 +0000156 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
Chris Lattner5e3bd972011-12-20 00:03:52 +0000157 return false;
158 SrcDefinitionsToResolve.push_back(SSTy);
Rafael Espindolaa96f2352014-11-28 16:41:24 +0000159 SpeculativeTypes.push_back(SrcTy);
160 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000161 Entry = DstTy;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000162 return true;
163 }
164 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000165
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000166 // If the number of subtypes disagree between the two types, then we fail.
167 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
Reid Spencer361e5132004-11-12 20:37:43 +0000168 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000169
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000170 // Fail if any of the extra properties (e.g. array size) of the type disagree.
171 if (isa<IntegerType>(DstTy))
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000172 return false; // bitwidth disagrees.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000173 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
175 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000176
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000177 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
179 return false;
180 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181 StructType *SSTy = cast<StructType>(SrcTy);
Chris Lattner44f7ab42011-08-12 18:07:26 +0000182 if (DSTy->isLiteral() != SSTy->isLiteral() ||
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000183 DSTy->isPacked() != SSTy->isPacked())
184 return false;
185 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
187 return false;
188 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
Joey Gouly5fad3e92013-01-10 10:49:36 +0000189 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000190 return false;
Reid Spencer361e5132004-11-12 20:37:43 +0000191 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000192
193 // Otherwise, we speculate that these two types will line up and recursively
194 // check the subelements.
195 Entry = DstTy;
196 SpeculativeTypes.push_back(SrcTy);
197
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000198 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
199 if (!areTypesIsomorphic(DstTy->getContainedType(I),
200 SrcTy->getContainedType(I)))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000201 return false;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000202
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000203 // If everything seems to have lined up, then everything is great.
204 return true;
205}
206
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000207void TypeMapTy::linkDefinedTypeBodies() {
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000208 SmallVector<Type *, 16> Elements;
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000209 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000210 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000211 assert(DstSTy->isOpaque());
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000212
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000213 // Map the body of the source type over to a new body for the dest type.
214 Elements.resize(SrcSTy->getNumElements());
Rafael Espindola290e2cc2014-11-25 14:35:53 +0000215 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000216 Elements[I] = get(SrcSTy->getElementType(I));
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000217
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000218 DstSTy->setBody(Elements, SrcSTy->isPacked());
Rafael Espindolaa5b9e1c2015-03-06 00:50:21 +0000219 DstStructTypesSet.switchToNonOpaque(DstSTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000220 }
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000221 SrcDefinitionsToResolve.clear();
Chris Lattner5e3bd972011-12-20 00:03:52 +0000222 DstResolvedOpaqueTypes.clear();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000223}
224
Rafael Espindola31ad4682014-12-03 22:36:37 +0000225void TypeMapTy::finishType(StructType *DTy, StructType *STy,
226 ArrayRef<Type *> ETypes) {
227 DTy->setBody(ETypes, STy->isPacked());
Rafael Espindolac81c3f52014-11-25 15:33:40 +0000228
229 // Steal STy's name.
230 if (STy->hasName()) {
231 SmallString<16> TmpName = STy->getName();
232 STy->setName("");
233 DTy->setName(TmpName);
234 }
235
Rafael Espindola31ad4682014-12-03 22:36:37 +0000236 DstStructTypesSet.addNonOpaque(DTy);
237}
238
239Type *TypeMapTy::get(Type *Ty) {
240 SmallPtrSet<StructType *, 8> Visited;
241 return get(Ty, Visited);
242}
243
244Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
245 // If we already have an entry for this type, return it.
246 Type **Entry = &MappedTypes[Ty];
247 if (*Entry)
248 return *Entry;
249
250 // These are types that LLVM itself will unique.
251 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
252
253#ifndef NDEBUG
254 if (!IsUniqued) {
255 for (auto &Pair : MappedTypes) {
256 assert(!(Pair.first != Ty && Pair.second == Ty) &&
257 "mapping to a source type");
258 }
259 }
260#endif
261
262 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
263 StructType *DTy = StructType::create(Ty->getContext());
264 return *Entry = DTy;
265 }
266
267 // If this is not a recursive type, then just map all of the elements and
268 // then rebuild the type from inside out.
269 SmallVector<Type *, 4> ElementTypes;
270
271 // If there are no element types to map, then the type is itself. This is
272 // true for the anonymous {} struct, things like 'float', integers, etc.
273 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
274 return *Entry = Ty;
275
276 // Remap all of the elements, keeping track of whether any of them change.
277 bool AnyChange = false;
278 ElementTypes.resize(Ty->getNumContainedTypes());
279 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
280 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
281 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
282 }
283
284 // If we found our type while recursively processing stuff, just use it.
285 Entry = &MappedTypes[Ty];
286 if (*Entry) {
287 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
288 if (DTy->isOpaque()) {
289 auto *STy = cast<StructType>(Ty);
290 finishType(DTy, STy, ElementTypes);
291 }
292 }
293 return *Entry;
294 }
295
296 // If all of the element types mapped directly over and the type is not
297 // a nomed struct, then the type is usable as-is.
298 if (!AnyChange && IsUniqued)
299 return *Entry = Ty;
300
301 // Otherwise, rebuild a modified type.
302 switch (Ty->getTypeID()) {
303 default:
304 llvm_unreachable("unknown derived type to remap");
305 case Type::ArrayTyID:
306 return *Entry = ArrayType::get(ElementTypes[0],
307 cast<ArrayType>(Ty)->getNumElements());
308 case Type::VectorTyID:
309 return *Entry = VectorType::get(ElementTypes[0],
310 cast<VectorType>(Ty)->getNumElements());
311 case Type::PointerTyID:
312 return *Entry = PointerType::get(ElementTypes[0],
313 cast<PointerType>(Ty)->getAddressSpace());
314 case Type::FunctionTyID:
315 return *Entry = FunctionType::get(ElementTypes[0],
316 makeArrayRef(ElementTypes).slice(1),
317 cast<FunctionType>(Ty)->isVarArg());
318 case Type::StructTyID: {
319 auto *STy = cast<StructType>(Ty);
320 bool IsPacked = STy->isPacked();
321 if (IsUniqued)
322 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
323
324 // If the type is opaque, we can just use it directly.
325 if (STy->isOpaque()) {
326 DstStructTypesSet.addOpaque(STy);
327 return *Entry = Ty;
328 }
329
330 if (StructType *OldT =
331 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
332 STy->setName("");
333 return *Entry = OldT;
334 }
335
336 if (!AnyChange) {
337 DstStructTypesSet.addNonOpaque(STy);
338 return *Entry = Ty;
339 }
340
341 StructType *DTy = StructType::create(Ty->getContext());
342 finishType(DTy, STy, ElementTypes);
343 return *Entry = DTy;
344 }
345 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000346}
347
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000348//===----------------------------------------------------------------------===//
349// ModuleLinker implementation.
350//===----------------------------------------------------------------------===//
351
352namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +0000353class ModuleLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000354
Rafael Espindolac84f6082014-11-25 06:11:24 +0000355/// Creates prototypes for functions that are lazily linked on the fly. This
356/// speeds up linking for modules with many/ lazily linked functions of which
357/// few get used.
David Blaikie437aafd2015-10-19 22:15:55 +0000358class ValueMaterializerTy final : public ValueMaterializer {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000359 ModuleLinker *ModLinker;
James Molloyf6f121e2013-05-28 15:17:05 +0000360
Rafael Espindolac84f6082014-11-25 06:11:24 +0000361public:
Rafael Espindola19b52382015-11-27 20:28:19 +0000362 ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
Rafael Espindolac84f6082014-11-25 06:11:24 +0000363
Rafael Espindola19b52382015-11-27 20:28:19 +0000364 Value *materializeDeclFor(Value *V) override;
365 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
Rafael Espindolac84f6082014-11-25 06:11:24 +0000366};
367
368class LinkDiagnosticInfo : public DiagnosticInfo {
369 const Twine &Msg;
370
371public:
372 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
373 void print(DiagnosticPrinter &DP) const override;
374};
375LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
376 const Twine &Msg)
377 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
378void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
379
380/// This is an implementation class for the LinkModules function, which is the
381/// entrypoint for this file.
382class ModuleLinker {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000383 Module &DstM;
384 Module &SrcM;
Rafael Espindolac84f6082014-11-25 06:11:24 +0000385
386 TypeMapTy TypeMap;
387 ValueMaterializerTy ValMaterializer;
388
389 /// Mapping of values from what they used to be in Src, to what they are now
390 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
391 /// due to the use of Value handles which the Linker doesn't actually need,
392 /// but this allows us to reuse the ValueMapper code.
393 ValueToValueMapTy ValueMap;
394
Rafael Espindolac84f6082014-11-25 06:11:24 +0000395 // Set of items not to link in from source.
Rafael Espindolac98b20b2015-11-30 18:54:24 +0000396 SmallPtrSet<const GlobalValue *, 16> DoNotLinkFromSource;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000397
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000398 DiagnosticHandlerFunction DiagnosticHandler;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000399
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000400 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +0000401 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000402
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000403 /// Function index passed into ModuleLinker for using in function
404 /// importing/exporting handling.
Mehdi Amini8220e8a2015-11-23 01:59:16 +0000405 const FunctionInfoIndex *ImportIndex;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000406
407 /// Function to import from source module, all other functions are
408 /// imported as declarations instead of definitions.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000409 DenseSet<const GlobalValue *> *ImportFunction;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000410
411 /// Set to true if the given FunctionInfoIndex contains any functions
412 /// from this source module, in which case we must conservatively assume
413 /// that any of its functions may be imported into another module
414 /// as part of a different backend compilation process.
Rafael Espindolaaf714762015-12-01 23:06:26 +0000415 bool HasExportedFunctions = false;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000416
Teresa Johnson10632932015-11-06 17:50:53 +0000417 /// Set to true when all global value body linking is complete (including
418 /// lazy linking). Used to prevent metadata linking from creating new
419 /// references.
Rafael Espindolaaf714762015-12-01 23:06:26 +0000420 bool DoneLinkingBodies = false;
Teresa Johnson10632932015-11-06 17:50:53 +0000421
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000422 bool HasError = false;
423
Rafael Espindolac84f6082014-11-25 06:11:24 +0000424public:
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000425 ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000426 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
Mehdi Amini8220e8a2015-11-23 01:59:16 +0000427 const FunctionInfoIndex *Index = nullptr,
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000428 DenseSet<const GlobalValue *> *FuncToImport = nullptr)
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000429 : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000430 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
Rafael Espindolaaf714762015-12-01 23:06:26 +0000431 ImportFunction(FuncToImport) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000432 assert((ImportIndex || !ImportFunction) &&
433 "Expect a FunctionInfoIndex when importing");
434 // If we have a FunctionInfoIndex but no function to import,
435 // then this is the primary module being compiled in a ThinLTO
436 // backend compilation, and we need to see if it has functions that
437 // may be exported to another backend compilation.
438 if (ImportIndex && !ImportFunction)
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000439 HasExportedFunctions = ImportIndex->hasExportedFunctions(&SrcM);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000440 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000441
Rafael Espindolac84f6082014-11-25 06:11:24 +0000442 bool run();
Rafael Espindola19b52382015-11-27 20:28:19 +0000443 Value *materializeDeclFor(Value *V);
444 void materializeInitFor(GlobalValue *New, GlobalValue *Old);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000445
Rafael Espindola19b52382015-11-27 20:28:19 +0000446private:
Artem Belevich020d4fb2015-09-01 17:55:55 +0000447 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
448 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
449 bool shouldInternalizeLinkedSymbols() {
450 return Flags & Linker::InternalizeLinkedSymbols;
451 }
452
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000453 /// Handles cloning of a global values from the source module into
454 /// the destination module, including setting the attributes and visibility.
455 GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000456 const GlobalValue *DGV, bool ForDefinition);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000457
458 /// Check if we should promote the given local value to global scope.
459 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
460
Rafael Espindolac84f6082014-11-25 06:11:24 +0000461 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
462 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000463
Rafael Espindolac84f6082014-11-25 06:11:24 +0000464 /// Helper method for setting a message and returning an error code.
465 bool emitError(const Twine &Message) {
466 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000467 HasError = true;
Rafael Espindolac84f6082014-11-25 06:11:24 +0000468 return true;
469 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000470
Rafael Espindolac84f6082014-11-25 06:11:24 +0000471 void emitWarning(const Twine &Message) {
472 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
473 }
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000474
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000475 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +0000476 const GlobalVariable *&GVar);
477 bool computeResultingSelectionKind(StringRef ComdatName,
478 Comdat::SelectionKind Src,
479 Comdat::SelectionKind Dst,
480 Comdat::SelectionKind &Result,
481 bool &LinkFromSrc);
482 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
483 ComdatsChosen;
484 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
485 bool &LinkFromSrc);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +0000486 // Keep track of the global value members of each comdat in source.
487 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000488
Rafael Espindolac84f6082014-11-25 06:11:24 +0000489 /// Given a global in the source module, return the global in the
490 /// destination module that is being linked to, if any.
491 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
492 // If the source has no name it can't link. If it has local linkage,
493 // there is no name match-up going on.
Teresa Johnsonb098f0c2015-11-24 19:46:58 +0000494 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
Rafael Espindolac84f6082014-11-25 06:11:24 +0000495 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000496
Rafael Espindolac84f6082014-11-25 06:11:24 +0000497 // Otherwise see if we have a match in the destination module's symtab.
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000498 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
Rafael Espindolac84f6082014-11-25 06:11:24 +0000499 if (!DGV)
500 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000501
Rafael Espindolac84f6082014-11-25 06:11:24 +0000502 // If we found a global with the same name in the dest module, but it has
503 // internal linkage, we are really not doing any linkage here.
504 if (DGV->hasLocalLinkage())
505 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000506
Rafael Espindolac84f6082014-11-25 06:11:24 +0000507 // Otherwise, we do in fact link to the destination global.
508 return DGV;
509 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000510
Rafael Espindolac84f6082014-11-25 06:11:24 +0000511 void computeTypeMapping();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000512
Rafael Espindolac84f6082014-11-25 06:11:24 +0000513 void upgradeMismatchedGlobalArray(StringRef Name);
514 void upgradeMismatchedGlobals();
David Majnemerdad0a642014-06-27 18:19:56 +0000515
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000516 bool linkIfNeeded(GlobalValue &GV);
Rafael Espindolac84f6082014-11-25 06:11:24 +0000517 bool linkAppendingVarProto(GlobalVariable *DstGV,
518 const GlobalVariable *SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000519
Rafael Espindolac84f6082014-11-25 06:11:24 +0000520 bool linkGlobalValueProto(GlobalValue *GV);
Rafael Espindolac84f6082014-11-25 06:11:24 +0000521 bool linkModuleFlagsMetadata();
Mikhail Glushenkov766d4892009-03-03 07:22:23 +0000522
Rafael Espindolaef237112014-12-08 18:45:16 +0000523 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
524 bool linkFunctionBody(Function &Dst, Function &Src);
525 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
Rafael Espindolae39cd5b2015-12-01 22:40:40 +0000526 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
Rafael Espindolaef237112014-12-08 18:45:16 +0000527
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000528 /// Functions that take care of cloning a specific global value type
529 /// into the destination module.
530 GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
531 const GlobalVariable *SGVar);
532 Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
533 GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
534
535 /// Helper methods to check if we are importing from or potentially
536 /// exporting from the current source module.
537 bool isPerformingImport() { return ImportFunction != nullptr; }
538 bool isModuleExporting() { return HasExportedFunctions; }
539
540 /// If we are importing from the source module, checks if we should
541 /// import SGV as a definition, otherwise import as a declaration.
542 bool doImportAsDefinition(const GlobalValue *SGV);
543
544 /// Get the name for SGV that should be used in the linked destination
545 /// module. Specifically, this handles the case where we need to rename
546 /// a local that is being promoted to global scope.
547 std::string getName(const GlobalValue *SGV);
548
549 /// Get the new linkage for SGV that should be used in the linked destination
550 /// module. Specifically, for ThinLTO importing or exporting it may need
551 /// to be adjusted.
552 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
553
554 /// Copies the necessary global value attributes and name from the source
555 /// to the newly cloned global value.
556 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
557
558 /// Updates the visibility for the new global cloned from the source
559 /// and, if applicable, linked with an existing destination global.
560 /// Handles visibility change required for promoted locals.
561 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
562 const GlobalValue *DGV = nullptr);
563
Rafael Espindolac84f6082014-11-25 06:11:24 +0000564 void linkNamedMDNodes();
565};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000566}
Bill Wendlingd48b7782012-02-28 04:01:21 +0000567
Rafael Espindola18c89412014-10-27 02:35:46 +0000568/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
569/// table. This is good for all clients except for us. Go through the trouble
570/// to force this back.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000571static void forceRenaming(GlobalValue *GV, StringRef Name) {
572 // If the global doesn't force its name or if it already has the right name,
573 // there is nothing for us to do.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000574 // Note that any required local to global promotion should already be done,
575 // so promoted locals will not skip this handling as their linkage is no
576 // longer local.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000577 if (GV->hasLocalLinkage() || GV->getName() == Name)
578 return;
579
580 Module *M = GV->getParent();
Reid Spencer361e5132004-11-12 20:37:43 +0000581
582 // If there is a conflict, rename the conflict.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000583 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000584 GV->takeName(ConflictGV);
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000585 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000586 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
Chris Lattner2a8d2e02007-02-11 00:39:38 +0000587 } else {
Rafael Espindolae3a933a2015-12-01 20:11:43 +0000588 GV->setName(Name); // Force the name back
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000589 }
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000590}
Reid Spencer90246aa2007-02-04 04:29:21 +0000591
Rafael Espindola18c89412014-10-27 02:35:46 +0000592/// copy additional attributes (those not needed to construct a GlobalValue)
593/// from the SrcGV to the DestGV.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000594void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
595 const GlobalValue *SrcGV) {
596 auto *GA = dyn_cast<GlobalAlias>(SrcGV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000597 if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000598 // FIXME: this is likelly bogus:
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000599 NewGV->copyAttributesFrom(GA->getBaseObject());
600 } else
601 NewGV->copyAttributesFrom(SrcGV);
602 forceRenaming(NewGV, getName(SrcGV));
Reid Spencer361e5132004-11-12 20:37:43 +0000603}
604
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000605bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
606 if (!isPerformingImport())
607 return false;
Teresa Johnson3cd81612015-11-10 18:20:11 +0000608 auto *GA = dyn_cast<GlobalAlias>(SGV);
609 if (GA) {
610 if (GA->hasWeakAnyLinkage())
611 return false;
Rafael Espindola89345772015-11-26 19:22:59 +0000612 const GlobalObject *GO = GA->getBaseObject();
613 if (!GO->hasLinkOnceODRLinkage())
614 return false;
615 return doImportAsDefinition(GO);
Teresa Johnson3cd81612015-11-10 18:20:11 +0000616 }
Teresa Johnsondfbebc32015-11-10 18:26:31 +0000617 // Always import GlobalVariable definitions, except for the special
618 // case of WeakAny which are imported as ExternalWeak declarations
619 // (see comments in ModuleLinker::getLinkage). The linkage changes
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000620 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
621 // global variables with external linkage are transformed to
Teresa Johnson3cd81612015-11-10 18:20:11 +0000622 // available_externally definitions, which are ultimately turned into
623 // declarations after the EliminateAvailableExternally pass).
Craig Topper66059c92015-11-18 07:07:59 +0000624 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
Teresa Johnson3cd81612015-11-10 18:20:11 +0000625 !SGV->hasWeakAnyLinkage())
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000626 return true;
627 // Only import the function requested for importing.
628 auto *SF = dyn_cast<Function>(SGV);
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000629 if (SF && ImportFunction->count(SF))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000630 return true;
631 // Otherwise no.
632 return false;
633}
634
635bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
636 assert(SGV->hasLocalLinkage());
637 // Both the imported references and the original local variable must
638 // be promoted.
639 if (!isPerformingImport() && !isModuleExporting())
640 return false;
641
642 // Local const variables never need to be promoted unless they are address
643 // taken. The imported uses can simply use the clone created in this module.
644 // For now we are conservative in determining which variables are not
645 // address taken by checking the unnamed addr flag. To be more aggressive,
646 // the address taken information must be checked earlier during parsing
647 // of the module and recorded in the function index for use when importing
648 // from that module.
649 auto *GVar = dyn_cast<GlobalVariable>(SGV);
650 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
651 return false;
652
653 // Eventually we only need to promote functions in the exporting module that
654 // are referenced by a potentially exported function (i.e. one that is in the
655 // function index).
656 return true;
657}
658
659std::string ModuleLinker::getName(const GlobalValue *SGV) {
660 // For locals that must be promoted to global scope, ensure that
661 // the promoted name uniquely identifies the copy in the original module,
662 // using the ID assigned during combined index creation. When importing,
663 // we rename all locals (not just those that are promoted) in order to
664 // avoid naming conflicts between locals imported from different modules.
665 if (SGV->hasLocalLinkage() &&
666 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
667 return FunctionInfoIndex::getGlobalNameForLocal(
668 SGV->getName(),
669 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
670 return SGV->getName();
671}
672
673GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
674 // Any local variable that is referenced by an exported function needs
675 // to be promoted to global scope. Since we don't currently know which
676 // functions reference which local variables/functions, we must treat
677 // all as potentially exported if this module is exporting anything.
678 if (isModuleExporting()) {
679 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
680 return GlobalValue::ExternalLinkage;
681 return SGV->getLinkage();
682 }
683
684 // Otherwise, if we aren't importing, no linkage change is needed.
685 if (!isPerformingImport())
686 return SGV->getLinkage();
687
688 switch (SGV->getLinkage()) {
689 case GlobalValue::ExternalLinkage:
690 // External defnitions are converted to available_externally
691 // definitions upon import, so that they are available for inlining
692 // and/or optimization, but are turned into declarations later
693 // during the EliminateAvailableExternally pass.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000694 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000695 return GlobalValue::AvailableExternallyLinkage;
696 // An imported external declaration stays external.
697 return SGV->getLinkage();
698
699 case GlobalValue::AvailableExternallyLinkage:
700 // An imported available_externally definition converts
701 // to external if imported as a declaration.
702 if (!doImportAsDefinition(SGV))
703 return GlobalValue::ExternalLinkage;
704 // An imported available_externally declaration stays that way.
705 return SGV->getLinkage();
706
707 case GlobalValue::LinkOnceAnyLinkage:
708 case GlobalValue::LinkOnceODRLinkage:
709 // These both stay the same when importing the definition.
710 // The ThinLTO pass will eventually force-import their definitions.
711 return SGV->getLinkage();
712
713 case GlobalValue::WeakAnyLinkage:
714 // Can't import weak_any definitions correctly, or we might change the
715 // program semantics, since the linker will pick the first weak_any
716 // definition and importing would change the order they are seen by the
717 // linker. The module linking caller needs to enforce this.
718 assert(!doImportAsDefinition(SGV));
719 // If imported as a declaration, it becomes external_weak.
720 return GlobalValue::ExternalWeakLinkage;
721
722 case GlobalValue::WeakODRLinkage:
723 // For weak_odr linkage, there is a guarantee that all copies will be
724 // equivalent, so the issue described above for weak_any does not exist,
725 // and the definition can be imported. It can be treated similarly
726 // to an imported externally visible global value.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000727 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000728 return GlobalValue::AvailableExternallyLinkage;
729 else
730 return GlobalValue::ExternalLinkage;
731
732 case GlobalValue::AppendingLinkage:
733 // It would be incorrect to import an appending linkage variable,
734 // since it would cause global constructors/destructors to be
735 // executed multiple times. This should have already been handled
736 // by linkGlobalValueProto.
Davide Italianof3d23292015-11-13 02:16:51 +0000737 llvm_unreachable("Cannot import appending linkage variable");
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000738
739 case GlobalValue::InternalLinkage:
740 case GlobalValue::PrivateLinkage:
741 // If we are promoting the local to global scope, it is handled
742 // similarly to a normal externally visible global.
743 if (doPromoteLocalToGlobal(SGV)) {
Teresa Johnson3cd81612015-11-10 18:20:11 +0000744 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000745 return GlobalValue::AvailableExternallyLinkage;
746 else
747 return GlobalValue::ExternalLinkage;
748 }
749 // A non-promoted imported local definition stays local.
750 // The ThinLTO pass will eventually force-import their definitions.
751 return SGV->getLinkage();
752
753 case GlobalValue::ExternalWeakLinkage:
754 // External weak doesn't apply to definitions, must be a declaration.
755 assert(!doImportAsDefinition(SGV));
756 // Linkage stays external_weak.
757 return SGV->getLinkage();
758
759 case GlobalValue::CommonLinkage:
760 // Linkage stays common on definitions.
761 // The ThinLTO pass will eventually force-import their definitions.
762 return SGV->getLinkage();
763 }
764
765 llvm_unreachable("unknown linkage type");
766}
767
Rafael Espindolaef237112014-12-08 18:45:16 +0000768/// Loop through the global variables in the src module and merge them into the
769/// dest module.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000770GlobalVariable *
771ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
772 const GlobalVariable *SGVar) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000773 // No linking to be performed or linking from the source: simply create an
774 // identical version of the symbol over in the dest module... the
775 // initializer will be filled in later by LinkGlobalInits.
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000776 GlobalVariable *NewDGV =
777 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
778 SGVar->isConstant(), GlobalValue::ExternalLinkage,
779 /*init*/ nullptr, getName(SGVar),
780 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
781 SGVar->getType()->getAddressSpace());
Rafael Espindolaef237112014-12-08 18:45:16 +0000782
783 return NewDGV;
784}
785
786/// Link the function in the source module into the destination module if
787/// needed, setting up mapping information.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000788Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
789 const Function *SF) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000790 // If there is no linkage to be performed or we are linking from the source,
791 // bring SF over.
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000792 return Function::Create(TypeMap.get(SF->getFunctionType()),
793 GlobalValue::ExternalLinkage, getName(SF), &DstM);
Rafael Espindolaef237112014-12-08 18:45:16 +0000794}
795
796/// Set up prototypes for any aliases that come over from the source module.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000797GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
798 const GlobalAlias *SGA) {
799 // If we are importing and encounter a weak_any alias, or an alias to
800 // an object being imported as a declaration, we must import the alias
801 // as a declaration as well, which involves converting it to a non-alias.
802 // See comments in ModuleLinker::getLinkage for why we cannot import
803 // weak_any defintions.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000804 if (isPerformingImport() && !doImportAsDefinition(SGA)) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000805 // Need to convert to declaration. All aliases must be definitions.
806 const GlobalValue *GVal = SGA->getBaseObject();
807 GlobalValue *NewGV;
808 if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
809 NewGV = copyGlobalVariableProto(TypeMap, GVar);
810 else {
811 auto *F = dyn_cast<Function>(GVal);
812 assert(F);
813 NewGV = copyFunctionProto(TypeMap, F);
814 }
Teresa Johnsonf1b0a6e2015-11-04 16:01:16 +0000815 // Set the linkage to External or ExternalWeak (see comments in
816 // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000817 if (SGA->hasWeakAnyLinkage())
818 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
Teresa Johnsonf1b0a6e2015-11-04 16:01:16 +0000819 else
820 NewGV->setLinkage(GlobalValue::ExternalLinkage);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000821 return NewGV;
822 }
Rafael Espindolaef237112014-12-08 18:45:16 +0000823 // If there is no linkage to be performed or we're linking from the source,
824 // bring over SGA.
David Blaikie6614d8d2015-09-14 20:29:26 +0000825 auto *Ty = TypeMap.get(SGA->getValueType());
826 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000827 GlobalValue::ExternalLinkage, getName(SGA), &DstM);
Rafael Espindolaef237112014-12-08 18:45:16 +0000828}
829
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000830static GlobalValue::VisibilityTypes
831getMinVisibility(GlobalValue::VisibilityTypes A,
832 GlobalValue::VisibilityTypes B) {
833 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
834 return GlobalValue::HiddenVisibility;
835 if (A == GlobalValue::ProtectedVisibility ||
836 B == GlobalValue::ProtectedVisibility)
837 return GlobalValue::ProtectedVisibility;
838 return GlobalValue::DefaultVisibility;
839}
840
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000841void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
842 const GlobalValue *DGV) {
843 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
844 if (DGV)
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000845 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000846 // For promoted locals, mark them hidden so that they can later be
847 // stripped from the symbol table to reduce bloat.
848 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
849 Visibility = GlobalValue::HiddenVisibility;
850 NewGV->setVisibility(Visibility);
851}
852
853GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
854 const GlobalValue *SGV,
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000855 const GlobalValue *DGV,
856 bool ForDefinition) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000857 GlobalValue *NewGV;
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000858 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000859 NewGV = copyGlobalVariableProto(TypeMap, SGVar);
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000860 } else if (auto *SF = dyn_cast<Function>(SGV)) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000861 NewGV = copyFunctionProto(TypeMap, SF);
Rafael Espindolaf3518c92015-12-02 19:30:52 +0000862 } else {
863 if (ForDefinition)
864 NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
865 else
866 NewGV = new GlobalVariable(
867 DstM, TypeMap.get(SGV->getType()->getElementType()),
868 /*isConstant*/ false, GlobalValue::ExternalLinkage,
869 /*init*/ nullptr, getName(SGV),
870 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
871 SGV->getType()->getAddressSpace());
872 }
873
874 if (ForDefinition)
875 NewGV->setLinkage(getLinkage(SGV));
876 else if (SGV->hasAvailableExternallyLinkage() || SGV->hasWeakLinkage() ||
877 SGV->hasLinkOnceLinkage())
878 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
879
Rafael Espindolaef237112014-12-08 18:45:16 +0000880 copyGVAttributes(NewGV, SGV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000881 setVisibility(NewGV, SGV, DGV);
Rafael Espindolaef237112014-12-08 18:45:16 +0000882 return NewGV;
883}
884
Rafael Espindola19b52382015-11-27 20:28:19 +0000885Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
886 return ModLinker->materializeDeclFor(V);
887}
888
889Value *ModuleLinker::materializeDeclFor(Value *V) {
Rafael Espindolaef237112014-12-08 18:45:16 +0000890 auto *SGV = dyn_cast<GlobalValue>(V);
891 if (!SGV)
Craig Topper2617dcc2014-04-15 06:32:26 +0000892 return nullptr;
James Molloyf6f121e2013-05-28 15:17:05 +0000893
Teresa Johnson10632932015-11-06 17:50:53 +0000894 // If we are done linking global value bodies (i.e. we are performing
895 // metadata linking), don't link in the global value due to this
896 // reference, simply map it to null.
Rafael Espindola6d2c3132015-12-01 23:01:51 +0000897 if (DoneLinkingBodies)
Teresa Johnson10632932015-11-06 17:50:53 +0000898 return nullptr;
899
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000900 linkGlobalValueProto(SGV);
901 if (HasError)
902 return nullptr;
903 Value *Ret = ValueMap[SGV];
904 assert(Ret);
905 return Ret;
James Molloyf6f121e2013-05-28 15:17:05 +0000906}
907
Rafael Espindola19b52382015-11-27 20:28:19 +0000908void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
909 GlobalValue *Old) {
910 return ModLinker->materializeInitFor(New, Old);
911}
912
913void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000914 if (auto *F = dyn_cast<Function>(New)) {
915 if (!F->isDeclaration())
916 return;
917 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
918 if (V->hasInitializer())
919 return;
920 } else {
921 auto *A = cast<GlobalAlias>(New);
922 if (A->getAliasee())
923 return;
924 }
925
926 if (Old->isDeclaration())
927 return;
928
Rafael Espindola19b52382015-11-27 20:28:19 +0000929 if (isPerformingImport() && !doImportAsDefinition(Old))
930 return;
931
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000932 if (!New->hasLocalLinkage() && DoNotLinkFromSource.count(Old))
Rafael Espindola19b52382015-11-27 20:28:19 +0000933 return;
934
Rafael Espindolae39cd5b2015-12-01 22:40:40 +0000935 linkGlobalValueBody(*New, *Old);
Rafael Espindola19b52382015-11-27 20:28:19 +0000936}
937
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000938bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000939 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000940 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000941 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
942 GVal = GA->getBaseObject();
943 if (!GVal)
944 // We cannot resolve the size of the aliasee yet.
945 return emitError("Linking COMDATs named '" + ComdatName +
946 "': COMDAT key involves incomputable alias size.");
947 }
948
949 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
950 if (!GVar)
951 return emitError(
952 "Linking COMDATs named '" + ComdatName +
953 "': GlobalVariable required for data dependent selection!");
954
955 return false;
956}
957
958bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
959 Comdat::SelectionKind Src,
960 Comdat::SelectionKind Dst,
961 Comdat::SelectionKind &Result,
962 bool &LinkFromSrc) {
963 // The ability to mix Comdat::SelectionKind::Any with
964 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
965 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
966 Dst == Comdat::SelectionKind::Largest;
967 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
968 Src == Comdat::SelectionKind::Largest;
969 if (DstAnyOrLargest && SrcAnyOrLargest) {
970 if (Dst == Comdat::SelectionKind::Largest ||
971 Src == Comdat::SelectionKind::Largest)
972 Result = Comdat::SelectionKind::Largest;
973 else
974 Result = Comdat::SelectionKind::Any;
975 } else if (Src == Dst) {
976 Result = Dst;
977 } else {
978 return emitError("Linking COMDATs named '" + ComdatName +
979 "': invalid selection kinds!");
980 }
981
982 switch (Result) {
983 case Comdat::SelectionKind::Any:
984 // Go with Dst.
985 LinkFromSrc = false;
986 break;
987 case Comdat::SelectionKind::NoDuplicates:
988 return emitError("Linking COMDATs named '" + ComdatName +
989 "': noduplicates has been violated!");
990 case Comdat::SelectionKind::ExactMatch:
991 case Comdat::SelectionKind::Largest:
992 case Comdat::SelectionKind::SameSize: {
993 const GlobalVariable *DstGV;
994 const GlobalVariable *SrcGV;
995 if (getComdatLeader(DstM, ComdatName, DstGV) ||
996 getComdatLeader(SrcM, ComdatName, SrcGV))
997 return true;
998
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000999 const DataLayout &DstDL = DstM.getDataLayout();
1000 const DataLayout &SrcDL = SrcM.getDataLayout();
David Majnemerdad0a642014-06-27 18:19:56 +00001001 uint64_t DstSize =
Mehdi Amini46a43552015-03-04 18:43:29 +00001002 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +00001003 uint64_t SrcSize =
Mehdi Amini46a43552015-03-04 18:43:29 +00001004 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +00001005 if (Result == Comdat::SelectionKind::ExactMatch) {
1006 if (SrcGV->getInitializer() != DstGV->getInitializer())
1007 return emitError("Linking COMDATs named '" + ComdatName +
1008 "': ExactMatch violated!");
1009 LinkFromSrc = false;
1010 } else if (Result == Comdat::SelectionKind::Largest) {
1011 LinkFromSrc = SrcSize > DstSize;
1012 } else if (Result == Comdat::SelectionKind::SameSize) {
1013 if (SrcSize != DstSize)
1014 return emitError("Linking COMDATs named '" + ComdatName +
1015 "': SameSize violated!");
1016 LinkFromSrc = false;
1017 } else {
1018 llvm_unreachable("unknown selection kind");
1019 }
1020 break;
1021 }
1022 }
1023
1024 return false;
1025}
1026
1027bool ModuleLinker::getComdatResult(const Comdat *SrcC,
1028 Comdat::SelectionKind &Result,
1029 bool &LinkFromSrc) {
Rafael Espindolab16196a2014-08-11 17:07:34 +00001030 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +00001031 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001032 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +00001033 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001034
Rafael Espindolab16196a2014-08-11 17:07:34 +00001035 if (DstCI == ComdatSymTab.end()) {
1036 // Use the comdat if it is only available in one of the modules.
1037 LinkFromSrc = true;
1038 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001039 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +00001040 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001041
1042 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +00001043 Comdat::SelectionKind DSK = DstC->getSelectionKind();
1044 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1045 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +00001046}
James Molloyf6f121e2013-05-28 15:17:05 +00001047
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001048bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1049 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001050 const GlobalValue &Src) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001051 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +00001052 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +00001053 LinkFromSrc = true;
1054 return false;
1055 }
1056
Rafael Espindola778fcc72014-11-02 13:28:57 +00001057 // We always have to add Src if it has appending linkage.
1058 if (Src.hasAppendingLinkage()) {
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001059 // Caller should have already determined that we can't link from source
1060 // when importing (see comments in linkGlobalValueProto).
1061 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +00001062 LinkFromSrc = true;
1063 return false;
1064 }
1065
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00001066 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1067 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001068
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001069 if (isPerformingImport()) {
1070 if (isa<Function>(&Src)) {
1071 // For functions, LinkFromSrc iff this is the function requested
1072 // for importing. For variables, decide below normally.
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +00001073 LinkFromSrc = ImportFunction->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001074 return false;
1075 }
1076
1077 // Check if this is an alias with an already existing definition
1078 // in Dest, which must have come from a prior importing pass from
1079 // the same Src module. Unlike imported function and variable
1080 // definitions, which are imported as available_externally and are
1081 // not definitions for the linker, that is not a valid linkage for
1082 // imported aliases which must be definitions. Simply use the existing
1083 // Dest copy.
1084 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1085 assert(isa<GlobalAlias>(&Dest));
1086 LinkFromSrc = false;
1087 return false;
1088 }
1089 }
1090
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001091 if (SrcIsDeclaration) {
1092 // If Src is external or if both Src & Dest are external.. Just link the
1093 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001094 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001095 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001096 LinkFromSrc = DestIsDeclaration;
1097 return false;
1098 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001099 // If the Dest is weak, use the source linkage.
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001100 LinkFromSrc = Dest.hasExternalWeakLinkage();
1101 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001102 }
1103
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001104 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001105 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001106 LinkFromSrc = true;
1107 return false;
1108 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001109
Rafael Espindola09106052014-09-09 15:59:12 +00001110 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001111 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1112 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +00001113 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001114 }
1115
1116 if (!Dest.hasCommonLinkage()) {
1117 LinkFromSrc = false;
1118 return false;
1119 }
Rafael Espindola09106052014-09-09 15:59:12 +00001120
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001121 const DataLayout &DL = Dest.getParent()->getDataLayout();
Rafael Espindola09106052014-09-09 15:59:12 +00001122 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1123 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001124 LinkFromSrc = SrcSize > DestSize;
1125 return false;
Rafael Espindola09106052014-09-09 15:59:12 +00001126 }
1127
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001128 if (Src.isWeakForLinker()) {
1129 assert(!Dest.hasExternalWeakLinkage());
1130 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +00001131
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001132 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1133 LinkFromSrc = true;
1134 return false;
1135 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001136
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001137 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +00001138 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001139 }
1140
1141 if (Dest.isWeakForLinker()) {
1142 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001143 LinkFromSrc = true;
1144 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +00001145 }
1146
1147 assert(!Src.hasExternalWeakLinkage());
1148 assert(!Dest.hasExternalWeakLinkage());
1149 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1150 "Unexpected linkage type!");
1151 return emitError("Linking globals named '" + Src.getName() +
1152 "': symbol multiply defined!");
1153}
1154
Rafael Espindola18c89412014-10-27 02:35:46 +00001155/// Loop over all of the linked values to compute type mappings. For example,
1156/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1157/// types 'Foo' but one got renamed when the module was loaded into the same
1158/// LLVMContext.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001159void ModuleLinker::computeTypeMapping() {
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001160 for (GlobalValue &SGV : SrcM.globals()) {
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001161 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1162 if (!DGV)
1163 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001164
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001165 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1166 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001167 continue;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001168 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001169
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001170 // Unify the element type of appending arrays.
1171 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001172 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001173 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
Devang Patel5c310be2009-08-11 18:01:24 +00001174 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001175
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001176 for (GlobalValue &SGV : SrcM) {
Rafael Espindolac8a476e2014-11-25 04:26:19 +00001177 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1178 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001179 }
Bill Wendling7b464612012-02-27 22:34:19 +00001180
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001181 for (GlobalValue &SGV : SrcM.aliases()) {
Rafael Espindolae96d7eb2014-11-25 04:43:59 +00001182 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1183 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1184 }
1185
Bill Wendlingd48b7782012-02-28 04:01:21 +00001186 // Incorporate types by name, scanning all the types in the source module.
1187 // At this point, the destination module may have a type "%foo = { i32 }" for
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001188 // example. When the source module got loaded into the same LLVMContext, if
1189 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001190 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001191 for (StructType *ST : Types) {
Rafael Espindola4d4c9382014-12-01 19:08:07 +00001192 if (!ST->hasName())
1193 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001194
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001195 // Check to see if there is a dot in the name followed by a digit.
Bill Wendlingd48b7782012-02-28 04:01:21 +00001196 size_t DotPos = ST->getName().rfind('.');
1197 if (DotPos == 0 || DotPos == StringRef::npos ||
Guy Benyei83c74e92013-02-12 21:21:59 +00001198 ST->getName().back() == '.' ||
Rafael Espindola973b3612014-12-01 19:17:46 +00001199 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
Bill Wendlingd48b7782012-02-28 04:01:21 +00001200 continue;
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001201
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001202 // Check to see if the destination module has a struct with the prefix name.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001203 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
Rafael Espindola973b3612014-12-01 19:17:46 +00001204 if (!DST)
1205 continue;
1206
1207 // Don't use it if this actually came from the source module. They're in
1208 // the same LLVMContext after all. Also don't use it unless the type is
1209 // actually used in the destination module. This can happen in situations
1210 // like this:
1211 //
1212 // Module A Module B
1213 // -------- --------
1214 // %Z = type { %A } %B = type { %C.1 }
1215 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1216 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1217 // %C = type { i8* } %B.3 = type { %C.1 }
1218 //
1219 // When we link Module B with Module A, the '%B' in Module B is
1220 // used. However, that would then use '%C.1'. But when we process '%C.1',
1221 // we prefer to take the '%C' version. So we are then left with both
1222 // '%C.1' and '%C' being used for the same types. This leads to some
1223 // variables using one type and some using the other.
Rafael Espindola31ad4682014-12-03 22:36:37 +00001224 if (TypeMap.DstStructTypesSet.hasType(DST))
Rafael Espindola973b3612014-12-01 19:17:46 +00001225 TypeMap.addTypeMapping(DST, ST);
Bill Wendling2b3f61a2012-02-27 23:48:30 +00001226 }
1227
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001228 // Now that we have discovered all of the type equivalences, get a body for
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001229 // any 'opaque' types in the dest module that are now resolved.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001230 TypeMap.linkDefinedTypeBodies();
Devang Patel5c310be2009-08-11 18:01:24 +00001231}
1232
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001233static void upgradeGlobalArray(GlobalVariable *GV) {
1234 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
1235 StructType *OldTy = cast<StructType>(ATy->getElementType());
1236 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
1237
1238 // Get the upgraded 3 element type.
1239 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
1240 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
1241 VoidPtrTy};
1242 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
1243
1244 // Build new constants with a null third field filled in.
1245 Constant *OldInitC = GV->getInitializer();
1246 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
1247 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
1248 // Invalid initializer; give up.
1249 return;
1250 std::vector<Constant *> Initializers;
1251 if (OldInit && OldInit->getNumOperands()) {
1252 Value *Null = Constant::getNullValue(VoidPtrTy);
1253 for (Use &U : OldInit->operands()) {
1254 ConstantStruct *Init = cast<ConstantStruct>(U.get());
1255 Initializers.push_back(ConstantStruct::get(
1256 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
1257 }
1258 }
1259 assert(Initializers.size() == ATy->getNumElements() &&
1260 "Failed to copy all array elements");
1261
1262 // Replace the old GV with a new one.
1263 ATy = ArrayType::get(NewTy, Initializers.size());
1264 Constant *NewInit = ConstantArray::get(ATy, Initializers);
1265 GlobalVariable *NewGV = new GlobalVariable(
1266 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
1267 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
1268 GV->isExternallyInitialized());
1269 NewGV->copyAttributesFrom(GV);
1270 NewGV->takeName(GV);
1271 assert(GV->use_empty() && "program cannot use initializer list");
1272 GV->eraseFromParent();
1273}
1274
1275void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
1276 // Look for the global arrays.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001277 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM.getNamedValue(Name));
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001278 if (!DstGV)
1279 return;
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001280 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM.getNamedValue(Name));
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001281 if (!SrcGV)
1282 return;
1283
1284 // Check if the types already match.
1285 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1286 auto *SrcTy =
1287 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1288 if (DstTy == SrcTy)
1289 return;
1290
1291 // Grab the element types. We can only upgrade an array of a two-field
1292 // struct. Only bother if the other one has three-fields.
1293 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
1294 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
1295 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
1296 upgradeGlobalArray(DstGV);
1297 return;
1298 }
1299 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
1300 upgradeGlobalArray(SrcGV);
1301
1302 // We can't upgrade any other differences.
1303}
1304
1305void ModuleLinker::upgradeMismatchedGlobals() {
1306 upgradeMismatchedGlobalArray("llvm.global_ctors");
1307 upgradeMismatchedGlobalArray("llvm.global_dtors");
1308}
1309
Rafael Espindola6e8ab922015-12-01 17:17:04 +00001310static void getArrayElements(const Constant *C,
1311 SmallVectorImpl<Constant *> &Dest) {
1312 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1313
1314 for (unsigned i = 0; i != NumElements; ++i)
1315 Dest.push_back(C->getAggregateElement(i));
1316}
1317
Rafael Espindola18c89412014-10-27 02:35:46 +00001318/// If there were any appending global variables, link them together now.
1319/// Return true on error.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001320bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
Rafael Espindola3e8bc6a2014-10-31 16:08:17 +00001321 const GlobalVariable *SrcGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001322 ArrayType *SrcTy =
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001323 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1324 Type *EltTy = SrcTy->getElementType();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001325
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001326 if (DstGV) {
1327 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001328
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001329 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1330 return emitError(
1331 "Linking globals named '" + SrcGV->getName() +
1332 "': can only link appending global with another appending global!");
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001333
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001334 // Check to see that they two arrays agree on type.
1335 if (EltTy != DstTy->getElementType())
1336 return emitError("Appending variables with different element types!");
1337 if (DstGV->isConstant() != SrcGV->isConstant())
1338 return emitError("Appending variables linked with different const'ness!");
Rafael Espindolafac3a012013-09-04 15:33:34 +00001339
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001340 if (DstGV->getAlignment() != SrcGV->getAlignment())
1341 return emitError(
1342 "Appending variables with different alignment need to be linked!");
Rafael Espindolafac3a012013-09-04 15:33:34 +00001343
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001344 if (DstGV->getVisibility() != SrcGV->getVisibility())
1345 return emitError(
1346 "Appending variables with different visibility need to be linked!");
1347
1348 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1349 return emitError(
1350 "Appending variables with different unnamed_addr need to be linked!");
1351
1352 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1353 return emitError(
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001354 "Appending variables with different section name need to be linked!");
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001355 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001356
Rafael Espindola6e8ab922015-12-01 17:17:04 +00001357 SmallVector<Constant *, 16> DstElements;
1358 if (DstGV)
1359 getArrayElements(DstGV->getInitializer(), DstElements);
1360
1361 SmallVector<Constant *, 16> SrcElements;
1362 getArrayElements(SrcGV->getInitializer(), SrcElements);
1363
1364 StringRef Name = SrcGV->getName();
1365 bool IsNewStructor =
1366 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1367 cast<StructType>(EltTy)->getNumElements() == 3;
1368 if (IsNewStructor)
1369 SrcElements.erase(
1370 std::remove_if(SrcElements.begin(), SrcElements.end(),
1371 [this](Constant *E) {
1372 auto *Key = dyn_cast<GlobalValue>(
1373 E->getAggregateElement(2)->stripPointerCasts());
1374 return DoNotLinkFromSource.count(Key);
1375 }),
1376 SrcElements.end());
1377 uint64_t NewSize = DstElements.size() + SrcElements.size();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001378 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001379
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001380 // Create the new global variable.
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001381 GlobalVariable *NG = new GlobalVariable(
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001382 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001383 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1384 SrcGV->getType()->getAddressSpace());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001385
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001386 // Propagate alignment, visibility and section info.
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001387 copyGVAttributes(NG, SrcGV);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001388
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001389 // Replace any uses of the two global variables with uses of the new
1390 // global.
1391 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
Anton Korobeynikove79f4c72008-03-10 22:34:28 +00001392
Rafael Espindola6e8ab922015-12-01 17:17:04 +00001393 for (auto *V : SrcElements) {
1394 DstElements.push_back(
1395 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1396 }
1397
1398 NG->setInitializer(ConstantArray::get(NewType, DstElements));
1399
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001400 if (DstGV) {
1401 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1402 DstGV->eraseFromParent();
1403 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001404
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001405 return false;
1406}
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001407
Rafael Espindola778fcc72014-11-02 13:28:57 +00001408bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001409 GlobalValue *DGV = getLinkedToGlobal(SGV);
Mikhail Glushenkov766d4892009-03-03 07:22:23 +00001410
Rafael Espindola778fcc72014-11-02 13:28:57 +00001411 // Handle the ultra special appending linkage case first.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001412 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1413 if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1414 // Don't want to append to global_ctors list, for example, when we
1415 // are importing for ThinLTO, otherwise the global ctors and dtors
1416 // get executed multiple times for local variables (the latter causing
1417 // double frees).
1418 DoNotLinkFromSource.insert(SGV);
1419 return false;
1420 }
Rafael Espindolac945c8d2015-11-29 03:29:42 +00001421 if (SGV->hasAppendingLinkage())
1422 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
Rafael Espindola778fcc72014-11-02 13:28:57 +00001423 cast<GlobalVariable>(SGV));
1424
1425 bool LinkFromSrc = true;
1426 Comdat *C = nullptr;
Rafael Espindola778fcc72014-11-02 13:28:57 +00001427 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1428
David Majnemerdad0a642014-06-27 18:19:56 +00001429 if (const Comdat *SC = SGV->getComdat()) {
1430 Comdat::SelectionKind SK;
1431 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001432 C = DstM.getOrInsertComdat(SC->getName());
Rafael Espindola778fcc72014-11-02 13:28:57 +00001433 C->setSelectionKind(SK);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001434 if (SGV->hasInternalLinkage())
1435 LinkFromSrc = true;
Rafael Espindola778fcc72014-11-02 13:28:57 +00001436 } else if (DGV) {
1437 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1438 return true;
1439 }
1440
1441 if (!LinkFromSrc) {
1442 // Track the source global so that we don't attempt to copy it over when
1443 // processing global initializers.
1444 DoNotLinkFromSource.insert(SGV);
1445
1446 if (DGV)
1447 // Make sure to remember this mapping.
1448 ValueMap[SGV] =
1449 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
David Majnemerdad0a642014-06-27 18:19:56 +00001450 }
1451
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001452 if (DGV)
Rafael Espindola778fcc72014-11-02 13:28:57 +00001453 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001454
Rafael Espindola778fcc72014-11-02 13:28:57 +00001455 GlobalValue *NewGV;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001456 if (!LinkFromSrc && DGV) {
Rafael Espindola26c29512014-12-05 17:53:15 +00001457 NewGV = DGV;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00001458 // When linking from source we setVisibility from copyGlobalValueProto.
1459 setVisibility(NewGV, SGV, DGV);
Rafael Espindola26c29512014-12-05 17:53:15 +00001460 } else {
Rafael Espindolaf3518c92015-12-02 19:30:52 +00001461 NewGV = copyGlobalValueProto(TypeMap, SGV, DGV, LinkFromSrc);
Teresa Johnson3cd81612015-11-10 18:20:11 +00001462
1463 if (isPerformingImport() && !doImportAsDefinition(SGV))
1464 DoNotLinkFromSource.insert(SGV);
Rafael Espindola26c29512014-12-05 17:53:15 +00001465 }
Rafael Espindolafe3842c2014-09-09 17:48:18 +00001466
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001467 NewGV->setUnnamedAddr(HasUnnamedAddr);
Rafael Espindola439835a2014-12-05 00:09:02 +00001468
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001469 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001470 if (C && LinkFromSrc)
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001471 NewGO->setComdat(C);
1472
1473 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1474 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1475 }
1476
Rafael Espindola879aeb72014-12-05 16:05:19 +00001477 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1478 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1479 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1480 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1481 (!DGVar->isConstant() || !SGVar->isConstant()))
1482 NewGVar->setConstant(false);
1483 }
1484
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001485 // Make sure to remember this mapping.
1486 if (NewGV != DGV) {
1487 if (DGV) {
1488 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1489 DGV->eraseFromParent();
Chandler Carruthfd38af22014-11-02 09:10:31 +00001490 }
Rafael Espindolaad9d0ca2014-12-05 15:42:30 +00001491 ValueMap[SGV] = NewGV;
Reid Spencer361e5132004-11-12 20:37:43 +00001492 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001493
Rafael Espindola778fcc72014-11-02 13:28:57 +00001494 return false;
1495}
1496
Rafael Espindola18c89412014-10-27 02:35:46 +00001497/// Update the initializers in the Dest module now that all globals that may be
1498/// referenced are in Dest.
Rafael Espindolaef237112014-12-08 18:45:16 +00001499void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1500 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001501 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1502 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Reid Spencer361e5132004-11-12 20:37:43 +00001503}
1504
Rafael Espindola18c89412014-10-27 02:35:46 +00001505/// Copy the source function over into the dest function and fix up references
1506/// to values. At this point we know that Dest is an external function, and
1507/// that Src is not.
Rafael Espindolaef237112014-12-08 18:45:16 +00001508bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1509 assert(Dst.isDeclaration() && !Src.isDeclaration());
Reid Spencer361e5132004-11-12 20:37:43 +00001510
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001511 // Materialize if needed.
Rafael Espindola3519da82014-12-08 14:25:26 +00001512 if (std::error_code EC = Src.materialize())
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001513 return emitError(EC.message());
1514
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001515 // Link in the prefix data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001516 if (Src.hasPrefixData())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001517 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1518 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001519
1520 // Link in the prologue data.
Rafael Espindola3519da82014-12-08 14:25:26 +00001521 if (Src.hasPrologueData())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001522 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1523 RF_MoveDistinctMDs, &TypeMap,
1524 &ValMaterializer));
Rafael Espindola869d1ce2014-12-08 13:44:38 +00001525
David Majnemer7fddecc2015-06-17 20:52:32 +00001526 // Link in the personality function.
1527 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001528 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1529 RF_MoveDistinctMDs, &TypeMap,
1530 &ValMaterializer));
David Majnemer7fddecc2015-06-17 20:52:32 +00001531
Chris Lattner7391dde2004-11-16 17:12:38 +00001532 // Go through and convert function arguments over, remembering the mapping.
Rafael Espindolaef237112014-12-08 18:45:16 +00001533 Function::arg_iterator DI = Dst.arg_begin();
Rafael Espindola3519da82014-12-08 14:25:26 +00001534 for (Argument &Arg : Src.args()) {
Rafael Espindolae3a933a2015-12-01 20:11:43 +00001535 DI->setName(Arg.getName()); // Copy the name over.
Reid Spencer361e5132004-11-12 20:37:43 +00001536
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001537 // Add a mapping to our mapping.
Duncan P. N. Exon Smith9934b262015-10-19 22:23:36 +00001538 ValueMap[&Arg] = &*DI;
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001539 ++DI;
Reid Spencer361e5132004-11-12 20:37:43 +00001540 }
1541
Duncan P. N. Exon Smithc8d987b2015-04-24 22:07:31 +00001542 // Copy over the metadata attachments.
1543 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1544 Src.getAllMetadata(MDs);
1545 for (const auto &I : MDs)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001546 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1547 &TypeMap, &ValMaterializer));
Duncan P. N. Exon Smithc8d987b2015-04-24 22:07:31 +00001548
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001549 // Splice the body of the source function into the dest function.
Rafael Espindolaef237112014-12-08 18:45:16 +00001550 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001551
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001552 // At this point, all of the instructions and values of the function are now
1553 // copied over. The only problem is that they are still referencing values in
1554 // the Source function as operands. Loop through all of the operands of the
1555 // functions and patch them up to point to the local versions.
Rafael Espindolaef237112014-12-08 18:45:16 +00001556 for (BasicBlock &BB : Dst)
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001557 for (Instruction &I : BB)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001558 RemapInstruction(&I, ValueMap,
1559 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
Rafael Espindola9f8eff32014-10-28 00:24:16 +00001560 &ValMaterializer);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001561
Chris Lattner7391dde2004-11-16 17:12:38 +00001562 // There is no need to map the arguments anymore.
Rafael Espindola3519da82014-12-08 14:25:26 +00001563 for (Argument &Arg : Src.args())
Rafael Espindolaa314d1a2014-12-08 14:20:10 +00001564 ValueMap.erase(&Arg);
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001565
Eric Christopher97cb5652015-05-15 18:20:14 +00001566 Src.dematerialize();
Rafael Espindola40d7ebe2014-12-08 13:29:33 +00001567 return false;
Reid Spencer361e5132004-11-12 20:37:43 +00001568}
1569
Rafael Espindolaef237112014-12-08 18:45:16 +00001570void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1571 Constant *Aliasee = Src.getAliasee();
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001572 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1573 &ValMaterializer);
Rafael Espindolaef237112014-12-08 18:45:16 +00001574 Dst.setAliasee(Val);
1575}
1576
Rafael Espindolae39cd5b2015-12-01 22:40:40 +00001577bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +00001578 if (const Comdat *SC = Src.getComdat()) {
1579 // To ensure that we don't generate an incomplete comdat group,
1580 // we must materialize and map in any other members that are not
1581 // yet materialized in Dst, which also ensures their definitions
1582 // are linked in. Otherwise, linkonce and other lazy linked GVs will
1583 // not be materialized if they aren't referenced.
1584 for (auto *SGV : ComdatMembers[SC]) {
Rafael Espindola19b52382015-11-27 20:28:19 +00001585 auto *DGV = cast_or_null<GlobalValue>(ValueMap[SGV]);
1586 if (DGV && !DGV->isDeclaration())
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +00001587 continue;
Rafael Espindola19b52382015-11-27 20:28:19 +00001588 MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +00001589 }
1590 }
Artem Belevich020d4fb2015-09-01 17:55:55 +00001591 if (shouldInternalizeLinkedSymbols())
Rafael Espindolae39cd5b2015-12-01 22:40:40 +00001592 if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
Artem Belevich020d4fb2015-09-01 17:55:55 +00001593 DGV->setLinkage(GlobalValue::InternalLinkage);
Rafael Espindolaef237112014-12-08 18:45:16 +00001594 if (auto *F = dyn_cast<Function>(&Src))
Rafael Espindolae39cd5b2015-12-01 22:40:40 +00001595 return linkFunctionBody(cast<Function>(Dst), *F);
Rafael Espindolaef237112014-12-08 18:45:16 +00001596 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
Rafael Espindolae39cd5b2015-12-01 22:40:40 +00001597 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
Rafael Espindolaef237112014-12-08 18:45:16 +00001598 return false;
Tanya Lattnercbb91402011-10-11 00:24:54 +00001599 }
Rafael Espindolae39cd5b2015-12-01 22:40:40 +00001600 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
Rafael Espindolaef237112014-12-08 18:45:16 +00001601 return false;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001602}
Anton Korobeynikov26098882008-03-05 23:21:39 +00001603
Rafael Espindola18c89412014-10-27 02:35:46 +00001604/// Insert all of the named MDNodes in Src into the Dest module.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001605void ModuleLinker::linkNamedMDNodes() {
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001606 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1607 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
Bill Wendling66f02412012-02-11 11:38:06 +00001608 // Don't link module flags here. Do them separately.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001609 if (&NMD == SrcModFlags)
1610 continue;
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001611 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001612 // Add Src elements into Dest node.
Yaron Keren3bf3f1f2015-06-15 16:20:16 +00001613 for (const MDNode *op : NMD.operands())
Teresa Johnson83d03dd2015-11-15 14:50:14 +00001614 DestNMD->addOperand(MapMetadata(
1615 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1616 &TypeMap, &ValMaterializer));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001617 }
1618}
Bill Wendling66f02412012-02-11 11:38:06 +00001619
Rafael Espindola18c89412014-10-27 02:35:46 +00001620/// Merge the linker flags in Src into the Dest module.
Bill Wendling66f02412012-02-11 11:38:06 +00001621bool ModuleLinker::linkModuleFlagsMetadata() {
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001622 // If the source module has no module flags, we are done.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001623 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
Rafael Espindolae3a933a2015-12-01 20:11:43 +00001624 if (!SrcModFlags)
1625 return false;
Bill Wendling66f02412012-02-11 11:38:06 +00001626
Bill Wendling66f02412012-02-11 11:38:06 +00001627 // If the destination module doesn't have module flags yet, then just copy
1628 // over the source module's flags.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001629 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
Bill Wendling66f02412012-02-11 11:38:06 +00001630 if (DstModFlags->getNumOperands() == 0) {
1631 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1632 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1633
1634 return false;
1635 }
1636
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001637 // First build a map of the existing module flags and requirements.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001638 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
Rafael Espindolae3a933a2015-12-01 20:11:43 +00001639 SmallSetVector<MDNode *, 16> Requirements;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001640 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001641 MDNode *Op = DstModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001642 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001643 MDString *ID = cast<MDString>(Op->getOperand(1));
Bill Wendling66f02412012-02-11 11:38:06 +00001644
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001645 if (Behavior->getZExtValue() == Module::Require) {
1646 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1647 } else {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001648 Flags[ID] = std::make_pair(Op, I);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001649 }
Bill Wendling66f02412012-02-11 11:38:06 +00001650 }
1651
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001652 // Merge in the flags from the source module, and also collect its set of
1653 // requirements.
1654 bool HasErr = false;
1655 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001656 MDNode *SrcOp = SrcModFlags->getOperand(I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001657 ConstantInt *SrcBehavior =
1658 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001659 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001660 MDNode *DstOp;
1661 unsigned DstIndex;
1662 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001663 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
Bill Wendling66f02412012-02-11 11:38:06 +00001664
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001665 // If this is a requirement, add it and continue.
1666 if (SrcBehaviorValue == Module::Require) {
1667 // If the destination module does not already have this requirement, add
1668 // it.
1669 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1670 DstModFlags->addOperand(SrcOp);
1671 }
1672 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001673 }
1674
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001675 // If there is no existing flag with this ID, just add it.
1676 if (!DstOp) {
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001677 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001678 DstModFlags->addOperand(SrcOp);
1679 continue;
1680 }
1681
1682 // Otherwise, perform a merge.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001683 ConstantInt *DstBehavior =
1684 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001685 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1686
1687 // If either flag has override behavior, handle it first.
1688 if (DstBehaviorValue == Module::Override) {
1689 // Diagnose inconsistent flags which both have override behavior.
1690 if (SrcBehaviorValue == Module::Override &&
1691 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1692 HasErr |= emitError("linking module flags '" + ID->getString() +
1693 "': IDs have conflicting override values");
1694 }
1695 continue;
1696 } else if (SrcBehaviorValue == Module::Override) {
1697 // Update the destination flag to that of the source.
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001698 DstModFlags->setOperand(DstIndex, SrcOp);
1699 Flags[ID].first = SrcOp;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001700 continue;
1701 }
1702
1703 // Diagnose inconsistent merge behavior types.
1704 if (SrcBehaviorValue != DstBehaviorValue) {
1705 HasErr |= emitError("linking module flags '" + ID->getString() +
1706 "': IDs have conflicting behaviors");
1707 continue;
1708 }
1709
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001710 auto replaceDstValue = [&](MDNode *New) {
1711 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001712 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001713 DstModFlags->setOperand(DstIndex, Flag);
1714 Flags[ID].first = Flag;
1715 };
1716
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001717 // Perform the merge for standard behavior types.
1718 switch (SrcBehaviorValue) {
1719 case Module::Require:
Rafael Espindolae3a933a2015-12-01 20:11:43 +00001720 case Module::Override:
1721 llvm_unreachable("not possible");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001722 case Module::Error: {
1723 // Emit an error if the values differ.
1724 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1725 HasErr |= emitError("linking module flags '" + ID->getString() +
1726 "': IDs have conflicting values");
1727 }
1728 continue;
1729 }
1730 case Module::Warning: {
1731 // Emit a warning if the values differ.
1732 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001733 emitWarning("linking module flags '" + ID->getString() +
1734 "': IDs have conflicting values");
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001735 }
1736 continue;
1737 }
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001738 case Module::Append: {
1739 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1740 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001741 SmallVector<Metadata *, 8> MDs;
1742 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001743 MDs.append(DstValue->op_begin(), DstValue->op_end());
1744 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001745
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001746 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001747 break;
1748 }
1749 case Module::AppendUnique: {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001750 SmallSetVector<Metadata *, 16> Elts;
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001751 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1752 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001753 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1754 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001755
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001756 replaceDstValue(MDNode::get(DstM.getContext(),
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001757 makeArrayRef(Elts.begin(), Elts.end())));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001758 break;
1759 }
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001760 }
Bill Wendling66f02412012-02-11 11:38:06 +00001761 }
1762
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001763 // Check all of the requirements.
1764 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1765 MDNode *Requirement = Requirements[I];
1766 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001767 Metadata *ReqValue = Requirement->getOperand(1);
Bill Wendling66f02412012-02-11 11:38:06 +00001768
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001769 MDNode *Op = Flags[Flag].first;
Daniel Dunbar0ec72bb2013-01-16 18:39:23 +00001770 if (!Op || Op->getOperand(2) != ReqValue) {
1771 HasErr |= emitError("linking module flags '" + Flag->getString() +
1772 "': does not have the required value");
1773 continue;
Bill Wendling66f02412012-02-11 11:38:06 +00001774 }
1775 }
1776
1777 return HasErr;
1778}
Rafael Espindolaed6dc372014-05-09 14:39:25 +00001779
Akira Hatanakac43df512015-02-13 00:40:41 +00001780// This function returns true if the triples match.
1781static bool triplesMatch(const Triple &T0, const Triple &T1) {
1782 // If vendor is apple, ignore the version number.
1783 if (T0.getVendor() == Triple::Apple)
Rafael Espindolae3a933a2015-12-01 20:11:43 +00001784 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1785 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
Akira Hatanakac43df512015-02-13 00:40:41 +00001786
1787 return T0 == T1;
1788}
1789
1790// This function returns the merged triple.
Rafael Espindolae3a933a2015-12-01 20:11:43 +00001791static std::string mergeTriples(const Triple &SrcTriple,
1792 const Triple &DstTriple) {
Akira Hatanakac43df512015-02-13 00:40:41 +00001793 // If vendor is apple, pick the triple with the larger version number.
1794 if (SrcTriple.getVendor() == Triple::Apple)
1795 if (DstTriple.isOSVersionLT(SrcTriple))
1796 return SrcTriple.str();
1797
1798 return DstTriple.str();
1799}
1800
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001801bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1802 GlobalValue *DGV = getLinkedToGlobal(&GV);
1803
1804 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1805 return false;
1806
1807 if (DGV && !GV.hasLocalLinkage()) {
1808 GlobalValue::VisibilityTypes Visibility =
1809 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1810 DGV->setVisibility(Visibility);
1811 GV.setVisibility(Visibility);
1812 }
1813
1814 if (const Comdat *SC = GV.getComdat()) {
1815 bool LinkFromSrc;
1816 Comdat::SelectionKind SK;
1817 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1818 if (!LinkFromSrc) {
1819 DoNotLinkFromSource.insert(&GV);
1820 return false;
1821 }
1822 }
1823
1824 if (!DGV && !shouldOverrideFromSrc() &&
1825 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1826 GV.hasAvailableExternallyLinkage())) {
1827 return false;
1828 }
1829 MapValue(&GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1830 return HasError;
1831}
1832
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001833bool ModuleLinker::run() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001834 // Inherit the target data from the source module if the destination module
1835 // doesn't have one already.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001836 if (DstM.getDataLayout().isDefault())
1837 DstM.setDataLayout(SrcM.getDataLayout());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001838
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001839 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001840 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001841 SrcM.getModuleIdentifier() + "' is '" +
1842 SrcM.getDataLayoutStr() + "' whereas '" +
1843 DstM.getModuleIdentifier() + "' is '" +
1844 DstM.getDataLayoutStr() + "'\n");
Eli Benderskye17f3702014-02-06 18:01:56 +00001845 }
Akira Hatanakac43df512015-02-13 00:40:41 +00001846
1847 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001848 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1849 DstM.setTargetTriple(SrcM.getTargetTriple());
Akira Hatanakac43df512015-02-13 00:40:41 +00001850
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001851 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
Akira Hatanakac43df512015-02-13 00:40:41 +00001852
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001853 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolad12b4a32014-10-25 04:06:10 +00001854 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001855 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1856 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1857 DstM.getTargetTriple() + "'\n");
Akira Hatanakac43df512015-02-13 00:40:41 +00001858
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001859 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001860
1861 // Append the module inline asm string.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001862 if (!SrcM.getModuleInlineAsm().empty()) {
1863 if (DstM.getModuleInlineAsm().empty())
1864 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001865 else
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001866 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1867 SrcM.getModuleInlineAsm());
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001868 }
1869
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001870 // Loop over all of the linked values to compute type mappings.
1871 computeTypeMapping();
1872
David Majnemerdad0a642014-06-27 18:19:56 +00001873 ComdatsChosen.clear();
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001874 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +00001875 const Comdat &C = SMEC.getValue();
1876 if (ComdatsChosen.count(&C))
1877 continue;
1878 Comdat::SelectionKind SK;
1879 bool LinkFromSrc;
1880 if (getComdatResult(&C, SK, LinkFromSrc))
1881 return true;
1882 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1883 }
1884
Duncan P. N. Exon Smith09d84ad2014-08-12 16:46:37 +00001885 // Upgrade mismatched global arrays.
1886 upgradeMismatchedGlobals();
1887
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001888 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001889 if (const Comdat *SC = GV.getComdat())
1890 ComdatMembers[SC].push_back(&GV);
1891
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001892 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001893 if (const Comdat *SC = SF.getComdat())
1894 ComdatMembers[SC].push_back(&SF);
1895
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001896 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001897 if (const Comdat *SC = GA.getComdat())
1898 ComdatMembers[SC].push_back(&GA);
1899
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001900 // Insert all of the globals in src into the DstM module... without linking
1901 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001902 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001903 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001904 return true;
1905
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001906 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001907 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001908 return true;
1909
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001910 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +00001911 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001912 return true;
1913
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001914 for (const auto &Entry : DstM.getComdatSymbolTable()) {
Rafael Espindolabeadd562014-12-08 18:05:48 +00001915 const Comdat &C = Entry.getValue();
1916 if (C.getSelectionKind() == Comdat::Any)
1917 continue;
Rafael Espindola0e309fe2015-12-01 19:50:54 +00001918 const GlobalValue *GV = SrcM.getNamedValue(C.getName());
Peter Collingbourneea45d832015-06-22 21:46:51 +00001919 if (GV)
Duncan P. N. Exon Smith4fb46cb2015-08-03 17:09:38 +00001920 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
Rafael Espindolabeadd562014-12-08 18:05:48 +00001921 }
1922
Teresa Johnson10632932015-11-06 17:50:53 +00001923 // Note that we are done linking global value bodies. This prevents
1924 // metadata linking from creating new references.
1925 DoneLinkingBodies = true;
1926
Teresa Johnson189b2522015-11-06 17:50:48 +00001927 // Remap all of the named MDNodes in Src into the DstM module. We do this
1928 // after linking GlobalValues so that MDNodes that reference GlobalValues
1929 // are properly remapped.
1930 linkNamedMDNodes();
1931
1932 // Merge the module flags into the DstM module.
1933 if (linkModuleFlagsMetadata())
1934 return true;
1935
Anton Korobeynikov26098882008-03-05 23:21:39 +00001936 return false;
1937}
Reid Spencer361e5132004-11-12 20:37:43 +00001938
Rafael Espindola31ad4682014-12-03 22:36:37 +00001939Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1940 : ETypes(E), IsPacked(P) {}
1941
1942Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1943 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1944
1945bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1946 if (IsPacked != That.IsPacked)
1947 return false;
1948 if (ETypes != That.ETypes)
1949 return false;
1950 return true;
1951}
1952
1953bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1954 return !this->operator==(That);
1955}
1956
1957StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1958 return DenseMapInfo<StructType *>::getEmptyKey();
1959}
1960
1961StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1962 return DenseMapInfo<StructType *>::getTombstoneKey();
1963}
1964
1965unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1966 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1967 Key.IsPacked);
1968}
1969
1970unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1971 return getHashValue(KeyTy(ST));
1972}
1973
1974bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1975 const StructType *RHS) {
1976 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1977 return false;
1978 return LHS == KeyTy(RHS);
1979}
1980
1981bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1982 const StructType *RHS) {
1983 if (RHS == getEmptyKey())
1984 return LHS == getEmptyKey();
1985
1986 if (RHS == getTombstoneKey())
1987 return LHS == getTombstoneKey();
1988
1989 return KeyTy(LHS) == KeyTy(RHS);
1990}
1991
1992void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1993 assert(!Ty->isOpaque());
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00001994 NonOpaqueStructTypes.insert(Ty);
Rafael Espindola31ad4682014-12-03 22:36:37 +00001995}
1996
Rafael Espindolaa5b9e1c2015-03-06 00:50:21 +00001997void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1998 assert(!Ty->isOpaque());
1999 NonOpaqueStructTypes.insert(Ty);
2000 bool Removed = OpaqueStructTypes.erase(Ty);
2001 (void)Removed;
2002 assert(Removed);
2003}
2004
Rafael Espindola31ad4682014-12-03 22:36:37 +00002005void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
2006 assert(Ty->isOpaque());
2007 OpaqueStructTypes.insert(Ty);
2008}
2009
2010StructType *
2011Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
2012 bool IsPacked) {
2013 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
2014 auto I = NonOpaqueStructTypes.find_as(Key);
2015 if (I == NonOpaqueStructTypes.end())
2016 return nullptr;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00002017 return *I;
Rafael Espindola31ad4682014-12-03 22:36:37 +00002018}
2019
2020bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
2021 if (Ty->isOpaque())
2022 return OpaqueStructTypes.count(Ty);
2023 auto I = NonOpaqueStructTypes.find(Ty);
2024 if (I == NonOpaqueStructTypes.end())
2025 return false;
Benjamin Kramer3280a5d2014-12-06 19:22:54 +00002026 return *I == Ty;
Rafael Espindola31ad4682014-12-03 22:36:37 +00002027}
2028
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002029Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
2030 : Composite(M), DiagnosticHandler(DiagnosticHandler) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00002031 TypeFinder StructTypes;
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002032 StructTypes.run(M, true);
Rafael Espindola31ad4682014-12-03 22:36:37 +00002033 for (StructType *Ty : StructTypes) {
2034 if (Ty->isOpaque())
2035 IdentifiedStructTypes.addOpaque(Ty);
2036 else
2037 IdentifiedStructTypes.addNonOpaque(Ty);
2038 }
Rafael Espindolaaa9918a2013-05-04 05:05:18 +00002039}
Rafael Espindola3df61b72013-05-04 03:48:37 +00002040
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002041Linker::Linker(Module &M)
Rafael Espindola4dbdceb2015-12-01 18:46:19 +00002042 : Linker(M, [this](const DiagnosticInfo &DI) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002043 Composite.getContext().diagnose(DI);
Rafael Espindola4dbdceb2015-12-01 18:46:19 +00002044 }) {}
Rafael Espindola5cb9c822014-11-17 20:51:01 +00002045
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002046bool Linker::linkInModule(Module &Src, unsigned Flags,
Mehdi Amini8220e8a2015-11-23 01:59:16 +00002047 const FunctionInfoIndex *Index,
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +00002048 DenseSet<const GlobalValue *> *FuncToImport) {
Rafael Espindolaa4e85e32014-12-01 16:32:20 +00002049 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00002050 DiagnosticHandler, Flags, Index, FuncToImport);
Manman Rendab999d2015-01-20 19:24:59 +00002051 bool RetCode = TheLinker.run();
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002052 Composite.dropTriviallyDeadConstantArrays();
Manman Rendab999d2015-01-20 19:24:59 +00002053 return RetCode;
Rafael Espindola3df61b72013-05-04 03:48:37 +00002054}
2055
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002056//===----------------------------------------------------------------------===//
2057// LinkModules entrypoint.
2058//===----------------------------------------------------------------------===//
2059
Rafael Espindola18c89412014-10-27 02:35:46 +00002060/// This function links two modules together, with the resulting Dest module
2061/// modified to be the composite of the two input modules. If an error occurs,
2062/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
2063/// Upon failure, the Dest module could be in a modified state, and shouldn't be
2064/// relied on to be consistent.
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002065bool Linker::linkModules(Module &Dest, Module &Src,
Artem Belevich020d4fb2015-09-01 17:55:55 +00002066 DiagnosticHandlerFunction DiagnosticHandler,
2067 unsigned Flags) {
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002068 Linker L(Dest, DiagnosticHandler);
Artem Belevich020d4fb2015-09-01 17:55:55 +00002069 return L.linkInModule(Src, Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002070}
2071
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002072bool Linker::linkModules(Module &Dest, Module &Src, unsigned Flags) {
Rafael Espindola287f18b2013-05-04 04:08:02 +00002073 Linker L(Dest);
Artem Belevich020d4fb2015-09-01 17:55:55 +00002074 return L.linkInModule(Src, Flags);
Reid Spencer361e5132004-11-12 20:37:43 +00002075}
Bill Wendlinga3aeb982012-05-09 08:55:40 +00002076
2077//===----------------------------------------------------------------------===//
2078// C API.
2079//===----------------------------------------------------------------------===//
2080
2081LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Juergen Ributzkaa57d5882015-03-02 18:59:38 +00002082 LLVMLinkerMode Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002083 Module *D = unwrap(Dest);
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002084 std::string Message;
Rafael Espindola4160f5d2014-10-27 23:02:10 +00002085 raw_string_ostream Stream(Message);
2086 DiagnosticPrinterRawOStream DP(Stream);
2087
Rafael Espindola0e309fe2015-12-01 19:50:54 +00002088 LLVMBool Result = Linker::linkModules(
2089 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002090
Eli Benderskyff715e22015-06-12 23:26:42 +00002091 if (OutMessages && Result) {
2092 Stream.flush();
Rafael Espindola98ab63c2014-10-25 04:31:08 +00002093 *OutMessages = strdup(Message.c_str());
Eli Benderskyff715e22015-06-12 23:26:42 +00002094 }
Bill Wendlinga3aeb982012-05-09 08:55:40 +00002095 return Result;
2096}