IRMover.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  1. //===- lib/Linker/IRMover.cpp ---------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/Linker/IRMover.h"
  9. #include "LinkDiagnosticInfo.h"
  10. #include "llvm/ADT/SetVector.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/IR/Constants.h"
  14. #include "llvm/IR/DebugInfo.h"
  15. #include "llvm/IR/DiagnosticPrinter.h"
  16. #include "llvm/IR/GVMaterializer.h"
  17. #include "llvm/IR/Intrinsics.h"
  18. #include "llvm/IR/TypeFinder.h"
  19. #include "llvm/Object/ModuleSymbolTable.h"
  20. #include "llvm/Support/Error.h"
  21. #include "llvm/Transforms/Utils/Cloning.h"
  22. #include <utility>
  23. using namespace llvm;
  24. //===----------------------------------------------------------------------===//
  25. // TypeMap implementation.
  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. /// When checking to see if two subgraphs are isomorphic, we speculatively
  32. /// add types to MappedTypes, but keep track of them here in case we need to
  33. /// roll back.
  34. SmallVector<Type *, 16> SpeculativeTypes;
  35. SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
  36. /// This is a list of non-opaque structs in the source module that are mapped
  37. /// to an opaque struct in the destination module.
  38. SmallVector<StructType *, 16> SrcDefinitionsToResolve;
  39. /// This is the set of opaque types in the destination modules who are
  40. /// getting a body from the source module.
  41. SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
  42. public:
  43. TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
  44. : DstStructTypesSet(DstStructTypesSet) {}
  45. IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
  46. /// Indicate that the specified type in the destination module is conceptually
  47. /// equivalent to the specified type in the source module.
  48. void addTypeMapping(Type *DstTy, Type *SrcTy);
  49. /// Produce a body for an opaque type in the dest module from a type
  50. /// definition in the source module.
  51. void linkDefinedTypeBodies();
  52. /// Return the mapped type to use for the specified input type from the
  53. /// source module.
  54. Type *get(Type *SrcTy);
  55. Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
  56. void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
  57. FunctionType *get(FunctionType *T) {
  58. return cast<FunctionType>(get((Type *)T));
  59. }
  60. private:
  61. Type *remapType(Type *SrcTy) override { return get(SrcTy); }
  62. bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
  63. };
  64. }
  65. void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
  66. assert(SpeculativeTypes.empty());
  67. assert(SpeculativeDstOpaqueTypes.empty());
  68. // Check to see if these types are recursively isomorphic and establish a
  69. // mapping between them if so.
  70. if (!areTypesIsomorphic(DstTy, SrcTy)) {
  71. // Oops, they aren't isomorphic. Just discard this request by rolling out
  72. // any speculative mappings we've established.
  73. for (Type *Ty : SpeculativeTypes)
  74. MappedTypes.erase(Ty);
  75. SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
  76. SpeculativeDstOpaqueTypes.size());
  77. for (StructType *Ty : SpeculativeDstOpaqueTypes)
  78. DstResolvedOpaqueTypes.erase(Ty);
  79. } else {
  80. // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
  81. // and all its descendants to lower amount of renaming in LLVM context
  82. // Renaming occurs because we load all source modules to the same context
  83. // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
  84. // As a result we may get several different types in the destination
  85. // module, which are in fact the same.
  86. for (Type *Ty : SpeculativeTypes)
  87. if (auto *STy = dyn_cast<StructType>(Ty))
  88. if (STy->hasName())
  89. STy->setName("");
  90. }
  91. SpeculativeTypes.clear();
  92. SpeculativeDstOpaqueTypes.clear();
  93. }
  94. /// Recursively walk this pair of types, returning true if they are isomorphic,
  95. /// false if they are not.
  96. bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
  97. // Two types with differing kinds are clearly not isomorphic.
  98. if (DstTy->getTypeID() != SrcTy->getTypeID())
  99. return false;
  100. // If we have an entry in the MappedTypes table, then we have our answer.
  101. Type *&Entry = MappedTypes[SrcTy];
  102. if (Entry)
  103. return Entry == DstTy;
  104. // Two identical types are clearly isomorphic. Remember this
  105. // non-speculatively.
  106. if (DstTy == SrcTy) {
  107. Entry = DstTy;
  108. return true;
  109. }
  110. // Okay, we have two types with identical kinds that we haven't seen before.
  111. // If this is an opaque struct type, special case it.
  112. if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
  113. // Mapping an opaque type to any struct, just keep the dest struct.
  114. if (SSTy->isOpaque()) {
  115. Entry = DstTy;
  116. SpeculativeTypes.push_back(SrcTy);
  117. return true;
  118. }
  119. // Mapping a non-opaque source type to an opaque dest. If this is the first
  120. // type that we're mapping onto this destination type then we succeed. Keep
  121. // the dest, but fill it in later. If this is the second (different) type
  122. // that we're trying to map onto the same opaque type then we fail.
  123. if (cast<StructType>(DstTy)->isOpaque()) {
  124. // We can only map one source type onto the opaque destination type.
  125. if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
  126. return false;
  127. SrcDefinitionsToResolve.push_back(SSTy);
  128. SpeculativeTypes.push_back(SrcTy);
  129. SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
  130. Entry = DstTy;
  131. return true;
  132. }
  133. }
  134. // If the number of subtypes disagree between the two types, then we fail.
  135. if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
  136. return false;
  137. // Fail if any of the extra properties (e.g. array size) of the type disagree.
  138. if (isa<IntegerType>(DstTy))
  139. return false; // bitwidth disagrees.
  140. if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
  141. if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
  142. return false;
  143. } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
  144. if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
  145. return false;
  146. } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
  147. StructType *SSTy = cast<StructType>(SrcTy);
  148. if (DSTy->isLiteral() != SSTy->isLiteral() ||
  149. DSTy->isPacked() != SSTy->isPacked())
  150. return false;
  151. } else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
  152. if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
  153. return false;
  154. } else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
  155. if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
  156. return false;
  157. }
  158. // Otherwise, we speculate that these two types will line up and recursively
  159. // check the subelements.
  160. Entry = DstTy;
  161. SpeculativeTypes.push_back(SrcTy);
  162. for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
  163. if (!areTypesIsomorphic(DstTy->getContainedType(I),
  164. SrcTy->getContainedType(I)))
  165. return false;
  166. // If everything seems to have lined up, then everything is great.
  167. return true;
  168. }
  169. void TypeMapTy::linkDefinedTypeBodies() {
  170. SmallVector<Type *, 16> Elements;
  171. for (StructType *SrcSTy : SrcDefinitionsToResolve) {
  172. StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
  173. assert(DstSTy->isOpaque());
  174. // Map the body of the source type over to a new body for the dest type.
  175. Elements.resize(SrcSTy->getNumElements());
  176. for (unsigned I = 0, E = Elements.size(); I != E; ++I)
  177. Elements[I] = get(SrcSTy->getElementType(I));
  178. DstSTy->setBody(Elements, SrcSTy->isPacked());
  179. DstStructTypesSet.switchToNonOpaque(DstSTy);
  180. }
  181. SrcDefinitionsToResolve.clear();
  182. DstResolvedOpaqueTypes.clear();
  183. }
  184. void TypeMapTy::finishType(StructType *DTy, StructType *STy,
  185. ArrayRef<Type *> ETypes) {
  186. DTy->setBody(ETypes, STy->isPacked());
  187. // Steal STy's name.
  188. if (STy->hasName()) {
  189. SmallString<16> TmpName = STy->getName();
  190. STy->setName("");
  191. DTy->setName(TmpName);
  192. }
  193. DstStructTypesSet.addNonOpaque(DTy);
  194. }
  195. Type *TypeMapTy::get(Type *Ty) {
  196. SmallPtrSet<StructType *, 8> Visited;
  197. return get(Ty, Visited);
  198. }
  199. Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
  200. // If we already have an entry for this type, return it.
  201. Type **Entry = &MappedTypes[Ty];
  202. if (*Entry)
  203. return *Entry;
  204. // These are types that LLVM itself will unique.
  205. bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
  206. if (!IsUniqued) {
  207. #ifndef NDEBUG
  208. for (auto &Pair : MappedTypes) {
  209. assert(!(Pair.first != Ty && Pair.second == Ty) &&
  210. "mapping to a source type");
  211. }
  212. #endif
  213. if (!Visited.insert(cast<StructType>(Ty)).second) {
  214. StructType *DTy = StructType::create(Ty->getContext());
  215. return *Entry = DTy;
  216. }
  217. }
  218. // If this is not a recursive type, then just map all of the elements and
  219. // then rebuild the type from inside out.
  220. SmallVector<Type *, 4> ElementTypes;
  221. // If there are no element types to map, then the type is itself. This is
  222. // true for the anonymous {} struct, things like 'float', integers, etc.
  223. if (Ty->getNumContainedTypes() == 0 && IsUniqued)
  224. return *Entry = Ty;
  225. // Remap all of the elements, keeping track of whether any of them change.
  226. bool AnyChange = false;
  227. ElementTypes.resize(Ty->getNumContainedTypes());
  228. for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
  229. ElementTypes[I] = get(Ty->getContainedType(I), Visited);
  230. AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
  231. }
  232. // If we found our type while recursively processing stuff, just use it.
  233. Entry = &MappedTypes[Ty];
  234. if (*Entry) {
  235. if (auto *DTy = dyn_cast<StructType>(*Entry)) {
  236. if (DTy->isOpaque()) {
  237. auto *STy = cast<StructType>(Ty);
  238. finishType(DTy, STy, ElementTypes);
  239. }
  240. }
  241. return *Entry;
  242. }
  243. // If all of the element types mapped directly over and the type is not
  244. // a named struct, then the type is usable as-is.
  245. if (!AnyChange && IsUniqued)
  246. return *Entry = Ty;
  247. // Otherwise, rebuild a modified type.
  248. switch (Ty->getTypeID()) {
  249. default:
  250. llvm_unreachable("unknown derived type to remap");
  251. case Type::ArrayTyID:
  252. return *Entry = ArrayType::get(ElementTypes[0],
  253. cast<ArrayType>(Ty)->getNumElements());
  254. case Type::ScalableVectorTyID:
  255. // FIXME: handle scalable vectors
  256. case Type::FixedVectorTyID:
  257. return *Entry = FixedVectorType::get(
  258. ElementTypes[0], cast<FixedVectorType>(Ty)->getNumElements());
  259. case Type::PointerTyID:
  260. return *Entry = PointerType::get(ElementTypes[0],
  261. cast<PointerType>(Ty)->getAddressSpace());
  262. case Type::FunctionTyID:
  263. return *Entry = FunctionType::get(ElementTypes[0],
  264. makeArrayRef(ElementTypes).slice(1),
  265. cast<FunctionType>(Ty)->isVarArg());
  266. case Type::StructTyID: {
  267. auto *STy = cast<StructType>(Ty);
  268. bool IsPacked = STy->isPacked();
  269. if (IsUniqued)
  270. return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
  271. // If the type is opaque, we can just use it directly.
  272. if (STy->isOpaque()) {
  273. DstStructTypesSet.addOpaque(STy);
  274. return *Entry = Ty;
  275. }
  276. if (StructType *OldT =
  277. DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
  278. STy->setName("");
  279. return *Entry = OldT;
  280. }
  281. if (!AnyChange) {
  282. DstStructTypesSet.addNonOpaque(STy);
  283. return *Entry = Ty;
  284. }
  285. StructType *DTy = StructType::create(Ty->getContext());
  286. finishType(DTy, STy, ElementTypes);
  287. return *Entry = DTy;
  288. }
  289. }
  290. }
  291. LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
  292. const Twine &Msg)
  293. : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
  294. void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
  295. //===----------------------------------------------------------------------===//
  296. // IRLinker implementation.
  297. //===----------------------------------------------------------------------===//
  298. namespace {
  299. class IRLinker;
  300. /// Creates prototypes for functions that are lazily linked on the fly. This
  301. /// speeds up linking for modules with many/ lazily linked functions of which
  302. /// few get used.
  303. class GlobalValueMaterializer final : public ValueMaterializer {
  304. IRLinker &TheIRLinker;
  305. public:
  306. GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
  307. Value *materialize(Value *V) override;
  308. };
  309. class LocalValueMaterializer final : public ValueMaterializer {
  310. IRLinker &TheIRLinker;
  311. public:
  312. LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
  313. Value *materialize(Value *V) override;
  314. };
  315. /// Type of the Metadata map in \a ValueToValueMapTy.
  316. typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
  317. /// This is responsible for keeping track of the state used for moving data
  318. /// from SrcM to DstM.
  319. class IRLinker {
  320. Module &DstM;
  321. std::unique_ptr<Module> SrcM;
  322. /// See IRMover::move().
  323. std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
  324. TypeMapTy TypeMap;
  325. GlobalValueMaterializer GValMaterializer;
  326. LocalValueMaterializer LValMaterializer;
  327. /// A metadata map that's shared between IRLinker instances.
  328. MDMapT &SharedMDs;
  329. /// Mapping of values from what they used to be in Src, to what they are now
  330. /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
  331. /// due to the use of Value handles which the Linker doesn't actually need,
  332. /// but this allows us to reuse the ValueMapper code.
  333. ValueToValueMapTy ValueMap;
  334. ValueToValueMapTy IndirectSymbolValueMap;
  335. DenseSet<GlobalValue *> ValuesToLink;
  336. std::vector<GlobalValue *> Worklist;
  337. std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
  338. void maybeAdd(GlobalValue *GV) {
  339. if (ValuesToLink.insert(GV).second)
  340. Worklist.push_back(GV);
  341. }
  342. /// Whether we are importing globals for ThinLTO, as opposed to linking the
  343. /// source module. If this flag is set, it means that we can rely on some
  344. /// other object file to define any non-GlobalValue entities defined by the
  345. /// source module. This currently causes us to not link retained types in
  346. /// debug info metadata and module inline asm.
  347. bool IsPerformingImport;
  348. /// Set to true when all global value body linking is complete (including
  349. /// lazy linking). Used to prevent metadata linking from creating new
  350. /// references.
  351. bool DoneLinkingBodies = false;
  352. /// The Error encountered during materialization. We use an Optional here to
  353. /// avoid needing to manage an unconsumed success value.
  354. Optional<Error> FoundError;
  355. void setError(Error E) {
  356. if (E)
  357. FoundError = std::move(E);
  358. }
  359. /// Most of the errors produced by this module are inconvertible StringErrors.
  360. /// This convenience function lets us return one of those more easily.
  361. Error stringErr(const Twine &T) {
  362. return make_error<StringError>(T, inconvertibleErrorCode());
  363. }
  364. /// Entry point for mapping values and alternate context for mapping aliases.
  365. ValueMapper Mapper;
  366. unsigned IndirectSymbolMCID;
  367. /// Handles cloning of a global values from the source module into
  368. /// the destination module, including setting the attributes and visibility.
  369. GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
  370. void emitWarning(const Twine &Message) {
  371. SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
  372. }
  373. /// Given a global in the source module, return the global in the
  374. /// destination module that is being linked to, if any.
  375. GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
  376. // If the source has no name it can't link. If it has local linkage,
  377. // there is no name match-up going on.
  378. if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
  379. return nullptr;
  380. // Otherwise see if we have a match in the destination module's symtab.
  381. GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
  382. if (!DGV)
  383. return nullptr;
  384. // If we found a global with the same name in the dest module, but it has
  385. // internal linkage, we are really not doing any linkage here.
  386. if (DGV->hasLocalLinkage())
  387. return nullptr;
  388. // Otherwise, we do in fact link to the destination global.
  389. return DGV;
  390. }
  391. void computeTypeMapping();
  392. Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
  393. const GlobalVariable *SrcGV);
  394. /// Given the GlobaValue \p SGV in the source module, and the matching
  395. /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
  396. /// into the destination module.
  397. ///
  398. /// Note this code may call the client-provided \p AddLazyFor.
  399. bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
  400. Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
  401. bool ForIndirectSymbol);
  402. Error linkModuleFlagsMetadata();
  403. void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
  404. Error linkFunctionBody(Function &Dst, Function &Src);
  405. void linkIndirectSymbolBody(GlobalIndirectSymbol &Dst,
  406. GlobalIndirectSymbol &Src);
  407. Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
  408. /// Replace all types in the source AttributeList with the
  409. /// corresponding destination type.
  410. AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
  411. /// Functions that take care of cloning a specific global value type
  412. /// into the destination module.
  413. GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
  414. Function *copyFunctionProto(const Function *SF);
  415. GlobalValue *copyGlobalIndirectSymbolProto(const GlobalIndirectSymbol *SGIS);
  416. /// Perform "replace all uses with" operations. These work items need to be
  417. /// performed as part of materialization, but we postpone them to happen after
  418. /// materialization is done. The materializer called by ValueMapper is not
  419. /// expected to delete constants, as ValueMapper is holding pointers to some
  420. /// of them, but constant destruction may be indirectly triggered by RAUW.
  421. /// Hence, the need to move this out of the materialization call chain.
  422. void flushRAUWWorklist();
  423. /// When importing for ThinLTO, prevent importing of types listed on
  424. /// the DICompileUnit that we don't need a copy of in the importing
  425. /// module.
  426. void prepareCompileUnitsForImport();
  427. void linkNamedMDNodes();
  428. public:
  429. IRLinker(Module &DstM, MDMapT &SharedMDs,
  430. IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
  431. ArrayRef<GlobalValue *> ValuesToLink,
  432. std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
  433. bool IsPerformingImport)
  434. : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
  435. TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
  436. SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
  437. Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
  438. &GValMaterializer),
  439. IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
  440. IndirectSymbolValueMap, &LValMaterializer)) {
  441. ValueMap.getMDMap() = std::move(SharedMDs);
  442. for (GlobalValue *GV : ValuesToLink)
  443. maybeAdd(GV);
  444. if (IsPerformingImport)
  445. prepareCompileUnitsForImport();
  446. }
  447. ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
  448. Error run();
  449. Value *materialize(Value *V, bool ForIndirectSymbol);
  450. };
  451. }
  452. /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
  453. /// table. This is good for all clients except for us. Go through the trouble
  454. /// to force this back.
  455. static void forceRenaming(GlobalValue *GV, StringRef Name) {
  456. // If the global doesn't force its name or if it already has the right name,
  457. // there is nothing for us to do.
  458. if (GV->hasLocalLinkage() || GV->getName() == Name)
  459. return;
  460. Module *M = GV->getParent();
  461. // If there is a conflict, rename the conflict.
  462. if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
  463. GV->takeName(ConflictGV);
  464. ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
  465. assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
  466. } else {
  467. GV->setName(Name); // Force the name back
  468. }
  469. }
  470. Value *GlobalValueMaterializer::materialize(Value *SGV) {
  471. return TheIRLinker.materialize(SGV, false);
  472. }
  473. Value *LocalValueMaterializer::materialize(Value *SGV) {
  474. return TheIRLinker.materialize(SGV, true);
  475. }
  476. Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
  477. auto *SGV = dyn_cast<GlobalValue>(V);
  478. if (!SGV)
  479. return nullptr;
  480. // When linking a global from other modules than source & dest, skip
  481. // materializing it because it would be mapped later when its containing
  482. // module is linked. Linking it now would potentially pull in many types that
  483. // may not be mapped properly.
  484. if (SGV->getParent() != &DstM && SGV->getParent() != SrcM.get())
  485. return nullptr;
  486. Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
  487. if (!NewProto) {
  488. setError(NewProto.takeError());
  489. return nullptr;
  490. }
  491. if (!*NewProto)
  492. return nullptr;
  493. GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
  494. if (!New)
  495. return *NewProto;
  496. // If we already created the body, just return.
  497. if (auto *F = dyn_cast<Function>(New)) {
  498. if (!F->isDeclaration())
  499. return New;
  500. } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
  501. if (V->hasInitializer() || V->hasAppendingLinkage())
  502. return New;
  503. } else {
  504. auto *IS = cast<GlobalIndirectSymbol>(New);
  505. if (IS->getIndirectSymbol())
  506. return New;
  507. }
  508. // When linking a global for an indirect symbol, it will always be linked.
  509. // However we need to check if it was not already scheduled to satisfy a
  510. // reference from a regular global value initializer. We know if it has been
  511. // schedule if the "New" GlobalValue that is mapped here for the indirect
  512. // symbol is the same as the one already mapped. If there is an entry in the
  513. // ValueMap but the value is different, it means that the value already had a
  514. // definition in the destination module (linkonce for instance), but we need a
  515. // new definition for the indirect symbol ("New" will be different.
  516. if (ForIndirectSymbol && ValueMap.lookup(SGV) == New)
  517. return New;
  518. if (ForIndirectSymbol || shouldLink(New, *SGV))
  519. setError(linkGlobalValueBody(*New, *SGV));
  520. return New;
  521. }
  522. /// Loop through the global variables in the src module and merge them into the
  523. /// dest module.
  524. GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
  525. // No linking to be performed or linking from the source: simply create an
  526. // identical version of the symbol over in the dest module... the
  527. // initializer will be filled in later by LinkGlobalInits.
  528. GlobalVariable *NewDGV =
  529. new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
  530. SGVar->isConstant(), GlobalValue::ExternalLinkage,
  531. /*init*/ nullptr, SGVar->getName(),
  532. /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
  533. SGVar->getAddressSpace());
  534. NewDGV->setAlignment(MaybeAlign(SGVar->getAlignment()));
  535. NewDGV->copyAttributesFrom(SGVar);
  536. return NewDGV;
  537. }
  538. AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
  539. for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
  540. for (Attribute::AttrKind TypedAttr :
  541. {Attribute::ByVal, Attribute::StructRet, Attribute::ByRef}) {
  542. if (Attrs.hasAttribute(i, TypedAttr)) {
  543. if (Type *Ty = Attrs.getAttribute(i, TypedAttr).getValueAsType()) {
  544. Attrs = Attrs.replaceAttributeType(C, i, TypedAttr, TypeMap.get(Ty));
  545. break;
  546. }
  547. }
  548. }
  549. }
  550. return Attrs;
  551. }
  552. /// Link the function in the source module into the destination module if
  553. /// needed, setting up mapping information.
  554. Function *IRLinker::copyFunctionProto(const Function *SF) {
  555. // If there is no linkage to be performed or we are linking from the source,
  556. // bring SF over.
  557. auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
  558. GlobalValue::ExternalLinkage,
  559. SF->getAddressSpace(), SF->getName(), &DstM);
  560. F->copyAttributesFrom(SF);
  561. F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
  562. return F;
  563. }
  564. /// Set up prototypes for any indirect symbols that come over from the source
  565. /// module.
  566. GlobalValue *
  567. IRLinker::copyGlobalIndirectSymbolProto(const GlobalIndirectSymbol *SGIS) {
  568. // If there is no linkage to be performed or we're linking from the source,
  569. // bring over SGA.
  570. auto *Ty = TypeMap.get(SGIS->getValueType());
  571. GlobalIndirectSymbol *GIS;
  572. if (isa<GlobalAlias>(SGIS))
  573. GIS = GlobalAlias::create(Ty, SGIS->getAddressSpace(),
  574. GlobalValue::ExternalLinkage, SGIS->getName(),
  575. &DstM);
  576. else
  577. GIS = GlobalIFunc::create(Ty, SGIS->getAddressSpace(),
  578. GlobalValue::ExternalLinkage, SGIS->getName(),
  579. nullptr, &DstM);
  580. GIS->copyAttributesFrom(SGIS);
  581. return GIS;
  582. }
  583. GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
  584. bool ForDefinition) {
  585. GlobalValue *NewGV;
  586. if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
  587. NewGV = copyGlobalVariableProto(SGVar);
  588. } else if (auto *SF = dyn_cast<Function>(SGV)) {
  589. NewGV = copyFunctionProto(SF);
  590. } else {
  591. if (ForDefinition)
  592. NewGV = copyGlobalIndirectSymbolProto(cast<GlobalIndirectSymbol>(SGV));
  593. else if (SGV->getValueType()->isFunctionTy())
  594. NewGV =
  595. Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
  596. GlobalValue::ExternalLinkage, SGV->getAddressSpace(),
  597. SGV->getName(), &DstM);
  598. else
  599. NewGV =
  600. new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
  601. /*isConstant*/ false, GlobalValue::ExternalLinkage,
  602. /*init*/ nullptr, SGV->getName(),
  603. /*insertbefore*/ nullptr,
  604. SGV->getThreadLocalMode(), SGV->getAddressSpace());
  605. }
  606. if (ForDefinition)
  607. NewGV->setLinkage(SGV->getLinkage());
  608. else if (SGV->hasExternalWeakLinkage())
  609. NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
  610. if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
  611. // Metadata for global variables and function declarations is copied eagerly.
  612. if (isa<GlobalVariable>(SGV) || SGV->isDeclaration())
  613. NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
  614. }
  615. // Remove these copied constants in case this stays a declaration, since
  616. // they point to the source module. If the def is linked the values will
  617. // be mapped in during linkFunctionBody.
  618. if (auto *NewF = dyn_cast<Function>(NewGV)) {
  619. NewF->setPersonalityFn(nullptr);
  620. NewF->setPrefixData(nullptr);
  621. NewF->setPrologueData(nullptr);
  622. }
  623. return NewGV;
  624. }
  625. static StringRef getTypeNamePrefix(StringRef Name) {
  626. size_t DotPos = Name.rfind('.');
  627. return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
  628. !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
  629. ? Name
  630. : Name.substr(0, DotPos);
  631. }
  632. /// Loop over all of the linked values to compute type mappings. For example,
  633. /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
  634. /// types 'Foo' but one got renamed when the module was loaded into the same
  635. /// LLVMContext.
  636. void IRLinker::computeTypeMapping() {
  637. for (GlobalValue &SGV : SrcM->globals()) {
  638. GlobalValue *DGV = getLinkedToGlobal(&SGV);
  639. if (!DGV)
  640. continue;
  641. if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
  642. TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
  643. continue;
  644. }
  645. // Unify the element type of appending arrays.
  646. ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
  647. ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
  648. TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
  649. }
  650. for (GlobalValue &SGV : *SrcM)
  651. if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
  652. if (DGV->getType() == SGV.getType()) {
  653. // If the types of DGV and SGV are the same, it means that DGV is from
  654. // the source module and got added to DstM from a shared metadata. We
  655. // shouldn't map this type to itself in case the type's components get
  656. // remapped to a new type from DstM (for instance, during the loop over
  657. // SrcM->getIdentifiedStructTypes() below).
  658. continue;
  659. }
  660. TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
  661. }
  662. for (GlobalValue &SGV : SrcM->aliases())
  663. if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
  664. TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
  665. // Incorporate types by name, scanning all the types in the source module.
  666. // At this point, the destination module may have a type "%foo = { i32 }" for
  667. // example. When the source module got loaded into the same LLVMContext, if
  668. // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
  669. std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
  670. for (StructType *ST : Types) {
  671. if (!ST->hasName())
  672. continue;
  673. if (TypeMap.DstStructTypesSet.hasType(ST)) {
  674. // This is actually a type from the destination module.
  675. // getIdentifiedStructTypes() can have found it by walking debug info
  676. // metadata nodes, some of which get linked by name when ODR Type Uniquing
  677. // is enabled on the Context, from the source to the destination module.
  678. continue;
  679. }
  680. auto STTypePrefix = getTypeNamePrefix(ST->getName());
  681. if (STTypePrefix.size() == ST->getName().size())
  682. continue;
  683. // Check to see if the destination module has a struct with the prefix name.
  684. StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
  685. if (!DST)
  686. continue;
  687. // Don't use it if this actually came from the source module. They're in
  688. // the same LLVMContext after all. Also don't use it unless the type is
  689. // actually used in the destination module. This can happen in situations
  690. // like this:
  691. //
  692. // Module A Module B
  693. // -------- --------
  694. // %Z = type { %A } %B = type { %C.1 }
  695. // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
  696. // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
  697. // %C = type { i8* } %B.3 = type { %C.1 }
  698. //
  699. // When we link Module B with Module A, the '%B' in Module B is
  700. // used. However, that would then use '%C.1'. But when we process '%C.1',
  701. // we prefer to take the '%C' version. So we are then left with both
  702. // '%C.1' and '%C' being used for the same types. This leads to some
  703. // variables using one type and some using the other.
  704. if (TypeMap.DstStructTypesSet.hasType(DST))
  705. TypeMap.addTypeMapping(DST, ST);
  706. }
  707. // Now that we have discovered all of the type equivalences, get a body for
  708. // any 'opaque' types in the dest module that are now resolved.
  709. TypeMap.linkDefinedTypeBodies();
  710. }
  711. static void getArrayElements(const Constant *C,
  712. SmallVectorImpl<Constant *> &Dest) {
  713. unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
  714. for (unsigned i = 0; i != NumElements; ++i)
  715. Dest.push_back(C->getAggregateElement(i));
  716. }
  717. /// If there were any appending global variables, link them together now.
  718. Expected<Constant *>
  719. IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
  720. const GlobalVariable *SrcGV) {
  721. // Check that both variables have compatible properties.
  722. if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
  723. if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
  724. return stringErr(
  725. "Linking globals named '" + SrcGV->getName() +
  726. "': can only link appending global with another appending "
  727. "global!");
  728. if (DstGV->isConstant() != SrcGV->isConstant())
  729. return stringErr("Appending variables linked with different const'ness!");
  730. if (DstGV->getAlignment() != SrcGV->getAlignment())
  731. return stringErr(
  732. "Appending variables with different alignment need to be linked!");
  733. if (DstGV->getVisibility() != SrcGV->getVisibility())
  734. return stringErr(
  735. "Appending variables with different visibility need to be linked!");
  736. if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
  737. return stringErr(
  738. "Appending variables with different unnamed_addr need to be linked!");
  739. if (DstGV->getSection() != SrcGV->getSection())
  740. return stringErr(
  741. "Appending variables with different section name need to be linked!");
  742. }
  743. // Do not need to do anything if source is a declaration.
  744. if (SrcGV->isDeclaration())
  745. return DstGV;
  746. Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
  747. ->getElementType();
  748. // FIXME: This upgrade is done during linking to support the C API. Once the
  749. // old form is deprecated, we should move this upgrade to
  750. // llvm::UpgradeGlobalVariable() and simplify the logic here and in
  751. // Mapper::mapAppendingVariable() in ValueMapper.cpp.
  752. StringRef Name = SrcGV->getName();
  753. bool IsNewStructor = false;
  754. bool IsOldStructor = false;
  755. if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
  756. if (cast<StructType>(EltTy)->getNumElements() == 3)
  757. IsNewStructor = true;
  758. else
  759. IsOldStructor = true;
  760. }
  761. PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
  762. if (IsOldStructor) {
  763. auto &ST = *cast<StructType>(EltTy);
  764. Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
  765. EltTy = StructType::get(SrcGV->getContext(), Tys, false);
  766. }
  767. uint64_t DstNumElements = 0;
  768. if (DstGV && !DstGV->isDeclaration()) {
  769. ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
  770. DstNumElements = DstTy->getNumElements();
  771. // Check to see that they two arrays agree on type.
  772. if (EltTy != DstTy->getElementType())
  773. return stringErr("Appending variables with different element types!");
  774. }
  775. SmallVector<Constant *, 16> SrcElements;
  776. getArrayElements(SrcGV->getInitializer(), SrcElements);
  777. if (IsNewStructor) {
  778. erase_if(SrcElements, [this](Constant *E) {
  779. auto *Key =
  780. dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
  781. if (!Key)
  782. return false;
  783. GlobalValue *DGV = getLinkedToGlobal(Key);
  784. return !shouldLink(DGV, *Key);
  785. });
  786. }
  787. uint64_t NewSize = DstNumElements + SrcElements.size();
  788. ArrayType *NewType = ArrayType::get(EltTy, NewSize);
  789. // Create the new global variable.
  790. GlobalVariable *NG = new GlobalVariable(
  791. DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
  792. /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
  793. SrcGV->getAddressSpace());
  794. NG->copyAttributesFrom(SrcGV);
  795. forceRenaming(NG, SrcGV->getName());
  796. Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
  797. Mapper.scheduleMapAppendingVariable(
  798. *NG,
  799. (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
  800. IsOldStructor, SrcElements);
  801. // Replace any uses of the two global variables with uses of the new
  802. // global.
  803. if (DstGV) {
  804. RAUWWorklist.push_back(
  805. std::make_pair(DstGV, ConstantExpr::getBitCast(NG, DstGV->getType())));
  806. }
  807. return Ret;
  808. }
  809. bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
  810. if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
  811. return true;
  812. if (DGV && !DGV->isDeclarationForLinker())
  813. return false;
  814. if (SGV.isDeclaration() || DoneLinkingBodies)
  815. return false;
  816. // Callback to the client to give a chance to lazily add the Global to the
  817. // list of value to link.
  818. bool LazilyAdded = false;
  819. AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
  820. maybeAdd(&GV);
  821. LazilyAdded = true;
  822. });
  823. return LazilyAdded;
  824. }
  825. Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
  826. bool ForIndirectSymbol) {
  827. GlobalValue *DGV = getLinkedToGlobal(SGV);
  828. bool ShouldLink = shouldLink(DGV, *SGV);
  829. // just missing from map
  830. if (ShouldLink) {
  831. auto I = ValueMap.find(SGV);
  832. if (I != ValueMap.end())
  833. return cast<Constant>(I->second);
  834. I = IndirectSymbolValueMap.find(SGV);
  835. if (I != IndirectSymbolValueMap.end())
  836. return cast<Constant>(I->second);
  837. }
  838. if (!ShouldLink && ForIndirectSymbol)
  839. DGV = nullptr;
  840. // Handle the ultra special appending linkage case first.
  841. if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
  842. return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
  843. cast<GlobalVariable>(SGV));
  844. GlobalValue *NewGV;
  845. if (DGV && !ShouldLink) {
  846. NewGV = DGV;
  847. } else {
  848. // If we are done linking global value bodies (i.e. we are performing
  849. // metadata linking), don't link in the global value due to this
  850. // reference, simply map it to null.
  851. if (DoneLinkingBodies)
  852. return nullptr;
  853. NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
  854. if (ShouldLink || !ForIndirectSymbol)
  855. forceRenaming(NewGV, SGV->getName());
  856. }
  857. // Overloaded intrinsics have overloaded types names as part of their
  858. // names. If we renamed overloaded types we should rename the intrinsic
  859. // as well.
  860. if (Function *F = dyn_cast<Function>(NewGV))
  861. if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F))
  862. NewGV = Remangled.getValue();
  863. if (ShouldLink || ForIndirectSymbol) {
  864. if (const Comdat *SC = SGV->getComdat()) {
  865. if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
  866. Comdat *DC = DstM.getOrInsertComdat(SC->getName());
  867. DC->setSelectionKind(SC->getSelectionKind());
  868. GO->setComdat(DC);
  869. }
  870. }
  871. }
  872. if (!ShouldLink && ForIndirectSymbol)
  873. NewGV->setLinkage(GlobalValue::InternalLinkage);
  874. Constant *C = NewGV;
  875. // Only create a bitcast if necessary. In particular, with
  876. // DebugTypeODRUniquing we may reach metadata in the destination module
  877. // containing a GV from the source module, in which case SGV will be
  878. // the same as DGV and NewGV, and TypeMap.get() will assert since it
  879. // assumes it is being invoked on a type in the source module.
  880. if (DGV && NewGV != SGV) {
  881. C = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  882. NewGV, TypeMap.get(SGV->getType()));
  883. }
  884. if (DGV && NewGV != DGV) {
  885. // Schedule "replace all uses with" to happen after materializing is
  886. // done. It is not safe to do it now, since ValueMapper may be holding
  887. // pointers to constants that will get deleted if RAUW runs.
  888. RAUWWorklist.push_back(std::make_pair(
  889. DGV,
  890. ConstantExpr::getPointerBitCastOrAddrSpaceCast(NewGV, DGV->getType())));
  891. }
  892. return C;
  893. }
  894. /// Update the initializers in the Dest module now that all globals that may be
  895. /// referenced are in Dest.
  896. void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
  897. // Figure out what the initializer looks like in the dest module.
  898. Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
  899. }
  900. /// Copy the source function over into the dest function and fix up references
  901. /// to values. At this point we know that Dest is an external function, and
  902. /// that Src is not.
  903. Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
  904. assert(Dst.isDeclaration() && !Src.isDeclaration());
  905. // Materialize if needed.
  906. if (Error Err = Src.materialize())
  907. return Err;
  908. // Link in the operands without remapping.
  909. if (Src.hasPrefixData())
  910. Dst.setPrefixData(Src.getPrefixData());
  911. if (Src.hasPrologueData())
  912. Dst.setPrologueData(Src.getPrologueData());
  913. if (Src.hasPersonalityFn())
  914. Dst.setPersonalityFn(Src.getPersonalityFn());
  915. // Copy over the metadata attachments without remapping.
  916. Dst.copyMetadata(&Src, 0);
  917. // Steal arguments and splice the body of Src into Dst.
  918. Dst.stealArgumentListFrom(Src);
  919. Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
  920. // Everything has been moved over. Remap it.
  921. Mapper.scheduleRemapFunction(Dst);
  922. return Error::success();
  923. }
  924. void IRLinker::linkIndirectSymbolBody(GlobalIndirectSymbol &Dst,
  925. GlobalIndirectSymbol &Src) {
  926. Mapper.scheduleMapGlobalIndirectSymbol(Dst, *Src.getIndirectSymbol(),
  927. IndirectSymbolMCID);
  928. }
  929. Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
  930. if (auto *F = dyn_cast<Function>(&Src))
  931. return linkFunctionBody(cast<Function>(Dst), *F);
  932. if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
  933. linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
  934. return Error::success();
  935. }
  936. linkIndirectSymbolBody(cast<GlobalIndirectSymbol>(Dst), cast<GlobalIndirectSymbol>(Src));
  937. return Error::success();
  938. }
  939. void IRLinker::flushRAUWWorklist() {
  940. for (const auto &Elem : RAUWWorklist) {
  941. GlobalValue *Old;
  942. Value *New;
  943. std::tie(Old, New) = Elem;
  944. Old->replaceAllUsesWith(New);
  945. Old->eraseFromParent();
  946. }
  947. RAUWWorklist.clear();
  948. }
  949. void IRLinker::prepareCompileUnitsForImport() {
  950. NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
  951. if (!SrcCompileUnits)
  952. return;
  953. // When importing for ThinLTO, prevent importing of types listed on
  954. // the DICompileUnit that we don't need a copy of in the importing
  955. // module. They will be emitted by the originating module.
  956. for (unsigned I = 0, E = SrcCompileUnits->getNumOperands(); I != E; ++I) {
  957. auto *CU = cast<DICompileUnit>(SrcCompileUnits->getOperand(I));
  958. assert(CU && "Expected valid compile unit");
  959. // Enums, macros, and retained types don't need to be listed on the
  960. // imported DICompileUnit. This means they will only be imported
  961. // if reached from the mapped IR.
  962. CU->replaceEnumTypes(nullptr);
  963. CU->replaceMacros(nullptr);
  964. CU->replaceRetainedTypes(nullptr);
  965. // The original definition (or at least its debug info - if the variable is
  966. // internalized and optimized away) will remain in the source module, so
  967. // there's no need to import them.
  968. // If LLVM ever does more advanced optimizations on global variables
  969. // (removing/localizing write operations, for instance) that can track
  970. // through debug info, this decision may need to be revisited - but do so
  971. // with care when it comes to debug info size. Emitting small CUs containing
  972. // only a few imported entities into every destination module may be very
  973. // size inefficient.
  974. CU->replaceGlobalVariables(nullptr);
  975. // Imported entities only need to be mapped in if they have local
  976. // scope, as those might correspond to an imported entity inside a
  977. // function being imported (any locally scoped imported entities that
  978. // don't end up referenced by an imported function will not be emitted
  979. // into the object). Imported entities not in a local scope
  980. // (e.g. on the namespace) only need to be emitted by the originating
  981. // module. Create a list of the locally scoped imported entities, and
  982. // replace the source CUs imported entity list with the new list, so
  983. // only those are mapped in.
  984. // FIXME: Locally-scoped imported entities could be moved to the
  985. // functions they are local to instead of listing them on the CU, and
  986. // we would naturally only link in those needed by function importing.
  987. SmallVector<TrackingMDNodeRef, 4> AllImportedModules;
  988. bool ReplaceImportedEntities = false;
  989. for (auto *IE : CU->getImportedEntities()) {
  990. DIScope *Scope = IE->getScope();
  991. assert(Scope && "Invalid Scope encoding!");
  992. if (isa<DILocalScope>(Scope))
  993. AllImportedModules.emplace_back(IE);
  994. else
  995. ReplaceImportedEntities = true;
  996. }
  997. if (ReplaceImportedEntities) {
  998. if (!AllImportedModules.empty())
  999. CU->replaceImportedEntities(MDTuple::get(
  1000. CU->getContext(),
  1001. SmallVector<Metadata *, 16>(AllImportedModules.begin(),
  1002. AllImportedModules.end())));
  1003. else
  1004. // If there were no local scope imported entities, we can map
  1005. // the whole list to nullptr.
  1006. CU->replaceImportedEntities(nullptr);
  1007. }
  1008. }
  1009. }
  1010. /// Insert all of the named MDNodes in Src into the Dest module.
  1011. void IRLinker::linkNamedMDNodes() {
  1012. const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
  1013. for (const NamedMDNode &NMD : SrcM->named_metadata()) {
  1014. // Don't link module flags here. Do them separately.
  1015. if (&NMD == SrcModFlags)
  1016. continue;
  1017. NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
  1018. // Add Src elements into Dest node.
  1019. for (const MDNode *Op : NMD.operands())
  1020. DestNMD->addOperand(Mapper.mapMDNode(*Op));
  1021. }
  1022. }
  1023. /// Merge the linker flags in Src into the Dest module.
  1024. Error IRLinker::linkModuleFlagsMetadata() {
  1025. // If the source module has no module flags, we are done.
  1026. const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
  1027. if (!SrcModFlags)
  1028. return Error::success();
  1029. // If the destination module doesn't have module flags yet, then just copy
  1030. // over the source module's flags.
  1031. NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
  1032. if (DstModFlags->getNumOperands() == 0) {
  1033. for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
  1034. DstModFlags->addOperand(SrcModFlags->getOperand(I));
  1035. return Error::success();
  1036. }
  1037. // First build a map of the existing module flags and requirements.
  1038. DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
  1039. SmallSetVector<MDNode *, 16> Requirements;
  1040. for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
  1041. MDNode *Op = DstModFlags->getOperand(I);
  1042. ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
  1043. MDString *ID = cast<MDString>(Op->getOperand(1));
  1044. if (Behavior->getZExtValue() == Module::Require) {
  1045. Requirements.insert(cast<MDNode>(Op->getOperand(2)));
  1046. } else {
  1047. Flags[ID] = std::make_pair(Op, I);
  1048. }
  1049. }
  1050. // Merge in the flags from the source module, and also collect its set of
  1051. // requirements.
  1052. for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
  1053. MDNode *SrcOp = SrcModFlags->getOperand(I);
  1054. ConstantInt *SrcBehavior =
  1055. mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
  1056. MDString *ID = cast<MDString>(SrcOp->getOperand(1));
  1057. MDNode *DstOp;
  1058. unsigned DstIndex;
  1059. std::tie(DstOp, DstIndex) = Flags.lookup(ID);
  1060. unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
  1061. // If this is a requirement, add it and continue.
  1062. if (SrcBehaviorValue == Module::Require) {
  1063. // If the destination module does not already have this requirement, add
  1064. // it.
  1065. if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
  1066. DstModFlags->addOperand(SrcOp);
  1067. }
  1068. continue;
  1069. }
  1070. // If there is no existing flag with this ID, just add it.
  1071. if (!DstOp) {
  1072. Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
  1073. DstModFlags->addOperand(SrcOp);
  1074. continue;
  1075. }
  1076. // Otherwise, perform a merge.
  1077. ConstantInt *DstBehavior =
  1078. mdconst::extract<ConstantInt>(DstOp->getOperand(0));
  1079. unsigned DstBehaviorValue = DstBehavior->getZExtValue();
  1080. auto overrideDstValue = [&]() {
  1081. DstModFlags->setOperand(DstIndex, SrcOp);
  1082. Flags[ID].first = SrcOp;
  1083. };
  1084. // If either flag has override behavior, handle it first.
  1085. if (DstBehaviorValue == Module::Override) {
  1086. // Diagnose inconsistent flags which both have override behavior.
  1087. if (SrcBehaviorValue == Module::Override &&
  1088. SrcOp->getOperand(2) != DstOp->getOperand(2))
  1089. return stringErr("linking module flags '" + ID->getString() +
  1090. "': IDs have conflicting override values in '" +
  1091. SrcM->getModuleIdentifier() + "' and '" +
  1092. DstM.getModuleIdentifier() + "'");
  1093. continue;
  1094. } else if (SrcBehaviorValue == Module::Override) {
  1095. // Update the destination flag to that of the source.
  1096. overrideDstValue();
  1097. continue;
  1098. }
  1099. // Diagnose inconsistent merge behavior types.
  1100. if (SrcBehaviorValue != DstBehaviorValue) {
  1101. bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
  1102. DstBehaviorValue == Module::Warning) ||
  1103. (DstBehaviorValue == Module::Max &&
  1104. SrcBehaviorValue == Module::Warning);
  1105. if (!MaxAndWarn)
  1106. return stringErr("linking module flags '" + ID->getString() +
  1107. "': IDs have conflicting behaviors in '" +
  1108. SrcM->getModuleIdentifier() + "' and '" +
  1109. DstM.getModuleIdentifier() + "'");
  1110. }
  1111. auto replaceDstValue = [&](MDNode *New) {
  1112. Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
  1113. MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
  1114. DstModFlags->setOperand(DstIndex, Flag);
  1115. Flags[ID].first = Flag;
  1116. };
  1117. // Emit a warning if the values differ and either source or destination
  1118. // request Warning behavior.
  1119. if ((DstBehaviorValue == Module::Warning ||
  1120. SrcBehaviorValue == Module::Warning) &&
  1121. SrcOp->getOperand(2) != DstOp->getOperand(2)) {
  1122. std::string Str;
  1123. raw_string_ostream(Str)
  1124. << "linking module flags '" << ID->getString()
  1125. << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
  1126. << "' from " << SrcM->getModuleIdentifier() << " with '"
  1127. << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
  1128. << ')';
  1129. emitWarning(Str);
  1130. }
  1131. // Choose the maximum if either source or destination request Max behavior.
  1132. if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
  1133. ConstantInt *DstValue =
  1134. mdconst::extract<ConstantInt>(DstOp->getOperand(2));
  1135. ConstantInt *SrcValue =
  1136. mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
  1137. // The resulting flag should have a Max behavior, and contain the maximum
  1138. // value from between the source and destination values.
  1139. Metadata *FlagOps[] = {
  1140. (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
  1141. (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
  1142. ->getOperand(2)};
  1143. MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
  1144. DstModFlags->setOperand(DstIndex, Flag);
  1145. Flags[ID].first = Flag;
  1146. continue;
  1147. }
  1148. // Perform the merge for standard behavior types.
  1149. switch (SrcBehaviorValue) {
  1150. case Module::Require:
  1151. case Module::Override:
  1152. llvm_unreachable("not possible");
  1153. case Module::Error: {
  1154. // Emit an error if the values differ.
  1155. if (SrcOp->getOperand(2) != DstOp->getOperand(2))
  1156. return stringErr("linking module flags '" + ID->getString() +
  1157. "': IDs have conflicting values in '" +
  1158. SrcM->getModuleIdentifier() + "' and '" +
  1159. DstM.getModuleIdentifier() + "'");
  1160. continue;
  1161. }
  1162. case Module::Warning: {
  1163. break;
  1164. }
  1165. case Module::Max: {
  1166. break;
  1167. }
  1168. case Module::Append: {
  1169. MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
  1170. MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
  1171. SmallVector<Metadata *, 8> MDs;
  1172. MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
  1173. MDs.append(DstValue->op_begin(), DstValue->op_end());
  1174. MDs.append(SrcValue->op_begin(), SrcValue->op_end());
  1175. replaceDstValue(MDNode::get(DstM.getContext(), MDs));
  1176. break;
  1177. }
  1178. case Module::AppendUnique: {
  1179. SmallSetVector<Metadata *, 16> Elts;
  1180. MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
  1181. MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
  1182. Elts.insert(DstValue->op_begin(), DstValue->op_end());
  1183. Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
  1184. replaceDstValue(MDNode::get(DstM.getContext(),
  1185. makeArrayRef(Elts.begin(), Elts.end())));
  1186. break;
  1187. }
  1188. }
  1189. }
  1190. // Check all of the requirements.
  1191. for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
  1192. MDNode *Requirement = Requirements[I];
  1193. MDString *Flag = cast<MDString>(Requirement->getOperand(0));
  1194. Metadata *ReqValue = Requirement->getOperand(1);
  1195. MDNode *Op = Flags[Flag].first;
  1196. if (!Op || Op->getOperand(2) != ReqValue)
  1197. return stringErr("linking module flags '" + Flag->getString() +
  1198. "': does not have the required value");
  1199. }
  1200. return Error::success();
  1201. }
  1202. /// Return InlineAsm adjusted with target-specific directives if required.
  1203. /// For ARM and Thumb, we have to add directives to select the appropriate ISA
  1204. /// to support mixing module-level inline assembly from ARM and Thumb modules.
  1205. static std::string adjustInlineAsm(const std::string &InlineAsm,
  1206. const Triple &Triple) {
  1207. if (Triple.getArch() == Triple::thumb || Triple.getArch() == Triple::thumbeb)
  1208. return ".text\n.balign 2\n.thumb\n" + InlineAsm;
  1209. if (Triple.getArch() == Triple::arm || Triple.getArch() == Triple::armeb)
  1210. return ".text\n.balign 4\n.arm\n" + InlineAsm;
  1211. return InlineAsm;
  1212. }
  1213. Error IRLinker::run() {
  1214. // Ensure metadata materialized before value mapping.
  1215. if (SrcM->getMaterializer())
  1216. if (Error Err = SrcM->getMaterializer()->materializeMetadata())
  1217. return Err;
  1218. // Inherit the target data from the source module if the destination module
  1219. // doesn't have one already.
  1220. if (DstM.getDataLayout().isDefault())
  1221. DstM.setDataLayout(SrcM->getDataLayout());
  1222. if (SrcM->getDataLayout() != DstM.getDataLayout()) {
  1223. emitWarning("Linking two modules of different data layouts: '" +
  1224. SrcM->getModuleIdentifier() + "' is '" +
  1225. SrcM->getDataLayoutStr() + "' whereas '" +
  1226. DstM.getModuleIdentifier() + "' is '" +
  1227. DstM.getDataLayoutStr() + "'\n");
  1228. }
  1229. // Copy the target triple from the source to dest if the dest's is empty.
  1230. if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
  1231. DstM.setTargetTriple(SrcM->getTargetTriple());
  1232. Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
  1233. if (!SrcM->getTargetTriple().empty()&&
  1234. !SrcTriple.isCompatibleWith(DstTriple))
  1235. emitWarning("Linking two modules of different target triples: '" +
  1236. SrcM->getModuleIdentifier() + "' is '" +
  1237. SrcM->getTargetTriple() + "' whereas '" +
  1238. DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
  1239. "'\n");
  1240. DstM.setTargetTriple(SrcTriple.merge(DstTriple));
  1241. // Loop over all of the linked values to compute type mappings.
  1242. computeTypeMapping();
  1243. std::reverse(Worklist.begin(), Worklist.end());
  1244. while (!Worklist.empty()) {
  1245. GlobalValue *GV = Worklist.back();
  1246. Worklist.pop_back();
  1247. // Already mapped.
  1248. if (ValueMap.find(GV) != ValueMap.end() ||
  1249. IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
  1250. continue;
  1251. assert(!GV->isDeclaration());
  1252. Mapper.mapValue(*GV);
  1253. if (FoundError)
  1254. return std::move(*FoundError);
  1255. flushRAUWWorklist();
  1256. }
  1257. // Note that we are done linking global value bodies. This prevents
  1258. // metadata linking from creating new references.
  1259. DoneLinkingBodies = true;
  1260. Mapper.addFlags(RF_NullMapMissingGlobalValues);
  1261. // Remap all of the named MDNodes in Src into the DstM module. We do this
  1262. // after linking GlobalValues so that MDNodes that reference GlobalValues
  1263. // are properly remapped.
  1264. linkNamedMDNodes();
  1265. if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
  1266. // Append the module inline asm string.
  1267. DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
  1268. SrcTriple));
  1269. } else if (IsPerformingImport) {
  1270. // Import any symver directives for symbols in DstM.
  1271. ModuleSymbolTable::CollectAsmSymvers(*SrcM,
  1272. [&](StringRef Name, StringRef Alias) {
  1273. if (DstM.getNamedValue(Name)) {
  1274. SmallString<256> S(".symver ");
  1275. S += Name;
  1276. S += ", ";
  1277. S += Alias;
  1278. DstM.appendModuleInlineAsm(S);
  1279. }
  1280. });
  1281. }
  1282. // Merge the module flags into the DstM module.
  1283. return linkModuleFlagsMetadata();
  1284. }
  1285. IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
  1286. : ETypes(E), IsPacked(P) {}
  1287. IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
  1288. : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
  1289. bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
  1290. return IsPacked == That.IsPacked && ETypes == That.ETypes;
  1291. }
  1292. bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
  1293. return !this->operator==(That);
  1294. }
  1295. StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
  1296. return DenseMapInfo<StructType *>::getEmptyKey();
  1297. }
  1298. StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
  1299. return DenseMapInfo<StructType *>::getTombstoneKey();
  1300. }
  1301. unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
  1302. return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
  1303. Key.IsPacked);
  1304. }
  1305. unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
  1306. return getHashValue(KeyTy(ST));
  1307. }
  1308. bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
  1309. const StructType *RHS) {
  1310. if (RHS == getEmptyKey() || RHS == getTombstoneKey())
  1311. return false;
  1312. return LHS == KeyTy(RHS);
  1313. }
  1314. bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
  1315. const StructType *RHS) {
  1316. if (RHS == getEmptyKey() || RHS == getTombstoneKey())
  1317. return LHS == RHS;
  1318. return KeyTy(LHS) == KeyTy(RHS);
  1319. }
  1320. void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
  1321. assert(!Ty->isOpaque());
  1322. NonOpaqueStructTypes.insert(Ty);
  1323. }
  1324. void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
  1325. assert(!Ty->isOpaque());
  1326. NonOpaqueStructTypes.insert(Ty);
  1327. bool Removed = OpaqueStructTypes.erase(Ty);
  1328. (void)Removed;
  1329. assert(Removed);
  1330. }
  1331. void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
  1332. assert(Ty->isOpaque());
  1333. OpaqueStructTypes.insert(Ty);
  1334. }
  1335. StructType *
  1336. IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
  1337. bool IsPacked) {
  1338. IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
  1339. auto I = NonOpaqueStructTypes.find_as(Key);
  1340. return I == NonOpaqueStructTypes.end() ? nullptr : *I;
  1341. }
  1342. bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
  1343. if (Ty->isOpaque())
  1344. return OpaqueStructTypes.count(Ty);
  1345. auto I = NonOpaqueStructTypes.find(Ty);
  1346. return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
  1347. }
  1348. IRMover::IRMover(Module &M) : Composite(M) {
  1349. TypeFinder StructTypes;
  1350. StructTypes.run(M, /* OnlyNamed */ false);
  1351. for (StructType *Ty : StructTypes) {
  1352. if (Ty->isOpaque())
  1353. IdentifiedStructTypes.addOpaque(Ty);
  1354. else
  1355. IdentifiedStructTypes.addNonOpaque(Ty);
  1356. }
  1357. // Self-map metadatas in the destination module. This is needed when
  1358. // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
  1359. // destination module may be reached from the source module.
  1360. for (auto *MD : StructTypes.getVisitedMetadata()) {
  1361. SharedMDs[MD].reset(const_cast<MDNode *>(MD));
  1362. }
  1363. }
  1364. Error IRMover::move(
  1365. std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
  1366. std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
  1367. bool IsPerformingImport) {
  1368. IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
  1369. std::move(Src), ValuesToLink, std::move(AddLazyFor),
  1370. IsPerformingImport);
  1371. Error E = TheIRLinker.run();
  1372. Composite.dropTriviallyDeadConstantArrays();
  1373. return E;
  1374. }