Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1 | //===- lib/Linker/IRMover.cpp ---------------------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "llvm/Linker/IRMover.h" |
| 11 | #include "LinkDiagnosticInfo.h" |
| 12 | #include "llvm/ADT/SetVector.h" |
| 13 | #include "llvm/ADT/SmallString.h" |
| 14 | #include "llvm/ADT/Triple.h" |
| 15 | #include "llvm/IR/Constants.h" |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 16 | #include "llvm/IR/DebugInfo.h" |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 17 | #include "llvm/IR/DiagnosticPrinter.h" |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 18 | #include "llvm/IR/GVMaterializer.h" |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 19 | #include "llvm/IR/TypeFinder.h" |
| 20 | #include "llvm/Transforms/Utils/Cloning.h" |
| 21 | using namespace llvm; |
| 22 | |
| 23 | //===----------------------------------------------------------------------===// |
| 24 | // TypeMap implementation. |
| 25 | //===----------------------------------------------------------------------===// |
| 26 | |
| 27 | namespace { |
| 28 | class TypeMapTy : public ValueMapTypeRemapper { |
| 29 | /// This is a mapping from a source type to a destination type to use. |
| 30 | DenseMap<Type *, Type *> MappedTypes; |
| 31 | |
| 32 | /// When checking to see if two subgraphs are isomorphic, we speculatively |
| 33 | /// add types to MappedTypes, but keep track of them here in case we need to |
| 34 | /// roll back. |
| 35 | SmallVector<Type *, 16> SpeculativeTypes; |
| 36 | |
| 37 | SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes; |
| 38 | |
| 39 | /// This is a list of non-opaque structs in the source module that are mapped |
| 40 | /// to an opaque struct in the destination module. |
| 41 | SmallVector<StructType *, 16> SrcDefinitionsToResolve; |
| 42 | |
| 43 | /// This is the set of opaque types in the destination modules who are |
| 44 | /// getting a body from the source module. |
| 45 | SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes; |
| 46 | |
| 47 | public: |
| 48 | TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet) |
| 49 | : DstStructTypesSet(DstStructTypesSet) {} |
| 50 | |
| 51 | IRMover::IdentifiedStructTypeSet &DstStructTypesSet; |
| 52 | /// Indicate that the specified type in the destination module is conceptually |
| 53 | /// equivalent to the specified type in the source module. |
| 54 | void addTypeMapping(Type *DstTy, Type *SrcTy); |
| 55 | |
| 56 | /// Produce a body for an opaque type in the dest module from a type |
| 57 | /// definition in the source module. |
| 58 | void linkDefinedTypeBodies(); |
| 59 | |
| 60 | /// Return the mapped type to use for the specified input type from the |
| 61 | /// source module. |
| 62 | Type *get(Type *SrcTy); |
| 63 | Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited); |
| 64 | |
| 65 | void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes); |
| 66 | |
| 67 | FunctionType *get(FunctionType *T) { |
| 68 | return cast<FunctionType>(get((Type *)T)); |
| 69 | } |
| 70 | |
| 71 | private: |
| 72 | Type *remapType(Type *SrcTy) override { return get(SrcTy); } |
| 73 | |
| 74 | bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); |
| 75 | }; |
| 76 | } |
| 77 | |
| 78 | void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { |
| 79 | assert(SpeculativeTypes.empty()); |
| 80 | assert(SpeculativeDstOpaqueTypes.empty()); |
| 81 | |
| 82 | // Check to see if these types are recursively isomorphic and establish a |
| 83 | // mapping between them if so. |
| 84 | if (!areTypesIsomorphic(DstTy, SrcTy)) { |
| 85 | // Oops, they aren't isomorphic. Just discard this request by rolling out |
| 86 | // any speculative mappings we've established. |
| 87 | for (Type *Ty : SpeculativeTypes) |
| 88 | MappedTypes.erase(Ty); |
| 89 | |
| 90 | SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - |
| 91 | SpeculativeDstOpaqueTypes.size()); |
| 92 | for (StructType *Ty : SpeculativeDstOpaqueTypes) |
| 93 | DstResolvedOpaqueTypes.erase(Ty); |
| 94 | } else { |
| 95 | for (Type *Ty : SpeculativeTypes) |
| 96 | if (auto *STy = dyn_cast<StructType>(Ty)) |
| 97 | if (STy->hasName()) |
| 98 | STy->setName(""); |
| 99 | } |
| 100 | SpeculativeTypes.clear(); |
| 101 | SpeculativeDstOpaqueTypes.clear(); |
| 102 | } |
| 103 | |
| 104 | /// Recursively walk this pair of types, returning true if they are isomorphic, |
| 105 | /// false if they are not. |
| 106 | bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { |
| 107 | // Two types with differing kinds are clearly not isomorphic. |
| 108 | if (DstTy->getTypeID() != SrcTy->getTypeID()) |
| 109 | return false; |
| 110 | |
| 111 | // If we have an entry in the MappedTypes table, then we have our answer. |
| 112 | Type *&Entry = MappedTypes[SrcTy]; |
| 113 | if (Entry) |
| 114 | return Entry == DstTy; |
| 115 | |
| 116 | // Two identical types are clearly isomorphic. Remember this |
| 117 | // non-speculatively. |
| 118 | if (DstTy == SrcTy) { |
| 119 | Entry = DstTy; |
| 120 | return true; |
| 121 | } |
| 122 | |
| 123 | // Okay, we have two types with identical kinds that we haven't seen before. |
| 124 | |
| 125 | // If this is an opaque struct type, special case it. |
| 126 | if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { |
| 127 | // Mapping an opaque type to any struct, just keep the dest struct. |
| 128 | if (SSTy->isOpaque()) { |
| 129 | Entry = DstTy; |
| 130 | SpeculativeTypes.push_back(SrcTy); |
| 131 | return true; |
| 132 | } |
| 133 | |
| 134 | // Mapping a non-opaque source type to an opaque dest. If this is the first |
| 135 | // type that we're mapping onto this destination type then we succeed. Keep |
| 136 | // the dest, but fill it in later. If this is the second (different) type |
| 137 | // that we're trying to map onto the same opaque type then we fail. |
| 138 | if (cast<StructType>(DstTy)->isOpaque()) { |
| 139 | // We can only map one source type onto the opaque destination type. |
| 140 | if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) |
| 141 | return false; |
| 142 | SrcDefinitionsToResolve.push_back(SSTy); |
| 143 | SpeculativeTypes.push_back(SrcTy); |
| 144 | SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy)); |
| 145 | Entry = DstTy; |
| 146 | return true; |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // If the number of subtypes disagree between the two types, then we fail. |
| 151 | if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) |
| 152 | return false; |
| 153 | |
| 154 | // Fail if any of the extra properties (e.g. array size) of the type disagree. |
| 155 | if (isa<IntegerType>(DstTy)) |
| 156 | return false; // bitwidth disagrees. |
| 157 | if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { |
| 158 | if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) |
| 159 | return false; |
| 160 | |
| 161 | } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { |
| 162 | if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) |
| 163 | return false; |
| 164 | } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { |
| 165 | StructType *SSTy = cast<StructType>(SrcTy); |
| 166 | if (DSTy->isLiteral() != SSTy->isLiteral() || |
| 167 | DSTy->isPacked() != SSTy->isPacked()) |
| 168 | return false; |
| 169 | } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { |
| 170 | if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) |
| 171 | return false; |
| 172 | } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { |
| 173 | if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) |
| 174 | return false; |
| 175 | } |
| 176 | |
| 177 | // Otherwise, we speculate that these two types will line up and recursively |
| 178 | // check the subelements. |
| 179 | Entry = DstTy; |
| 180 | SpeculativeTypes.push_back(SrcTy); |
| 181 | |
| 182 | for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) |
| 183 | if (!areTypesIsomorphic(DstTy->getContainedType(I), |
| 184 | SrcTy->getContainedType(I))) |
| 185 | return false; |
| 186 | |
| 187 | // If everything seems to have lined up, then everything is great. |
| 188 | return true; |
| 189 | } |
| 190 | |
| 191 | void TypeMapTy::linkDefinedTypeBodies() { |
| 192 | SmallVector<Type *, 16> Elements; |
| 193 | for (StructType *SrcSTy : SrcDefinitionsToResolve) { |
| 194 | StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); |
| 195 | assert(DstSTy->isOpaque()); |
| 196 | |
| 197 | // Map the body of the source type over to a new body for the dest type. |
| 198 | Elements.resize(SrcSTy->getNumElements()); |
| 199 | for (unsigned I = 0, E = Elements.size(); I != E; ++I) |
| 200 | Elements[I] = get(SrcSTy->getElementType(I)); |
| 201 | |
| 202 | DstSTy->setBody(Elements, SrcSTy->isPacked()); |
| 203 | DstStructTypesSet.switchToNonOpaque(DstSTy); |
| 204 | } |
| 205 | SrcDefinitionsToResolve.clear(); |
| 206 | DstResolvedOpaqueTypes.clear(); |
| 207 | } |
| 208 | |
| 209 | void TypeMapTy::finishType(StructType *DTy, StructType *STy, |
| 210 | ArrayRef<Type *> ETypes) { |
| 211 | DTy->setBody(ETypes, STy->isPacked()); |
| 212 | |
| 213 | // Steal STy's name. |
| 214 | if (STy->hasName()) { |
| 215 | SmallString<16> TmpName = STy->getName(); |
| 216 | STy->setName(""); |
| 217 | DTy->setName(TmpName); |
| 218 | } |
| 219 | |
| 220 | DstStructTypesSet.addNonOpaque(DTy); |
| 221 | } |
| 222 | |
| 223 | Type *TypeMapTy::get(Type *Ty) { |
| 224 | SmallPtrSet<StructType *, 8> Visited; |
| 225 | return get(Ty, Visited); |
| 226 | } |
| 227 | |
| 228 | Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) { |
| 229 | // If we already have an entry for this type, return it. |
| 230 | Type **Entry = &MappedTypes[Ty]; |
| 231 | if (*Entry) |
| 232 | return *Entry; |
| 233 | |
| 234 | // These are types that LLVM itself will unique. |
| 235 | bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral(); |
| 236 | |
| 237 | #ifndef NDEBUG |
| 238 | if (!IsUniqued) { |
| 239 | for (auto &Pair : MappedTypes) { |
| 240 | assert(!(Pair.first != Ty && Pair.second == Ty) && |
| 241 | "mapping to a source type"); |
| 242 | } |
| 243 | } |
| 244 | #endif |
| 245 | |
| 246 | if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) { |
| 247 | StructType *DTy = StructType::create(Ty->getContext()); |
| 248 | return *Entry = DTy; |
| 249 | } |
| 250 | |
| 251 | // If this is not a recursive type, then just map all of the elements and |
| 252 | // then rebuild the type from inside out. |
| 253 | SmallVector<Type *, 4> ElementTypes; |
| 254 | |
| 255 | // If there are no element types to map, then the type is itself. This is |
| 256 | // true for the anonymous {} struct, things like 'float', integers, etc. |
| 257 | if (Ty->getNumContainedTypes() == 0 && IsUniqued) |
| 258 | return *Entry = Ty; |
| 259 | |
| 260 | // Remap all of the elements, keeping track of whether any of them change. |
| 261 | bool AnyChange = false; |
| 262 | ElementTypes.resize(Ty->getNumContainedTypes()); |
| 263 | for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { |
| 264 | ElementTypes[I] = get(Ty->getContainedType(I), Visited); |
| 265 | AnyChange |= ElementTypes[I] != Ty->getContainedType(I); |
| 266 | } |
| 267 | |
| 268 | // If we found our type while recursively processing stuff, just use it. |
| 269 | Entry = &MappedTypes[Ty]; |
| 270 | if (*Entry) { |
| 271 | if (auto *DTy = dyn_cast<StructType>(*Entry)) { |
| 272 | if (DTy->isOpaque()) { |
| 273 | auto *STy = cast<StructType>(Ty); |
| 274 | finishType(DTy, STy, ElementTypes); |
| 275 | } |
| 276 | } |
| 277 | return *Entry; |
| 278 | } |
| 279 | |
| 280 | // If all of the element types mapped directly over and the type is not |
| 281 | // a nomed struct, then the type is usable as-is. |
| 282 | if (!AnyChange && IsUniqued) |
| 283 | return *Entry = Ty; |
| 284 | |
| 285 | // Otherwise, rebuild a modified type. |
| 286 | switch (Ty->getTypeID()) { |
| 287 | default: |
| 288 | llvm_unreachable("unknown derived type to remap"); |
| 289 | case Type::ArrayTyID: |
| 290 | return *Entry = ArrayType::get(ElementTypes[0], |
| 291 | cast<ArrayType>(Ty)->getNumElements()); |
| 292 | case Type::VectorTyID: |
| 293 | return *Entry = VectorType::get(ElementTypes[0], |
| 294 | cast<VectorType>(Ty)->getNumElements()); |
| 295 | case Type::PointerTyID: |
| 296 | return *Entry = PointerType::get(ElementTypes[0], |
| 297 | cast<PointerType>(Ty)->getAddressSpace()); |
| 298 | case Type::FunctionTyID: |
| 299 | return *Entry = FunctionType::get(ElementTypes[0], |
| 300 | makeArrayRef(ElementTypes).slice(1), |
| 301 | cast<FunctionType>(Ty)->isVarArg()); |
| 302 | case Type::StructTyID: { |
| 303 | auto *STy = cast<StructType>(Ty); |
| 304 | bool IsPacked = STy->isPacked(); |
| 305 | if (IsUniqued) |
| 306 | return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked); |
| 307 | |
| 308 | // If the type is opaque, we can just use it directly. |
| 309 | if (STy->isOpaque()) { |
| 310 | DstStructTypesSet.addOpaque(STy); |
| 311 | return *Entry = Ty; |
| 312 | } |
| 313 | |
| 314 | if (StructType *OldT = |
| 315 | DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) { |
| 316 | STy->setName(""); |
| 317 | return *Entry = OldT; |
| 318 | } |
| 319 | |
| 320 | if (!AnyChange) { |
| 321 | DstStructTypesSet.addNonOpaque(STy); |
| 322 | return *Entry = Ty; |
| 323 | } |
| 324 | |
| 325 | StructType *DTy = StructType::create(Ty->getContext()); |
| 326 | finishType(DTy, STy, ElementTypes); |
| 327 | return *Entry = DTy; |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, |
| 333 | const Twine &Msg) |
| 334 | : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} |
| 335 | void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } |
| 336 | |
| 337 | //===----------------------------------------------------------------------===// |
Teresa Johnson | bef5436 | 2015-12-18 19:28:59 +0000 | [diff] [blame] | 338 | // IRLinker implementation. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 339 | //===----------------------------------------------------------------------===// |
| 340 | |
| 341 | namespace { |
| 342 | class IRLinker; |
| 343 | |
| 344 | /// Creates prototypes for functions that are lazily linked on the fly. This |
| 345 | /// speeds up linking for modules with many/ lazily linked functions of which |
| 346 | /// few get used. |
| 347 | class GlobalValueMaterializer final : public ValueMaterializer { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 348 | IRLinker &TheIRLinker; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 349 | |
| 350 | public: |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 351 | GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {} |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 352 | Value *materializeDeclFor(Value *V) override; |
| 353 | void materializeInitFor(GlobalValue *New, GlobalValue *Old) override; |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 354 | Metadata *mapTemporaryMetadata(Metadata *MD) override; |
| 355 | void replaceTemporaryMetadata(const Metadata *OrigMD, |
| 356 | Metadata *NewMD) override; |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 357 | bool isMetadataNeeded(Metadata *MD) override; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 358 | }; |
| 359 | |
| 360 | class LocalValueMaterializer final : public ValueMaterializer { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 361 | IRLinker &TheIRLinker; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 362 | |
| 363 | public: |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 364 | LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {} |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 365 | Value *materializeDeclFor(Value *V) override; |
| 366 | void materializeInitFor(GlobalValue *New, GlobalValue *Old) override; |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 367 | Metadata *mapTemporaryMetadata(Metadata *MD) override; |
| 368 | void replaceTemporaryMetadata(const Metadata *OrigMD, |
| 369 | Metadata *NewMD) override; |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 370 | bool isMetadataNeeded(Metadata *MD) override; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 371 | }; |
| 372 | |
| 373 | /// This is responsible for keeping track of the state used for moving data |
| 374 | /// from SrcM to DstM. |
| 375 | class IRLinker { |
| 376 | Module &DstM; |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 377 | std::unique_ptr<Module> SrcM; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 378 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 379 | /// See IRMover::move(). |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 380 | std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor; |
| 381 | |
| 382 | TypeMapTy TypeMap; |
| 383 | GlobalValueMaterializer GValMaterializer; |
| 384 | LocalValueMaterializer LValMaterializer; |
| 385 | |
| 386 | /// Mapping of values from what they used to be in Src, to what they are now |
| 387 | /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead |
| 388 | /// due to the use of Value handles which the Linker doesn't actually need, |
| 389 | /// but this allows us to reuse the ValueMapper code. |
| 390 | ValueToValueMapTy ValueMap; |
| 391 | ValueToValueMapTy AliasValueMap; |
| 392 | |
| 393 | DenseSet<GlobalValue *> ValuesToLink; |
| 394 | std::vector<GlobalValue *> Worklist; |
| 395 | |
| 396 | void maybeAdd(GlobalValue *GV) { |
| 397 | if (ValuesToLink.insert(GV).second) |
| 398 | Worklist.push_back(GV); |
| 399 | } |
| 400 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 401 | /// Set to true when all global value body linking is complete (including |
| 402 | /// lazy linking). Used to prevent metadata linking from creating new |
| 403 | /// references. |
| 404 | bool DoneLinkingBodies = false; |
| 405 | |
| 406 | bool HasError = false; |
| 407 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 408 | /// Flag indicating that we are just linking metadata (after function |
| 409 | /// importing). |
| 410 | bool IsMetadataLinkingPostpass; |
| 411 | |
| 412 | /// Flags to pass to value mapper invocations. |
| 413 | RemapFlags ValueMapperFlags = RF_MoveDistinctMDs; |
| 414 | |
| 415 | /// Association between metadata values created during bitcode parsing and |
| 416 | /// the value id. Used to correlate temporary metadata created during |
| 417 | /// function importing with the final metadata parsed during the subsequent |
| 418 | /// metadata linking postpass. |
Teresa Johnson | 61b406e | 2015-12-29 23:00:22 +0000 | [diff] [blame] | 419 | DenseMap<const Metadata *, unsigned> MetadataToIDs; |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 420 | |
| 421 | /// Association between metadata value id and temporary metadata that |
| 422 | /// remains unmapped after function importing. Saved during function |
| 423 | /// importing and consumed during the metadata linking postpass. |
| 424 | DenseMap<unsigned, MDNode *> *ValIDToTempMDMap; |
| 425 | |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 426 | /// Set of subprogram metadata that does not need to be linked into the |
| 427 | /// destination module, because the functions were not imported directly |
| 428 | /// or via an inlined body in an imported function. |
| 429 | SmallPtrSet<const Metadata *, 16> UnneededSubprograms; |
| 430 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 431 | /// Handles cloning of a global values from the source module into |
| 432 | /// the destination module, including setting the attributes and visibility. |
| 433 | GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition); |
| 434 | |
| 435 | /// Helper method for setting a message and returning an error code. |
| 436 | bool emitError(const Twine &Message) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 437 | SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 438 | HasError = true; |
| 439 | return true; |
| 440 | } |
| 441 | |
| 442 | void emitWarning(const Twine &Message) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 443 | SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 444 | } |
| 445 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 446 | /// Check whether we should be linking metadata from the source module. |
| 447 | bool shouldLinkMetadata() { |
| 448 | // ValIDToTempMDMap will be non-null when we are importing or otherwise want |
| 449 | // to link metadata lazily, and then when linking the metadata. |
| 450 | // We only want to return true for the former case. |
| 451 | return ValIDToTempMDMap == nullptr || IsMetadataLinkingPostpass; |
| 452 | } |
| 453 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 454 | /// Given a global in the source module, return the global in the |
| 455 | /// destination module that is being linked to, if any. |
| 456 | GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { |
| 457 | // If the source has no name it can't link. If it has local linkage, |
| 458 | // there is no name match-up going on. |
| 459 | if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) |
| 460 | return nullptr; |
| 461 | |
| 462 | // Otherwise see if we have a match in the destination module's symtab. |
| 463 | GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName()); |
| 464 | if (!DGV) |
| 465 | return nullptr; |
| 466 | |
| 467 | // If we found a global with the same name in the dest module, but it has |
| 468 | // internal linkage, we are really not doing any linkage here. |
| 469 | if (DGV->hasLocalLinkage()) |
| 470 | return nullptr; |
| 471 | |
| 472 | // Otherwise, we do in fact link to the destination global. |
| 473 | return DGV; |
| 474 | } |
| 475 | |
| 476 | void computeTypeMapping(); |
| 477 | |
| 478 | Constant *linkAppendingVarProto(GlobalVariable *DstGV, |
| 479 | const GlobalVariable *SrcGV); |
| 480 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 481 | /// Given the GlobaValue \p SGV in the source module, and the matching |
| 482 | /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV |
| 483 | /// into the destination module. |
| 484 | /// |
| 485 | /// Note this code may call the client-provided \p AddLazyFor. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 486 | bool shouldLink(GlobalValue *DGV, GlobalValue &SGV); |
| 487 | Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias); |
| 488 | |
| 489 | bool linkModuleFlagsMetadata(); |
| 490 | |
| 491 | void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src); |
| 492 | bool linkFunctionBody(Function &Dst, Function &Src); |
| 493 | void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src); |
| 494 | bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src); |
| 495 | |
| 496 | /// Functions that take care of cloning a specific global value type |
| 497 | /// into the destination module. |
| 498 | GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar); |
| 499 | Function *copyFunctionProto(const Function *SF); |
| 500 | GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA); |
| 501 | |
| 502 | void linkNamedMDNodes(); |
| 503 | |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 504 | /// Populate the UnneededSubprograms set with the DISubprogram metadata |
| 505 | /// from the source module that we don't need to link into the dest module, |
| 506 | /// because the functions were not imported directly or via an inlined body |
| 507 | /// in an imported function. |
Rafael Espindola | 394524d | 2016-01-21 00:00:53 +0000 | [diff] [blame] | 508 | void findNeededSubprograms(); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 509 | |
Teresa Johnson | 71d12d2 | 2016-01-25 22:04:56 +0000 | [diff] [blame] | 510 | /// Recursive helper for findNeededSubprograms to locate any DISubprogram |
| 511 | /// reached from the given Node, marking any found as needed. |
| 512 | void findReachedSubprograms(const MDNode *Node, |
| 513 | SmallPtrSet<const MDNode *, 16> &Visited); |
| 514 | |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 515 | /// The value mapper leaves nulls in the list of subprograms for any |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 516 | /// in the UnneededSubprograms map. Strip those out of the mapped |
| 517 | /// compile unit. |
| 518 | void stripNullSubprograms(DICompileUnit *CU); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 519 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 520 | public: |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 521 | IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set, |
| 522 | std::unique_ptr<Module> SrcM, ArrayRef<GlobalValue *> ValuesToLink, |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 523 | std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor, |
| 524 | DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr, |
| 525 | bool IsMetadataLinkingPostpass = false) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 526 | : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set), |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 527 | GValMaterializer(*this), LValMaterializer(*this), |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 528 | IsMetadataLinkingPostpass(IsMetadataLinkingPostpass), |
| 529 | ValIDToTempMDMap(ValIDToTempMDMap) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 530 | for (GlobalValue *GV : ValuesToLink) |
| 531 | maybeAdd(GV); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 532 | |
| 533 | // If appropriate, tell the value mapper that it can expect to see |
| 534 | // temporary metadata. |
| 535 | if (!shouldLinkMetadata()) |
| 536 | ValueMapperFlags = ValueMapperFlags | RF_HaveUnmaterializedMetadata; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 537 | } |
| 538 | |
Teresa Johnson | cc42857 | 2015-12-30 19:32:24 +0000 | [diff] [blame] | 539 | ~IRLinker() { |
| 540 | // In the case where we are not linking metadata, we unset the CanReplace |
| 541 | // flag on all temporary metadata in the MetadataToIDs map to ensure |
| 542 | // none was replaced while being a map key. Now that we are destructing |
| 543 | // the map, set the flag back to true, so that it is replaceable during |
| 544 | // metadata linking. |
| 545 | if (!shouldLinkMetadata()) { |
| 546 | for (auto MDI : MetadataToIDs) { |
| 547 | Metadata *MD = const_cast<Metadata *>(MDI.first); |
| 548 | MDNode *Node = dyn_cast<MDNode>(MD); |
| 549 | assert((Node && Node->isTemporary()) && |
| 550 | "Found non-temp metadata in map when not linking metadata"); |
| 551 | Node->setCanReplace(true); |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 556 | bool run(); |
| 557 | Value *materializeDeclFor(Value *V, bool ForAlias); |
| 558 | void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 559 | |
| 560 | /// Save the mapping between the given temporary metadata and its metadata |
| 561 | /// value id. Used to support metadata linking as a postpass for function |
| 562 | /// importing. |
| 563 | Metadata *mapTemporaryMetadata(Metadata *MD); |
| 564 | |
| 565 | /// Replace any temporary metadata saved for the source metadata's id with |
| 566 | /// the new non-temporary metadata. Used when metadata linking as a postpass |
| 567 | /// for function importing. |
| 568 | void replaceTemporaryMetadata(const Metadata *OrigMD, Metadata *NewMD); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 569 | |
| 570 | /// Indicates whether we need to map the given metadata into the destination |
| 571 | /// module. Used to prevent linking of metadata only needed by functions not |
| 572 | /// linked into the dest module. |
| 573 | bool isMetadataNeeded(Metadata *MD); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 574 | }; |
| 575 | } |
| 576 | |
| 577 | /// The LLVM SymbolTable class autorenames globals that conflict in the symbol |
| 578 | /// table. This is good for all clients except for us. Go through the trouble |
| 579 | /// to force this back. |
| 580 | static void forceRenaming(GlobalValue *GV, StringRef Name) { |
| 581 | // If the global doesn't force its name or if it already has the right name, |
| 582 | // there is nothing for us to do. |
| 583 | if (GV->hasLocalLinkage() || GV->getName() == Name) |
| 584 | return; |
| 585 | |
| 586 | Module *M = GV->getParent(); |
| 587 | |
| 588 | // If there is a conflict, rename the conflict. |
| 589 | if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { |
| 590 | GV->takeName(ConflictGV); |
| 591 | ConflictGV->setName(Name); // This will cause ConflictGV to get renamed |
| 592 | assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); |
| 593 | } else { |
| 594 | GV->setName(Name); // Force the name back |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | Value *GlobalValueMaterializer::materializeDeclFor(Value *V) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 599 | return TheIRLinker.materializeDeclFor(V, false); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 600 | } |
| 601 | |
| 602 | void GlobalValueMaterializer::materializeInitFor(GlobalValue *New, |
| 603 | GlobalValue *Old) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 604 | TheIRLinker.materializeInitFor(New, Old, false); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 605 | } |
| 606 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 607 | Metadata *GlobalValueMaterializer::mapTemporaryMetadata(Metadata *MD) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 608 | return TheIRLinker.mapTemporaryMetadata(MD); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 609 | } |
| 610 | |
| 611 | void GlobalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD, |
| 612 | Metadata *NewMD) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 613 | TheIRLinker.replaceTemporaryMetadata(OrigMD, NewMD); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 614 | } |
| 615 | |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 616 | bool GlobalValueMaterializer::isMetadataNeeded(Metadata *MD) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 617 | return TheIRLinker.isMetadataNeeded(MD); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 618 | } |
| 619 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 620 | Value *LocalValueMaterializer::materializeDeclFor(Value *V) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 621 | return TheIRLinker.materializeDeclFor(V, true); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 622 | } |
| 623 | |
| 624 | void LocalValueMaterializer::materializeInitFor(GlobalValue *New, |
| 625 | GlobalValue *Old) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 626 | TheIRLinker.materializeInitFor(New, Old, true); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 627 | } |
| 628 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 629 | Metadata *LocalValueMaterializer::mapTemporaryMetadata(Metadata *MD) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 630 | return TheIRLinker.mapTemporaryMetadata(MD); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 631 | } |
| 632 | |
| 633 | void LocalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD, |
| 634 | Metadata *NewMD) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 635 | TheIRLinker.replaceTemporaryMetadata(OrigMD, NewMD); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 636 | } |
| 637 | |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 638 | bool LocalValueMaterializer::isMetadataNeeded(Metadata *MD) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 639 | return TheIRLinker.isMetadataNeeded(MD); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 640 | } |
| 641 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 642 | Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) { |
| 643 | auto *SGV = dyn_cast<GlobalValue>(V); |
| 644 | if (!SGV) |
| 645 | return nullptr; |
| 646 | |
| 647 | return linkGlobalValueProto(SGV, ForAlias); |
| 648 | } |
| 649 | |
| 650 | void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old, |
| 651 | bool ForAlias) { |
| 652 | // If we already created the body, just return. |
| 653 | if (auto *F = dyn_cast<Function>(New)) { |
| 654 | if (!F->isDeclaration()) |
| 655 | return; |
| 656 | } else if (auto *V = dyn_cast<GlobalVariable>(New)) { |
| 657 | if (V->hasInitializer()) |
| 658 | return; |
| 659 | } else { |
| 660 | auto *A = cast<GlobalAlias>(New); |
| 661 | if (A->getAliasee()) |
| 662 | return; |
| 663 | } |
| 664 | |
| 665 | if (ForAlias || shouldLink(New, *Old)) |
| 666 | linkGlobalValueBody(*New, *Old); |
| 667 | } |
| 668 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 669 | Metadata *IRLinker::mapTemporaryMetadata(Metadata *MD) { |
| 670 | if (!ValIDToTempMDMap) |
| 671 | return nullptr; |
| 672 | // If this temporary metadata has a value id recorded during function |
| 673 | // parsing, record that in the ValIDToTempMDMap if one was provided. |
Teresa Johnson | 6f508af | 2016-01-21 16:46:40 +0000 | [diff] [blame] | 674 | auto I = MetadataToIDs.find(MD); |
Teresa Johnson | f5aa64f | 2016-01-21 17:16:53 +0000 | [diff] [blame] | 675 | if (I == MetadataToIDs.end()) |
| 676 | return nullptr; |
| 677 | unsigned Idx = I->second; |
| 678 | MDNode *Node = cast<MDNode>(MD); |
| 679 | assert(Node->isTemporary()); |
| 680 | // If we created a temp MD when importing a different function from |
| 681 | // this module, reuse the same temporary metadata. |
| 682 | auto IterBool = ValIDToTempMDMap->insert(std::make_pair(Idx, Node)); |
| 683 | return IterBool.first->second; |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 684 | } |
| 685 | |
| 686 | void IRLinker::replaceTemporaryMetadata(const Metadata *OrigMD, |
| 687 | Metadata *NewMD) { |
| 688 | if (!ValIDToTempMDMap) |
| 689 | return; |
| 690 | #ifndef NDEBUG |
| 691 | auto *N = dyn_cast_or_null<MDNode>(NewMD); |
| 692 | assert(!N || !N->isTemporary()); |
| 693 | #endif |
| 694 | // If a mapping between metadata value ids and temporary metadata |
| 695 | // created during function importing was provided, and the source |
| 696 | // metadata has a value id recorded during metadata parsing, replace |
| 697 | // the temporary metadata with the final mapped metadata now. |
Teresa Johnson | 6f508af | 2016-01-21 16:46:40 +0000 | [diff] [blame] | 698 | auto I = MetadataToIDs.find(OrigMD); |
Teresa Johnson | f5aa64f | 2016-01-21 17:16:53 +0000 | [diff] [blame] | 699 | if (I == MetadataToIDs.end()) |
| 700 | return; |
| 701 | unsigned Idx = I->second; |
| 702 | auto VI = ValIDToTempMDMap->find(Idx); |
| 703 | // Nothing to do if we didn't need to create a temporary metadata during |
| 704 | // function importing. |
| 705 | if (VI == ValIDToTempMDMap->end()) |
| 706 | return; |
| 707 | MDNode *TempMD = VI->second; |
| 708 | TempMD->replaceAllUsesWith(NewMD); |
| 709 | MDNode::deleteTemporary(TempMD); |
| 710 | ValIDToTempMDMap->erase(VI); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 711 | } |
| 712 | |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 713 | bool IRLinker::isMetadataNeeded(Metadata *MD) { |
| 714 | // Currently only DISubprogram metadata is marked as being unneeded. |
| 715 | if (UnneededSubprograms.empty()) |
| 716 | return true; |
| 717 | MDNode *Node = dyn_cast<MDNode>(MD); |
| 718 | if (!Node) |
| 719 | return true; |
| 720 | DISubprogram *SP = getDISubprogram(Node); |
| 721 | if (!SP) |
| 722 | return true; |
| 723 | return !UnneededSubprograms.count(SP); |
| 724 | } |
| 725 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 726 | /// Loop through the global variables in the src module and merge them into the |
| 727 | /// dest module. |
| 728 | GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) { |
| 729 | // No linking to be performed or linking from the source: simply create an |
| 730 | // identical version of the symbol over in the dest module... the |
| 731 | // initializer will be filled in later by LinkGlobalInits. |
| 732 | GlobalVariable *NewDGV = |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 733 | new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()), |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 734 | SGVar->isConstant(), GlobalValue::ExternalLinkage, |
| 735 | /*init*/ nullptr, SGVar->getName(), |
| 736 | /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), |
| 737 | SGVar->getType()->getAddressSpace()); |
| 738 | NewDGV->setAlignment(SGVar->getAlignment()); |
| 739 | return NewDGV; |
| 740 | } |
| 741 | |
| 742 | /// Link the function in the source module into the destination module if |
| 743 | /// needed, setting up mapping information. |
| 744 | Function *IRLinker::copyFunctionProto(const Function *SF) { |
| 745 | // If there is no linkage to be performed or we are linking from the source, |
| 746 | // bring SF over. |
| 747 | return Function::Create(TypeMap.get(SF->getFunctionType()), |
| 748 | GlobalValue::ExternalLinkage, SF->getName(), &DstM); |
| 749 | } |
| 750 | |
| 751 | /// Set up prototypes for any aliases that come over from the source module. |
| 752 | GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) { |
| 753 | // If there is no linkage to be performed or we're linking from the source, |
| 754 | // bring over SGA. |
| 755 | auto *Ty = TypeMap.get(SGA->getValueType()); |
| 756 | return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(), |
| 757 | GlobalValue::ExternalLinkage, SGA->getName(), |
| 758 | &DstM); |
| 759 | } |
| 760 | |
| 761 | GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV, |
| 762 | bool ForDefinition) { |
| 763 | GlobalValue *NewGV; |
| 764 | if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { |
| 765 | NewGV = copyGlobalVariableProto(SGVar); |
| 766 | } else if (auto *SF = dyn_cast<Function>(SGV)) { |
| 767 | NewGV = copyFunctionProto(SF); |
| 768 | } else { |
| 769 | if (ForDefinition) |
| 770 | NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV)); |
| 771 | else |
| 772 | NewGV = new GlobalVariable( |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 773 | DstM, TypeMap.get(SGV->getValueType()), |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 774 | /*isConstant*/ false, GlobalValue::ExternalLinkage, |
| 775 | /*init*/ nullptr, SGV->getName(), |
| 776 | /*insertbefore*/ nullptr, SGV->getThreadLocalMode(), |
| 777 | SGV->getType()->getAddressSpace()); |
| 778 | } |
| 779 | |
| 780 | if (ForDefinition) |
| 781 | NewGV->setLinkage(SGV->getLinkage()); |
| 782 | else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() || |
| 783 | SGV->hasLinkOnceLinkage()) |
| 784 | NewGV->setLinkage(GlobalValue::ExternalWeakLinkage); |
| 785 | |
| 786 | NewGV->copyAttributesFrom(SGV); |
Teresa Johnson | 5fe4005 | 2016-01-12 00:24:24 +0000 | [diff] [blame] | 787 | |
| 788 | // Remove these copied constants in case this stays a declaration, since |
| 789 | // they point to the source module. If the def is linked the values will |
| 790 | // be mapped in during linkFunctionBody. |
| 791 | if (auto *NewF = dyn_cast<Function>(NewGV)) { |
| 792 | NewF->setPersonalityFn(nullptr); |
| 793 | NewF->setPrefixData(nullptr); |
| 794 | NewF->setPrologueData(nullptr); |
| 795 | } |
| 796 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 797 | return NewGV; |
| 798 | } |
| 799 | |
| 800 | /// Loop over all of the linked values to compute type mappings. For example, |
| 801 | /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct |
| 802 | /// types 'Foo' but one got renamed when the module was loaded into the same |
| 803 | /// LLVMContext. |
| 804 | void IRLinker::computeTypeMapping() { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 805 | for (GlobalValue &SGV : SrcM->globals()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 806 | GlobalValue *DGV = getLinkedToGlobal(&SGV); |
| 807 | if (!DGV) |
| 808 | continue; |
| 809 | |
| 810 | if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { |
| 811 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 812 | continue; |
| 813 | } |
| 814 | |
| 815 | // Unify the element type of appending arrays. |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 816 | ArrayType *DAT = cast<ArrayType>(DGV->getValueType()); |
| 817 | ArrayType *SAT = cast<ArrayType>(SGV.getValueType()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 818 | TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); |
| 819 | } |
| 820 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 821 | for (GlobalValue &SGV : *SrcM) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 822 | if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) |
| 823 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 824 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 825 | for (GlobalValue &SGV : SrcM->aliases()) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 826 | if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) |
| 827 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 828 | |
| 829 | // Incorporate types by name, scanning all the types in the source module. |
| 830 | // At this point, the destination module may have a type "%foo = { i32 }" for |
| 831 | // example. When the source module got loaded into the same LLVMContext, if |
| 832 | // it had the same type, it would have been renamed to "%foo.42 = { i32 }". |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 833 | std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 834 | for (StructType *ST : Types) { |
| 835 | if (!ST->hasName()) |
| 836 | continue; |
| 837 | |
| 838 | // Check to see if there is a dot in the name followed by a digit. |
| 839 | size_t DotPos = ST->getName().rfind('.'); |
| 840 | if (DotPos == 0 || DotPos == StringRef::npos || |
| 841 | ST->getName().back() == '.' || |
| 842 | !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1]))) |
| 843 | continue; |
| 844 | |
| 845 | // Check to see if the destination module has a struct with the prefix name. |
| 846 | StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos)); |
| 847 | if (!DST) |
| 848 | continue; |
| 849 | |
| 850 | // Don't use it if this actually came from the source module. They're in |
| 851 | // the same LLVMContext after all. Also don't use it unless the type is |
| 852 | // actually used in the destination module. This can happen in situations |
| 853 | // like this: |
| 854 | // |
| 855 | // Module A Module B |
| 856 | // -------- -------- |
| 857 | // %Z = type { %A } %B = type { %C.1 } |
| 858 | // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } |
| 859 | // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } |
| 860 | // %C = type { i8* } %B.3 = type { %C.1 } |
| 861 | // |
| 862 | // When we link Module B with Module A, the '%B' in Module B is |
| 863 | // used. However, that would then use '%C.1'. But when we process '%C.1', |
| 864 | // we prefer to take the '%C' version. So we are then left with both |
| 865 | // '%C.1' and '%C' being used for the same types. This leads to some |
| 866 | // variables using one type and some using the other. |
| 867 | if (TypeMap.DstStructTypesSet.hasType(DST)) |
| 868 | TypeMap.addTypeMapping(DST, ST); |
| 869 | } |
| 870 | |
| 871 | // Now that we have discovered all of the type equivalences, get a body for |
| 872 | // any 'opaque' types in the dest module that are now resolved. |
| 873 | TypeMap.linkDefinedTypeBodies(); |
| 874 | } |
| 875 | |
| 876 | static void getArrayElements(const Constant *C, |
| 877 | SmallVectorImpl<Constant *> &Dest) { |
| 878 | unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); |
| 879 | |
| 880 | for (unsigned i = 0; i != NumElements; ++i) |
| 881 | Dest.push_back(C->getAggregateElement(i)); |
| 882 | } |
| 883 | |
| 884 | /// If there were any appending global variables, link them together now. |
| 885 | /// Return true on error. |
| 886 | Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV, |
| 887 | const GlobalVariable *SrcGV) { |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 888 | Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType())) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 889 | ->getElementType(); |
| 890 | |
| 891 | StringRef Name = SrcGV->getName(); |
| 892 | bool IsNewStructor = false; |
| 893 | bool IsOldStructor = false; |
| 894 | if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") { |
| 895 | if (cast<StructType>(EltTy)->getNumElements() == 3) |
| 896 | IsNewStructor = true; |
| 897 | else |
| 898 | IsOldStructor = true; |
| 899 | } |
| 900 | |
| 901 | PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo(); |
| 902 | if (IsOldStructor) { |
| 903 | auto &ST = *cast<StructType>(EltTy); |
| 904 | Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy}; |
| 905 | EltTy = StructType::get(SrcGV->getContext(), Tys, false); |
| 906 | } |
| 907 | |
| 908 | if (DstGV) { |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 909 | ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 910 | |
| 911 | if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) { |
| 912 | emitError( |
| 913 | "Linking globals named '" + SrcGV->getName() + |
| 914 | "': can only link appending global with another appending global!"); |
| 915 | return nullptr; |
| 916 | } |
| 917 | |
| 918 | // Check to see that they two arrays agree on type. |
| 919 | if (EltTy != DstTy->getElementType()) { |
| 920 | emitError("Appending variables with different element types!"); |
| 921 | return nullptr; |
| 922 | } |
| 923 | if (DstGV->isConstant() != SrcGV->isConstant()) { |
| 924 | emitError("Appending variables linked with different const'ness!"); |
| 925 | return nullptr; |
| 926 | } |
| 927 | |
| 928 | if (DstGV->getAlignment() != SrcGV->getAlignment()) { |
| 929 | emitError( |
| 930 | "Appending variables with different alignment need to be linked!"); |
| 931 | return nullptr; |
| 932 | } |
| 933 | |
| 934 | if (DstGV->getVisibility() != SrcGV->getVisibility()) { |
| 935 | emitError( |
| 936 | "Appending variables with different visibility need to be linked!"); |
| 937 | return nullptr; |
| 938 | } |
| 939 | |
| 940 | if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) { |
| 941 | emitError( |
| 942 | "Appending variables with different unnamed_addr need to be linked!"); |
| 943 | return nullptr; |
| 944 | } |
| 945 | |
| 946 | if (StringRef(DstGV->getSection()) != SrcGV->getSection()) { |
| 947 | emitError( |
| 948 | "Appending variables with different section name need to be linked!"); |
| 949 | return nullptr; |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | SmallVector<Constant *, 16> DstElements; |
| 954 | if (DstGV) |
| 955 | getArrayElements(DstGV->getInitializer(), DstElements); |
| 956 | |
| 957 | SmallVector<Constant *, 16> SrcElements; |
| 958 | getArrayElements(SrcGV->getInitializer(), SrcElements); |
| 959 | |
| 960 | if (IsNewStructor) |
| 961 | SrcElements.erase( |
| 962 | std::remove_if(SrcElements.begin(), SrcElements.end(), |
| 963 | [this](Constant *E) { |
| 964 | auto *Key = dyn_cast<GlobalValue>( |
| 965 | E->getAggregateElement(2)->stripPointerCasts()); |
| 966 | if (!Key) |
| 967 | return false; |
| 968 | GlobalValue *DGV = getLinkedToGlobal(Key); |
| 969 | return !shouldLink(DGV, *Key); |
| 970 | }), |
| 971 | SrcElements.end()); |
| 972 | uint64_t NewSize = DstElements.size() + SrcElements.size(); |
| 973 | ArrayType *NewType = ArrayType::get(EltTy, NewSize); |
| 974 | |
| 975 | // Create the new global variable. |
| 976 | GlobalVariable *NG = new GlobalVariable( |
| 977 | DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(), |
| 978 | /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(), |
| 979 | SrcGV->getType()->getAddressSpace()); |
| 980 | |
| 981 | NG->copyAttributesFrom(SrcGV); |
| 982 | forceRenaming(NG, SrcGV->getName()); |
| 983 | |
| 984 | Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); |
| 985 | |
| 986 | // Stop recursion. |
| 987 | ValueMap[SrcGV] = Ret; |
| 988 | |
| 989 | for (auto *V : SrcElements) { |
| 990 | Constant *NewV; |
| 991 | if (IsOldStructor) { |
| 992 | auto *S = cast<ConstantStruct>(V); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 993 | auto *E1 = MapValue(S->getOperand(0), ValueMap, ValueMapperFlags, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 994 | &TypeMap, &GValMaterializer); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 995 | auto *E2 = MapValue(S->getOperand(1), ValueMap, ValueMapperFlags, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 996 | &TypeMap, &GValMaterializer); |
| 997 | Value *Null = Constant::getNullValue(VoidPtrTy); |
| 998 | NewV = |
| 999 | ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr); |
| 1000 | } else { |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1001 | NewV = |
| 1002 | MapValue(V, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1003 | } |
| 1004 | DstElements.push_back(NewV); |
| 1005 | } |
| 1006 | |
| 1007 | NG->setInitializer(ConstantArray::get(NewType, DstElements)); |
| 1008 | |
| 1009 | // Replace any uses of the two global variables with uses of the new |
| 1010 | // global. |
| 1011 | if (DstGV) { |
| 1012 | DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); |
| 1013 | DstGV->eraseFromParent(); |
| 1014 | } |
| 1015 | |
| 1016 | return Ret; |
| 1017 | } |
| 1018 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1019 | bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) { |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1020 | // Already imported all the values. Just map to the Dest value |
| 1021 | // in case it is referenced in the metadata. |
| 1022 | if (IsMetadataLinkingPostpass) { |
| 1023 | assert(!ValuesToLink.count(&SGV) && |
| 1024 | "Source value unexpectedly requested for link during metadata link"); |
| 1025 | return false; |
| 1026 | } |
| 1027 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1028 | if (ValuesToLink.count(&SGV)) |
| 1029 | return true; |
| 1030 | |
| 1031 | if (SGV.hasLocalLinkage()) |
| 1032 | return true; |
| 1033 | |
Rafael Espindola | 55a7ae5 | 2016-01-20 22:38:23 +0000 | [diff] [blame] | 1034 | if (DGV && !DGV->isDeclarationForLinker()) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1035 | return false; |
| 1036 | |
| 1037 | if (SGV.hasAvailableExternallyLinkage()) |
| 1038 | return true; |
| 1039 | |
| 1040 | if (DoneLinkingBodies) |
| 1041 | return false; |
| 1042 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 1043 | |
| 1044 | // Callback to the client to give a chance to lazily add the Global to the |
| 1045 | // list of value to link. |
| 1046 | bool LazilyAdded = false; |
| 1047 | AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) { |
| 1048 | maybeAdd(&GV); |
| 1049 | LazilyAdded = true; |
| 1050 | }); |
| 1051 | return LazilyAdded; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1052 | } |
| 1053 | |
| 1054 | Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) { |
| 1055 | GlobalValue *DGV = getLinkedToGlobal(SGV); |
| 1056 | |
| 1057 | bool ShouldLink = shouldLink(DGV, *SGV); |
| 1058 | |
| 1059 | // just missing from map |
| 1060 | if (ShouldLink) { |
| 1061 | auto I = ValueMap.find(SGV); |
| 1062 | if (I != ValueMap.end()) |
| 1063 | return cast<Constant>(I->second); |
| 1064 | |
| 1065 | I = AliasValueMap.find(SGV); |
| 1066 | if (I != AliasValueMap.end()) |
| 1067 | return cast<Constant>(I->second); |
| 1068 | } |
| 1069 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame^] | 1070 | if (!ShouldLink && ForAlias) |
| 1071 | DGV = nullptr; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1072 | |
| 1073 | // Handle the ultra special appending linkage case first. |
| 1074 | assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage()); |
| 1075 | if (SGV->hasAppendingLinkage()) |
| 1076 | return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV), |
| 1077 | cast<GlobalVariable>(SGV)); |
| 1078 | |
| 1079 | GlobalValue *NewGV; |
Rafael Espindola | 55a7ae5 | 2016-01-20 22:38:23 +0000 | [diff] [blame] | 1080 | if (DGV && !ShouldLink) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1081 | NewGV = DGV; |
| 1082 | } else { |
| 1083 | // If we are done linking global value bodies (i.e. we are performing |
| 1084 | // metadata linking), don't link in the global value due to this |
| 1085 | // reference, simply map it to null. |
| 1086 | if (DoneLinkingBodies) |
| 1087 | return nullptr; |
| 1088 | |
| 1089 | NewGV = copyGlobalValueProto(SGV, ShouldLink); |
Evgeniy Stepanov | 9fb70f5 | 2016-01-20 22:05:50 +0000 | [diff] [blame] | 1090 | if (ShouldLink || !ForAlias) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1091 | forceRenaming(NewGV, SGV->getName()); |
| 1092 | } |
| 1093 | if (ShouldLink || ForAlias) { |
| 1094 | if (const Comdat *SC = SGV->getComdat()) { |
| 1095 | if (auto *GO = dyn_cast<GlobalObject>(NewGV)) { |
| 1096 | Comdat *DC = DstM.getOrInsertComdat(SC->getName()); |
| 1097 | DC->setSelectionKind(SC->getSelectionKind()); |
| 1098 | GO->setComdat(DC); |
| 1099 | } |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | if (!ShouldLink && ForAlias) |
| 1104 | NewGV->setLinkage(GlobalValue::InternalLinkage); |
| 1105 | |
| 1106 | Constant *C = NewGV; |
| 1107 | if (DGV) |
| 1108 | C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType())); |
| 1109 | |
| 1110 | if (DGV && NewGV != DGV) { |
| 1111 | DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType())); |
| 1112 | DGV->eraseFromParent(); |
| 1113 | } |
| 1114 | |
| 1115 | return C; |
| 1116 | } |
| 1117 | |
| 1118 | /// Update the initializers in the Dest module now that all globals that may be |
| 1119 | /// referenced are in Dest. |
| 1120 | void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) { |
| 1121 | // Figure out what the initializer looks like in the dest module. |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1122 | Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, ValueMapperFlags, |
| 1123 | &TypeMap, &GValMaterializer)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1124 | } |
| 1125 | |
| 1126 | /// Copy the source function over into the dest function and fix up references |
| 1127 | /// to values. At this point we know that Dest is an external function, and |
| 1128 | /// that Src is not. |
| 1129 | bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) { |
| 1130 | assert(Dst.isDeclaration() && !Src.isDeclaration()); |
| 1131 | |
| 1132 | // Materialize if needed. |
| 1133 | if (std::error_code EC = Src.materialize()) |
| 1134 | return emitError(EC.message()); |
| 1135 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1136 | if (!shouldLinkMetadata()) |
| 1137 | // This is only supported for lazy links. Do after materialization of |
| 1138 | // a function and before remapping metadata on instructions below |
| 1139 | // in RemapInstruction, as the saved mapping is used to handle |
| 1140 | // the temporary metadata hanging off instructions. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1141 | SrcM->getMaterializer()->saveMetadataList(MetadataToIDs, |
| 1142 | /* OnlyTempMD = */ true); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1143 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1144 | // Link in the prefix data. |
| 1145 | if (Src.hasPrefixData()) |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1146 | Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, ValueMapperFlags, |
| 1147 | &TypeMap, &GValMaterializer)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1148 | |
| 1149 | // Link in the prologue data. |
| 1150 | if (Src.hasPrologueData()) |
| 1151 | Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1152 | ValueMapperFlags, &TypeMap, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1153 | &GValMaterializer)); |
| 1154 | |
| 1155 | // Link in the personality function. |
| 1156 | if (Src.hasPersonalityFn()) |
| 1157 | Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap, |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1158 | ValueMapperFlags, &TypeMap, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1159 | &GValMaterializer)); |
| 1160 | |
| 1161 | // Go through and convert function arguments over, remembering the mapping. |
| 1162 | Function::arg_iterator DI = Dst.arg_begin(); |
| 1163 | for (Argument &Arg : Src.args()) { |
| 1164 | DI->setName(Arg.getName()); // Copy the name over. |
| 1165 | |
| 1166 | // Add a mapping to our mapping. |
| 1167 | ValueMap[&Arg] = &*DI; |
| 1168 | ++DI; |
| 1169 | } |
| 1170 | |
| 1171 | // Copy over the metadata attachments. |
| 1172 | SmallVector<std::pair<unsigned, MDNode *>, 8> MDs; |
| 1173 | Src.getAllMetadata(MDs); |
| 1174 | for (const auto &I : MDs) |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1175 | Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, ValueMapperFlags, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1176 | &TypeMap, &GValMaterializer)); |
| 1177 | |
| 1178 | // Splice the body of the source function into the dest function. |
| 1179 | Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList()); |
| 1180 | |
| 1181 | // At this point, all of the instructions and values of the function are now |
| 1182 | // copied over. The only problem is that they are still referencing values in |
| 1183 | // the Source function as operands. Loop through all of the operands of the |
| 1184 | // functions and patch them up to point to the local versions. |
| 1185 | for (BasicBlock &BB : Dst) |
| 1186 | for (Instruction &I : BB) |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1187 | RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries | ValueMapperFlags, |
| 1188 | &TypeMap, &GValMaterializer); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1189 | |
| 1190 | // There is no need to map the arguments anymore. |
| 1191 | for (Argument &Arg : Src.args()) |
| 1192 | ValueMap.erase(&Arg); |
| 1193 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1194 | return false; |
| 1195 | } |
| 1196 | |
| 1197 | void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) { |
| 1198 | Constant *Aliasee = Src.getAliasee(); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1199 | Constant *Val = MapValue(Aliasee, AliasValueMap, ValueMapperFlags, &TypeMap, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1200 | &LValMaterializer); |
| 1201 | Dst.setAliasee(Val); |
| 1202 | } |
| 1203 | |
| 1204 | bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) { |
| 1205 | if (auto *F = dyn_cast<Function>(&Src)) |
| 1206 | return linkFunctionBody(cast<Function>(Dst), *F); |
| 1207 | if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) { |
| 1208 | linkGlobalInit(cast<GlobalVariable>(Dst), *GVar); |
| 1209 | return false; |
| 1210 | } |
| 1211 | linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src)); |
| 1212 | return false; |
| 1213 | } |
| 1214 | |
Teresa Johnson | 71d12d2 | 2016-01-25 22:04:56 +0000 | [diff] [blame] | 1215 | void IRLinker::findReachedSubprograms( |
| 1216 | const MDNode *Node, SmallPtrSet<const MDNode *, 16> &Visited) { |
| 1217 | if (!Visited.insert(Node).second) |
| 1218 | return; |
| 1219 | DISubprogram *SP = getDISubprogram(Node); |
| 1220 | if (SP) |
| 1221 | UnneededSubprograms.erase(SP); |
| 1222 | for (auto &Op : Node->operands()) { |
| 1223 | const MDNode *OpN = dyn_cast_or_null<MDNode>(Op.get()); |
| 1224 | if (!OpN) |
| 1225 | continue; |
| 1226 | findReachedSubprograms(OpN, Visited); |
| 1227 | } |
| 1228 | } |
| 1229 | |
Rafael Espindola | 394524d | 2016-01-21 00:00:53 +0000 | [diff] [blame] | 1230 | void IRLinker::findNeededSubprograms() { |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1231 | // Track unneeded nodes to make it simpler to handle the case |
| 1232 | // where we are checking if an already-mapped SP is needed. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1233 | NamedMDNode *CompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu"); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1234 | if (!CompileUnits) |
| 1235 | return; |
| 1236 | for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) { |
| 1237 | auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I)); |
| 1238 | assert(CU && "Expected valid compile unit"); |
Teresa Johnson | b951558 | 2016-01-07 00:06:27 +0000 | [diff] [blame] | 1239 | // Ensure that we don't remove subprograms referenced by DIImportedEntity. |
Ahmed Bougacha | a7324a2 | 2016-01-07 03:14:59 +0000 | [diff] [blame] | 1240 | // It is not legal to have a DIImportedEntity with a null entity or scope. |
Teresa Johnson | f07db00 | 2016-01-25 21:29:55 +0000 | [diff] [blame] | 1241 | // Using getDISubprogram handles the case where the subprogram is reached |
| 1242 | // via an intervening DILexicalBlock. |
Teresa Johnson | b951558 | 2016-01-07 00:06:27 +0000 | [diff] [blame] | 1243 | // FIXME: The DISubprogram for functions not linked in but kept due to |
| 1244 | // being referenced by a DIImportedEntity should also get their |
| 1245 | // IsDefinition flag is unset. |
| 1246 | SmallPtrSet<DISubprogram *, 8> ImportedEntitySPs; |
| 1247 | for (auto *IE : CU->getImportedEntities()) { |
Teresa Johnson | f07db00 | 2016-01-25 21:29:55 +0000 | [diff] [blame] | 1248 | if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getEntity()))) |
Teresa Johnson | b951558 | 2016-01-07 00:06:27 +0000 | [diff] [blame] | 1249 | ImportedEntitySPs.insert(SP); |
Teresa Johnson | f07db00 | 2016-01-25 21:29:55 +0000 | [diff] [blame] | 1250 | if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getScope()))) |
Ahmed Bougacha | a7324a2 | 2016-01-07 03:14:59 +0000 | [diff] [blame] | 1251 | ImportedEntitySPs.insert(SP); |
Teresa Johnson | b951558 | 2016-01-07 00:06:27 +0000 | [diff] [blame] | 1252 | } |
Teresa Johnson | d213aa4 | 2015-12-22 01:17:19 +0000 | [diff] [blame] | 1253 | for (auto *Op : CU->getSubprograms()) { |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1254 | // Unless we were doing function importing and deferred metadata linking, |
| 1255 | // any needed SPs should have been mapped as they would be reached |
| 1256 | // from the function linked in (either on the function itself for linked |
| 1257 | // function bodies, or from DILocation on inlined instructions). |
| 1258 | assert(!(ValueMap.MD()[Op] && IsMetadataLinkingPostpass) && |
| 1259 | "DISubprogram shouldn't be mapped yet"); |
Teresa Johnson | b951558 | 2016-01-07 00:06:27 +0000 | [diff] [blame] | 1260 | if (!ValueMap.MD()[Op] && !ImportedEntitySPs.count(Op)) |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1261 | UnneededSubprograms.insert(Op); |
| 1262 | } |
| 1263 | } |
| 1264 | if (!IsMetadataLinkingPostpass) |
| 1265 | return; |
| 1266 | // In the case of metadata linking as a postpass (e.g. for function |
Teresa Johnson | 71d12d2 | 2016-01-25 22:04:56 +0000 | [diff] [blame] | 1267 | // importing), see which MD from the source has an associated |
| 1268 | // temporary metadata node, which means that any DISubprogram |
| 1269 | // reached from that MD was needed by an imported function. |
| 1270 | SmallPtrSet<const MDNode *, 16> Visited; |
Teresa Johnson | 61b406e | 2015-12-29 23:00:22 +0000 | [diff] [blame] | 1271 | for (auto MDI : MetadataToIDs) { |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1272 | const MDNode *Node = dyn_cast<MDNode>(MDI.first); |
| 1273 | if (!Node) |
| 1274 | continue; |
Teresa Johnson | 71d12d2 | 2016-01-25 22:04:56 +0000 | [diff] [blame] | 1275 | if (!ValIDToTempMDMap->count(MDI.second)) |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1276 | continue; |
Teresa Johnson | 71d12d2 | 2016-01-25 22:04:56 +0000 | [diff] [blame] | 1277 | // Find any SP needed recursively from this needed Node. |
| 1278 | findReachedSubprograms(Node, Visited); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1279 | } |
| 1280 | } |
| 1281 | |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1282 | // Squash null subprograms from the given compile unit's subprogram list. |
| 1283 | void IRLinker::stripNullSubprograms(DICompileUnit *CU) { |
| 1284 | // There won't be any nulls if we didn't have any subprograms marked |
| 1285 | // as unneeded. |
| 1286 | if (UnneededSubprograms.empty()) |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1287 | return; |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1288 | SmallVector<Metadata *, 16> NewSPs; |
| 1289 | NewSPs.reserve(CU->getSubprograms().size()); |
| 1290 | bool FoundNull = false; |
| 1291 | for (DISubprogram *SP : CU->getSubprograms()) { |
| 1292 | if (!SP) { |
| 1293 | FoundNull = true; |
| 1294 | continue; |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1295 | } |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1296 | NewSPs.push_back(SP); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1297 | } |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1298 | if (FoundNull) |
| 1299 | CU->replaceSubprograms(MDTuple::get(CU->getContext(), NewSPs)); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1300 | } |
| 1301 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1302 | /// Insert all of the named MDNodes in Src into the Dest module. |
| 1303 | void IRLinker::linkNamedMDNodes() { |
Rafael Espindola | 394524d | 2016-01-21 00:00:53 +0000 | [diff] [blame] | 1304 | findNeededSubprograms(); |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1305 | const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); |
| 1306 | for (const NamedMDNode &NMD : SrcM->named_metadata()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1307 | // Don't link module flags here. Do them separately. |
| 1308 | if (&NMD == SrcModFlags) |
| 1309 | continue; |
| 1310 | NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName()); |
| 1311 | // Add Src elements into Dest node. |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1312 | for (const MDNode *op : NMD.operands()) { |
| 1313 | MDNode *DestMD = MapMetadata( |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1314 | op, ValueMap, ValueMapperFlags | RF_NullMapMissingGlobalValues, |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1315 | &TypeMap, &GValMaterializer); |
| 1316 | // For each newly mapped compile unit remove any null subprograms, |
| 1317 | // which occur when findNeededSubprograms identified any as unneeded |
| 1318 | // in the dest module. |
| 1319 | if (auto *CU = dyn_cast<DICompileUnit>(DestMD)) |
| 1320 | stripNullSubprograms(CU); |
| 1321 | DestNMD->addOperand(DestMD); |
| 1322 | } |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | /// Merge the linker flags in Src into the Dest module. |
| 1327 | bool IRLinker::linkModuleFlagsMetadata() { |
| 1328 | // If the source module has no module flags, we are done. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1329 | const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1330 | if (!SrcModFlags) |
| 1331 | return false; |
| 1332 | |
| 1333 | // If the destination module doesn't have module flags yet, then just copy |
| 1334 | // over the source module's flags. |
| 1335 | NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata(); |
| 1336 | if (DstModFlags->getNumOperands() == 0) { |
| 1337 | for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) |
| 1338 | DstModFlags->addOperand(SrcModFlags->getOperand(I)); |
| 1339 | |
| 1340 | return false; |
| 1341 | } |
| 1342 | |
| 1343 | // First build a map of the existing module flags and requirements. |
| 1344 | DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags; |
| 1345 | SmallSetVector<MDNode *, 16> Requirements; |
| 1346 | for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { |
| 1347 | MDNode *Op = DstModFlags->getOperand(I); |
| 1348 | ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0)); |
| 1349 | MDString *ID = cast<MDString>(Op->getOperand(1)); |
| 1350 | |
| 1351 | if (Behavior->getZExtValue() == Module::Require) { |
| 1352 | Requirements.insert(cast<MDNode>(Op->getOperand(2))); |
| 1353 | } else { |
| 1354 | Flags[ID] = std::make_pair(Op, I); |
| 1355 | } |
| 1356 | } |
| 1357 | |
| 1358 | // Merge in the flags from the source module, and also collect its set of |
| 1359 | // requirements. |
| 1360 | for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { |
| 1361 | MDNode *SrcOp = SrcModFlags->getOperand(I); |
| 1362 | ConstantInt *SrcBehavior = |
| 1363 | mdconst::extract<ConstantInt>(SrcOp->getOperand(0)); |
| 1364 | MDString *ID = cast<MDString>(SrcOp->getOperand(1)); |
| 1365 | MDNode *DstOp; |
| 1366 | unsigned DstIndex; |
| 1367 | std::tie(DstOp, DstIndex) = Flags.lookup(ID); |
| 1368 | unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); |
| 1369 | |
| 1370 | // If this is a requirement, add it and continue. |
| 1371 | if (SrcBehaviorValue == Module::Require) { |
| 1372 | // If the destination module does not already have this requirement, add |
| 1373 | // it. |
| 1374 | if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { |
| 1375 | DstModFlags->addOperand(SrcOp); |
| 1376 | } |
| 1377 | continue; |
| 1378 | } |
| 1379 | |
| 1380 | // If there is no existing flag with this ID, just add it. |
| 1381 | if (!DstOp) { |
| 1382 | Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands()); |
| 1383 | DstModFlags->addOperand(SrcOp); |
| 1384 | continue; |
| 1385 | } |
| 1386 | |
| 1387 | // Otherwise, perform a merge. |
| 1388 | ConstantInt *DstBehavior = |
| 1389 | mdconst::extract<ConstantInt>(DstOp->getOperand(0)); |
| 1390 | unsigned DstBehaviorValue = DstBehavior->getZExtValue(); |
| 1391 | |
| 1392 | // If either flag has override behavior, handle it first. |
| 1393 | if (DstBehaviorValue == Module::Override) { |
| 1394 | // Diagnose inconsistent flags which both have override behavior. |
| 1395 | if (SrcBehaviorValue == Module::Override && |
| 1396 | SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1397 | emitError("linking module flags '" + ID->getString() + |
| 1398 | "': IDs have conflicting override values"); |
| 1399 | } |
| 1400 | continue; |
| 1401 | } else if (SrcBehaviorValue == Module::Override) { |
| 1402 | // Update the destination flag to that of the source. |
| 1403 | DstModFlags->setOperand(DstIndex, SrcOp); |
| 1404 | Flags[ID].first = SrcOp; |
| 1405 | continue; |
| 1406 | } |
| 1407 | |
| 1408 | // Diagnose inconsistent merge behavior types. |
| 1409 | if (SrcBehaviorValue != DstBehaviorValue) { |
| 1410 | emitError("linking module flags '" + ID->getString() + |
| 1411 | "': IDs have conflicting behaviors"); |
| 1412 | continue; |
| 1413 | } |
| 1414 | |
| 1415 | auto replaceDstValue = [&](MDNode *New) { |
| 1416 | Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New}; |
| 1417 | MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps); |
| 1418 | DstModFlags->setOperand(DstIndex, Flag); |
| 1419 | Flags[ID].first = Flag; |
| 1420 | }; |
| 1421 | |
| 1422 | // Perform the merge for standard behavior types. |
| 1423 | switch (SrcBehaviorValue) { |
| 1424 | case Module::Require: |
| 1425 | case Module::Override: |
| 1426 | llvm_unreachable("not possible"); |
| 1427 | case Module::Error: { |
| 1428 | // Emit an error if the values differ. |
| 1429 | if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1430 | emitError("linking module flags '" + ID->getString() + |
| 1431 | "': IDs have conflicting values"); |
| 1432 | } |
| 1433 | continue; |
| 1434 | } |
| 1435 | case Module::Warning: { |
| 1436 | // Emit a warning if the values differ. |
| 1437 | if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1438 | emitWarning("linking module flags '" + ID->getString() + |
| 1439 | "': IDs have conflicting values"); |
| 1440 | } |
| 1441 | continue; |
| 1442 | } |
| 1443 | case Module::Append: { |
| 1444 | MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); |
| 1445 | MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); |
| 1446 | SmallVector<Metadata *, 8> MDs; |
| 1447 | MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands()); |
| 1448 | MDs.append(DstValue->op_begin(), DstValue->op_end()); |
| 1449 | MDs.append(SrcValue->op_begin(), SrcValue->op_end()); |
| 1450 | |
| 1451 | replaceDstValue(MDNode::get(DstM.getContext(), MDs)); |
| 1452 | break; |
| 1453 | } |
| 1454 | case Module::AppendUnique: { |
| 1455 | SmallSetVector<Metadata *, 16> Elts; |
| 1456 | MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); |
| 1457 | MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); |
| 1458 | Elts.insert(DstValue->op_begin(), DstValue->op_end()); |
| 1459 | Elts.insert(SrcValue->op_begin(), SrcValue->op_end()); |
| 1460 | |
| 1461 | replaceDstValue(MDNode::get(DstM.getContext(), |
| 1462 | makeArrayRef(Elts.begin(), Elts.end()))); |
| 1463 | break; |
| 1464 | } |
| 1465 | } |
| 1466 | } |
| 1467 | |
| 1468 | // Check all of the requirements. |
| 1469 | for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { |
| 1470 | MDNode *Requirement = Requirements[I]; |
| 1471 | MDString *Flag = cast<MDString>(Requirement->getOperand(0)); |
| 1472 | Metadata *ReqValue = Requirement->getOperand(1); |
| 1473 | |
| 1474 | MDNode *Op = Flags[Flag].first; |
| 1475 | if (!Op || Op->getOperand(2) != ReqValue) { |
| 1476 | emitError("linking module flags '" + Flag->getString() + |
| 1477 | "': does not have the required value"); |
| 1478 | continue; |
| 1479 | } |
| 1480 | } |
| 1481 | |
| 1482 | return HasError; |
| 1483 | } |
| 1484 | |
| 1485 | // This function returns true if the triples match. |
| 1486 | static bool triplesMatch(const Triple &T0, const Triple &T1) { |
| 1487 | // If vendor is apple, ignore the version number. |
| 1488 | if (T0.getVendor() == Triple::Apple) |
| 1489 | return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() && |
| 1490 | T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS(); |
| 1491 | |
| 1492 | return T0 == T1; |
| 1493 | } |
| 1494 | |
| 1495 | // This function returns the merged triple. |
| 1496 | static std::string mergeTriples(const Triple &SrcTriple, |
| 1497 | const Triple &DstTriple) { |
| 1498 | // If vendor is apple, pick the triple with the larger version number. |
| 1499 | if (SrcTriple.getVendor() == Triple::Apple) |
| 1500 | if (DstTriple.isOSVersionLT(SrcTriple)) |
| 1501 | return SrcTriple.str(); |
| 1502 | |
| 1503 | return DstTriple.str(); |
| 1504 | } |
| 1505 | |
| 1506 | bool IRLinker::run() { |
Teresa Johnson | 0556e22 | 2016-03-10 18:47:03 +0000 | [diff] [blame] | 1507 | // Ensure metadata materialized before value mapping. |
| 1508 | if (shouldLinkMetadata() && SrcM->getMaterializer()) |
| 1509 | if (SrcM->getMaterializer()->materializeMetadata()) |
| 1510 | return true; |
| 1511 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1512 | // Inherit the target data from the source module if the destination module |
| 1513 | // doesn't have one already. |
| 1514 | if (DstM.getDataLayout().isDefault()) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1515 | DstM.setDataLayout(SrcM->getDataLayout()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1516 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1517 | if (SrcM->getDataLayout() != DstM.getDataLayout()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1518 | emitWarning("Linking two modules of different data layouts: '" + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1519 | SrcM->getModuleIdentifier() + "' is '" + |
| 1520 | SrcM->getDataLayoutStr() + "' whereas '" + |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1521 | DstM.getModuleIdentifier() + "' is '" + |
| 1522 | DstM.getDataLayoutStr() + "'\n"); |
| 1523 | } |
| 1524 | |
| 1525 | // Copy the target triple from the source to dest if the dest's is empty. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1526 | if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) |
| 1527 | DstM.setTargetTriple(SrcM->getTargetTriple()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1528 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1529 | Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1530 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1531 | if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple)) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1532 | emitWarning("Linking two modules of different target triples: " + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1533 | SrcM->getModuleIdentifier() + "' is '" + |
| 1534 | SrcM->getTargetTriple() + "' whereas '" + |
| 1535 | DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() + |
| 1536 | "'\n"); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1537 | |
| 1538 | DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple)); |
| 1539 | |
| 1540 | // Append the module inline asm string. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1541 | if (!SrcM->getModuleInlineAsm().empty()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1542 | if (DstM.getModuleInlineAsm().empty()) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1543 | DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1544 | else |
| 1545 | DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1546 | SrcM->getModuleInlineAsm()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1547 | } |
| 1548 | |
| 1549 | // Loop over all of the linked values to compute type mappings. |
| 1550 | computeTypeMapping(); |
| 1551 | |
| 1552 | std::reverse(Worklist.begin(), Worklist.end()); |
| 1553 | while (!Worklist.empty()) { |
| 1554 | GlobalValue *GV = Worklist.back(); |
| 1555 | Worklist.pop_back(); |
| 1556 | |
| 1557 | // Already mapped. |
| 1558 | if (ValueMap.find(GV) != ValueMap.end() || |
| 1559 | AliasValueMap.find(GV) != AliasValueMap.end()) |
| 1560 | continue; |
| 1561 | |
| 1562 | assert(!GV->isDeclaration()); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1563 | MapValue(GV, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1564 | if (HasError) |
| 1565 | return true; |
| 1566 | } |
| 1567 | |
| 1568 | // Note that we are done linking global value bodies. This prevents |
| 1569 | // metadata linking from creating new references. |
| 1570 | DoneLinkingBodies = true; |
| 1571 | |
| 1572 | // Remap all of the named MDNodes in Src into the DstM module. We do this |
| 1573 | // after linking GlobalValues so that MDNodes that reference GlobalValues |
| 1574 | // are properly remapped. |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1575 | if (shouldLinkMetadata()) { |
| 1576 | // Even if just linking metadata we should link decls above in case |
| 1577 | // any are referenced by metadata. IRLinker::shouldLink ensures that |
| 1578 | // we don't actually link anything from source. |
Teresa Johnson | 0556e22 | 2016-03-10 18:47:03 +0000 | [diff] [blame] | 1579 | if (IsMetadataLinkingPostpass) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1580 | SrcM->getMaterializer()->saveMetadataList(MetadataToIDs, |
| 1581 | /* OnlyTempMD = */ false); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1582 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1583 | linkNamedMDNodes(); |
| 1584 | |
| 1585 | if (IsMetadataLinkingPostpass) { |
| 1586 | // Handle anything left in the ValIDToTempMDMap, such as metadata nodes |
| 1587 | // not reached by the dbg.cu NamedMD (i.e. only reached from |
| 1588 | // instructions). |
Teresa Johnson | 61b406e | 2015-12-29 23:00:22 +0000 | [diff] [blame] | 1589 | // Walk the MetadataToIDs once to find the set of new (imported) MD |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1590 | // that still has corresponding temporary metadata, and invoke metadata |
| 1591 | // mapping on each one. |
Teresa Johnson | 61b406e | 2015-12-29 23:00:22 +0000 | [diff] [blame] | 1592 | for (auto MDI : MetadataToIDs) { |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1593 | if (!ValIDToTempMDMap->count(MDI.second)) |
| 1594 | continue; |
| 1595 | MapMetadata(MDI.first, ValueMap, ValueMapperFlags, &TypeMap, |
| 1596 | &GValMaterializer); |
| 1597 | } |
| 1598 | assert(ValIDToTempMDMap->empty()); |
| 1599 | } |
| 1600 | |
| 1601 | // Merge the module flags into the DstM module. |
| 1602 | if (linkModuleFlagsMetadata()) |
| 1603 | return true; |
| 1604 | } |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1605 | |
| 1606 | return false; |
| 1607 | } |
| 1608 | |
| 1609 | IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P) |
| 1610 | : ETypes(E), IsPacked(P) {} |
| 1611 | |
| 1612 | IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST) |
| 1613 | : ETypes(ST->elements()), IsPacked(ST->isPacked()) {} |
| 1614 | |
| 1615 | bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const { |
| 1616 | if (IsPacked != That.IsPacked) |
| 1617 | return false; |
| 1618 | if (ETypes != That.ETypes) |
| 1619 | return false; |
| 1620 | return true; |
| 1621 | } |
| 1622 | |
| 1623 | bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const { |
| 1624 | return !this->operator==(That); |
| 1625 | } |
| 1626 | |
| 1627 | StructType *IRMover::StructTypeKeyInfo::getEmptyKey() { |
| 1628 | return DenseMapInfo<StructType *>::getEmptyKey(); |
| 1629 | } |
| 1630 | |
| 1631 | StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() { |
| 1632 | return DenseMapInfo<StructType *>::getTombstoneKey(); |
| 1633 | } |
| 1634 | |
| 1635 | unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) { |
| 1636 | return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()), |
| 1637 | Key.IsPacked); |
| 1638 | } |
| 1639 | |
| 1640 | unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) { |
| 1641 | return getHashValue(KeyTy(ST)); |
| 1642 | } |
| 1643 | |
| 1644 | bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS, |
| 1645 | const StructType *RHS) { |
| 1646 | if (RHS == getEmptyKey() || RHS == getTombstoneKey()) |
| 1647 | return false; |
| 1648 | return LHS == KeyTy(RHS); |
| 1649 | } |
| 1650 | |
| 1651 | bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS, |
| 1652 | const StructType *RHS) { |
| 1653 | if (RHS == getEmptyKey()) |
| 1654 | return LHS == getEmptyKey(); |
| 1655 | |
| 1656 | if (RHS == getTombstoneKey()) |
| 1657 | return LHS == getTombstoneKey(); |
| 1658 | |
| 1659 | return KeyTy(LHS) == KeyTy(RHS); |
| 1660 | } |
| 1661 | |
| 1662 | void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) { |
| 1663 | assert(!Ty->isOpaque()); |
| 1664 | NonOpaqueStructTypes.insert(Ty); |
| 1665 | } |
| 1666 | |
| 1667 | void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) { |
| 1668 | assert(!Ty->isOpaque()); |
| 1669 | NonOpaqueStructTypes.insert(Ty); |
| 1670 | bool Removed = OpaqueStructTypes.erase(Ty); |
| 1671 | (void)Removed; |
| 1672 | assert(Removed); |
| 1673 | } |
| 1674 | |
| 1675 | void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) { |
| 1676 | assert(Ty->isOpaque()); |
| 1677 | OpaqueStructTypes.insert(Ty); |
| 1678 | } |
| 1679 | |
| 1680 | StructType * |
| 1681 | IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes, |
| 1682 | bool IsPacked) { |
| 1683 | IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked); |
| 1684 | auto I = NonOpaqueStructTypes.find_as(Key); |
| 1685 | if (I == NonOpaqueStructTypes.end()) |
| 1686 | return nullptr; |
| 1687 | return *I; |
| 1688 | } |
| 1689 | |
| 1690 | bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) { |
| 1691 | if (Ty->isOpaque()) |
| 1692 | return OpaqueStructTypes.count(Ty); |
| 1693 | auto I = NonOpaqueStructTypes.find(Ty); |
| 1694 | if (I == NonOpaqueStructTypes.end()) |
| 1695 | return false; |
| 1696 | return *I == Ty; |
| 1697 | } |
| 1698 | |
Rafael Espindola | 9d2bfc4 | 2015-12-14 23:17:03 +0000 | [diff] [blame] | 1699 | IRMover::IRMover(Module &M) : Composite(M) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1700 | TypeFinder StructTypes; |
| 1701 | StructTypes.run(M, true); |
| 1702 | for (StructType *Ty : StructTypes) { |
| 1703 | if (Ty->isOpaque()) |
| 1704 | IdentifiedStructTypes.addOpaque(Ty); |
| 1705 | else |
| 1706 | IdentifiedStructTypes.addNonOpaque(Ty); |
| 1707 | } |
| 1708 | } |
| 1709 | |
| 1710 | bool IRMover::move( |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1711 | std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink, |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1712 | std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor, |
| 1713 | DenseMap<unsigned, MDNode *> *ValIDToTempMDMap, |
| 1714 | bool IsMetadataLinkingPostpass) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1715 | IRLinker TheIRLinker(Composite, IdentifiedStructTypes, std::move(Src), |
| 1716 | ValuesToLink, AddLazyFor, ValIDToTempMDMap, |
| 1717 | IsMetadataLinkingPostpass); |
Teresa Johnson | bef5436 | 2015-12-18 19:28:59 +0000 | [diff] [blame] | 1718 | bool RetCode = TheIRLinker.run(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1719 | Composite.dropTriviallyDeadConstantArrays(); |
| 1720 | return RetCode; |
| 1721 | } |