LLVM  mainline
LinkModules.cpp
Go to the documentation of this file.
00001 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the LLVM module linker.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Linker/Linker.h"
00015 #include "LinkDiagnosticInfo.h"
00016 #include "llvm-c/Linker.h"
00017 #include "llvm/ADT/SetVector.h"
00018 #include "llvm/ADT/StringSet.h"
00019 #include "llvm/IR/DiagnosticPrinter.h"
00020 #include "llvm/IR/LLVMContext.h"
00021 using namespace llvm;
00022 
00023 namespace {
00024 
00025 /// This is an implementation class for the LinkModules function, which is the
00026 /// entrypoint for this file.
00027 class ModuleLinker {
00028   IRMover &Mover;
00029   Module &SrcM;
00030 
00031   SetVector<GlobalValue *> ValuesToLink;
00032   StringSet<> Internalize;
00033 
00034   /// For symbol clashes, prefer those from Src.
00035   unsigned Flags;
00036 
00037   /// Function index passed into ModuleLinker for using in function
00038   /// importing/exporting handling.
00039   const FunctionInfoIndex *ImportIndex;
00040 
00041   /// Functions to import from source module, all other functions are
00042   /// imported as declarations instead of definitions.
00043   DenseSet<const GlobalValue *> *FunctionsToImport;
00044 
00045   /// Set to true if the given FunctionInfoIndex contains any functions
00046   /// from this source module, in which case we must conservatively assume
00047   /// that any of its functions may be imported into another module
00048   /// as part of a different backend compilation process.
00049   bool HasExportedFunctions = false;
00050 
00051   /// Association between metadata value id and temporary metadata that
00052   /// remains unmapped after function importing. Saved during function
00053   /// importing and consumed during the metadata linking postpass.
00054   DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
00055 
00056   /// Used as the callback for lazy linking.
00057   /// The mover has just hit GV and we have to decide if it, and other members
00058   /// of the same comdat, should be linked. Every member to be linked is passed
00059   /// to Add.
00060   void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
00061 
00062   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
00063   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
00064   bool shouldInternalizeLinkedSymbols() {
00065     return Flags & Linker::InternalizeLinkedSymbols;
00066   }
00067 
00068   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
00069                             const GlobalValue &Src);
00070 
00071   /// Should we have mover and linker error diag info?
00072   bool emitError(const Twine &Message) {
00073     SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
00074     return true;
00075   }
00076 
00077   bool getComdatLeader(Module &M, StringRef ComdatName,
00078                        const GlobalVariable *&GVar);
00079   bool computeResultingSelectionKind(StringRef ComdatName,
00080                                      Comdat::SelectionKind Src,
00081                                      Comdat::SelectionKind Dst,
00082                                      Comdat::SelectionKind &Result,
00083                                      bool &LinkFromSrc);
00084   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
00085       ComdatsChosen;
00086   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
00087                        bool &LinkFromSrc);
00088   // Keep track of the global value members of each comdat in source.
00089   DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
00090 
00091   /// Given a global in the source module, return the global in the
00092   /// destination module that is being linked to, if any.
00093   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
00094     Module &DstM = Mover.getModule();
00095     // If the source has no name it can't link.  If it has local linkage,
00096     // there is no name match-up going on.
00097     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
00098       return nullptr;
00099 
00100     // Otherwise see if we have a match in the destination module's symtab.
00101     GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
00102     if (!DGV)
00103       return nullptr;
00104 
00105     // If we found a global with the same name in the dest module, but it has
00106     // internal linkage, we are really not doing any linkage here.
00107     if (DGV->hasLocalLinkage())
00108       return nullptr;
00109 
00110     // Otherwise, we do in fact link to the destination global.
00111     return DGV;
00112   }
00113 
00114   bool linkIfNeeded(GlobalValue &GV);
00115 
00116   /// Helper method to check if we are importing from the current source
00117   /// module.
00118   bool isPerformingImport() const { return FunctionsToImport != nullptr; }
00119 
00120   /// If we are importing from the source module, checks if we should
00121   /// import SGV as a definition, otherwise import as a declaration.
00122   bool doImportAsDefinition(const GlobalValue *SGV);
00123 
00124 public:
00125   ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
00126                const FunctionInfoIndex *Index = nullptr,
00127                DenseSet<const GlobalValue *> *FunctionsToImport = nullptr,
00128                DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr)
00129       : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
00130         FunctionsToImport(FunctionsToImport),
00131         ValIDToTempMDMap(ValIDToTempMDMap) {
00132     assert((ImportIndex || !FunctionsToImport) &&
00133            "Expect a FunctionInfoIndex when importing");
00134     // If we have a FunctionInfoIndex but no function to import,
00135     // then this is the primary module being compiled in a ThinLTO
00136     // backend compilation, and we need to see if it has functions that
00137     // may be exported to another backend compilation.
00138     if (ImportIndex && !FunctionsToImport)
00139       HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
00140   }
00141 
00142   bool run();
00143 };
00144 
00145 /// Class to handle necessary GlobalValue changes required by ThinLTO including
00146 /// linkage changes and any necessary renaming.
00147 class ThinLTOGlobalProcessing {
00148   /// The Module which we are exporting or importing functions from.
00149   Module &M;
00150 
00151   /// Function index passed in for function importing/exporting handling.
00152   const FunctionInfoIndex *ImportIndex;
00153 
00154   /// Functions to import from this module, all other functions will be
00155   /// imported as declarations instead of definitions.
00156   DenseSet<const GlobalValue *> *FunctionsToImport;
00157 
00158   /// Set to true if the given FunctionInfoIndex contains any functions
00159   /// from this source module, in which case we must conservatively assume
00160   /// that any of its functions may be imported into another module
00161   /// as part of a different backend compilation process.
00162   bool HasExportedFunctions = false;
00163 
00164   /// Populated during ThinLTO global processing with locals promoted
00165   /// to global scope in an exporting module, which now need to be linked
00166   /// in if calling from the ModuleLinker.
00167   SetVector<GlobalValue *> NewExportedValues;
00168 
00169   /// Check if we should promote the given local value to global scope.
00170   bool doPromoteLocalToGlobal(const GlobalValue *SGV);
00171 
00172   /// Helper methods to check if we are importing from or potentially
00173   /// exporting from the current source module.
00174   bool isPerformingImport() const { return FunctionsToImport != nullptr; }
00175   bool isModuleExporting() const { return HasExportedFunctions; }
00176 
00177   /// If we are importing from the source module, checks if we should
00178   /// import SGV as a definition, otherwise import as a declaration.
00179   bool doImportAsDefinition(const GlobalValue *SGV);
00180 
00181   /// Get the name for SGV that should be used in the linked destination
00182   /// module. Specifically, this handles the case where we need to rename
00183   /// a local that is being promoted to global scope.
00184   std::string getName(const GlobalValue *SGV);
00185 
00186   /// Process globals so that they can be used in ThinLTO. This includes
00187   /// promoting local variables so that they can be reference externally by
00188   /// thin lto imported globals and converting strong external globals to
00189   /// available_externally.
00190   void processGlobalsForThinLTO();
00191   void processGlobalForThinLTO(GlobalValue &GV);
00192 
00193   /// Get the new linkage for SGV that should be used in the linked destination
00194   /// module. Specifically, for ThinLTO importing or exporting it may need
00195   /// to be adjusted.
00196   GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
00197 
00198 public:
00199   ThinLTOGlobalProcessing(
00200       Module &M, const FunctionInfoIndex *Index,
00201       DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
00202       : M(M), ImportIndex(Index), FunctionsToImport(FunctionsToImport) {
00203     // If we have a FunctionInfoIndex but no function to import,
00204     // then this is the primary module being compiled in a ThinLTO
00205     // backend compilation, and we need to see if it has functions that
00206     // may be exported to another backend compilation.
00207     if (!FunctionsToImport)
00208       HasExportedFunctions = ImportIndex->hasExportedFunctions(M);
00209   }
00210 
00211   bool run();
00212 
00213   /// Access the promoted globals that are now exported and need to be linked.
00214   SetVector<GlobalValue *> &getNewExportedValues() { return NewExportedValues; }
00215 };
00216 }
00217 
00218 /// Checks if we should import SGV as a definition, otherwise import as a
00219 /// declaration.
00220 static bool
00221 doImportAsDefinitionImpl(const GlobalValue *SGV,
00222                          DenseSet<const GlobalValue *> *FunctionsToImport) {
00223   auto *GA = dyn_cast<GlobalAlias>(SGV);
00224   if (GA) {
00225     if (GA->hasWeakAnyLinkage())
00226       return false;
00227     const GlobalObject *GO = GA->getBaseObject();
00228     if (!GO->hasLinkOnceODRLinkage())
00229       return false;
00230     return doImportAsDefinitionImpl(GO, FunctionsToImport);
00231   }
00232   // Always import GlobalVariable definitions, except for the special
00233   // case of WeakAny which are imported as ExternalWeak declarations
00234   // (see comments in ModuleLinker::getLinkage). The linkage changes
00235   // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
00236   // global variables with external linkage are transformed to
00237   // available_externally definitions, which are ultimately turned into
00238   // declarations after the EliminateAvailableExternally pass).
00239   if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
00240       !SGV->hasWeakAnyLinkage())
00241     return true;
00242   // Only import the function requested for importing.
00243   auto *SF = dyn_cast<Function>(SGV);
00244   if (SF && FunctionsToImport->count(SF))
00245     return true;
00246   // Otherwise no.
00247   return false;
00248 }
00249 
00250 bool ThinLTOGlobalProcessing::doImportAsDefinition(const GlobalValue *SGV) {
00251   if (!isPerformingImport())
00252     return false;
00253   return doImportAsDefinitionImpl(SGV, FunctionsToImport);
00254 }
00255 
00256 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
00257   if (!isPerformingImport())
00258     return false;
00259   return doImportAsDefinitionImpl(SGV, FunctionsToImport);
00260 }
00261 
00262 bool ThinLTOGlobalProcessing::doPromoteLocalToGlobal(const GlobalValue *SGV) {
00263   assert(SGV->hasLocalLinkage());
00264   // Both the imported references and the original local variable must
00265   // be promoted.
00266   if (!isPerformingImport() && !isModuleExporting())
00267     return false;
00268 
00269   // Local const variables never need to be promoted unless they are address
00270   // taken. The imported uses can simply use the clone created in this module.
00271   // For now we are conservative in determining which variables are not
00272   // address taken by checking the unnamed addr flag. To be more aggressive,
00273   // the address taken information must be checked earlier during parsing
00274   // of the module and recorded in the function index for use when importing
00275   // from that module.
00276   auto *GVar = dyn_cast<GlobalVariable>(SGV);
00277   if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
00278     return false;
00279 
00280   // Eventually we only need to promote functions in the exporting module that
00281   // are referenced by a potentially exported function (i.e. one that is in the
00282   // function index).
00283   return true;
00284 }
00285 
00286 std::string ThinLTOGlobalProcessing::getName(const GlobalValue *SGV) {
00287   // For locals that must be promoted to global scope, ensure that
00288   // the promoted name uniquely identifies the copy in the original module,
00289   // using the ID assigned during combined index creation. When importing,
00290   // we rename all locals (not just those that are promoted) in order to
00291   // avoid naming conflicts between locals imported from different modules.
00292   if (SGV->hasLocalLinkage() &&
00293       (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
00294     return FunctionInfoIndex::getGlobalNameForLocal(
00295         SGV->getName(),
00296         ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
00297   return SGV->getName();
00298 }
00299 
00300 GlobalValue::LinkageTypes
00301 ThinLTOGlobalProcessing::getLinkage(const GlobalValue *SGV) {
00302   // Any local variable that is referenced by an exported function needs
00303   // to be promoted to global scope. Since we don't currently know which
00304   // functions reference which local variables/functions, we must treat
00305   // all as potentially exported if this module is exporting anything.
00306   if (isModuleExporting()) {
00307     if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
00308       return GlobalValue::ExternalLinkage;
00309     return SGV->getLinkage();
00310   }
00311 
00312   // Otherwise, if we aren't importing, no linkage change is needed.
00313   if (!isPerformingImport())
00314     return SGV->getLinkage();
00315 
00316   switch (SGV->getLinkage()) {
00317   case GlobalValue::ExternalLinkage:
00318     // External defnitions are converted to available_externally
00319     // definitions upon import, so that they are available for inlining
00320     // and/or optimization, but are turned into declarations later
00321     // during the EliminateAvailableExternally pass.
00322     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
00323       return GlobalValue::AvailableExternallyLinkage;
00324     // An imported external declaration stays external.
00325     return SGV->getLinkage();
00326 
00327   case GlobalValue::AvailableExternallyLinkage:
00328     // An imported available_externally definition converts
00329     // to external if imported as a declaration.
00330     if (!doImportAsDefinition(SGV))
00331       return GlobalValue::ExternalLinkage;
00332     // An imported available_externally declaration stays that way.
00333     return SGV->getLinkage();
00334 
00335   case GlobalValue::LinkOnceAnyLinkage:
00336   case GlobalValue::LinkOnceODRLinkage:
00337     // These both stay the same when importing the definition.
00338     // The ThinLTO pass will eventually force-import their definitions.
00339     return SGV->getLinkage();
00340 
00341   case GlobalValue::WeakAnyLinkage:
00342     // Can't import weak_any definitions correctly, or we might change the
00343     // program semantics, since the linker will pick the first weak_any
00344     // definition and importing would change the order they are seen by the
00345     // linker. The module linking caller needs to enforce this.
00346     assert(!doImportAsDefinition(SGV));
00347     // If imported as a declaration, it becomes external_weak.
00348     return GlobalValue::ExternalWeakLinkage;
00349 
00350   case GlobalValue::WeakODRLinkage:
00351     // For weak_odr linkage, there is a guarantee that all copies will be
00352     // equivalent, so the issue described above for weak_any does not exist,
00353     // and the definition can be imported. It can be treated similarly
00354     // to an imported externally visible global value.
00355     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
00356       return GlobalValue::AvailableExternallyLinkage;
00357     else
00358       return GlobalValue::ExternalLinkage;
00359 
00360   case GlobalValue::AppendingLinkage:
00361     // It would be incorrect to import an appending linkage variable,
00362     // since it would cause global constructors/destructors to be
00363     // executed multiple times. This should have already been handled
00364     // by linkIfNeeded, and we will assert in shouldLinkFromSource
00365     // if we try to import, so we simply return AppendingLinkage.
00366     return GlobalValue::AppendingLinkage;
00367 
00368   case GlobalValue::InternalLinkage:
00369   case GlobalValue::PrivateLinkage:
00370     // If we are promoting the local to global scope, it is handled
00371     // similarly to a normal externally visible global.
00372     if (doPromoteLocalToGlobal(SGV)) {
00373       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
00374         return GlobalValue::AvailableExternallyLinkage;
00375       else
00376         return GlobalValue::ExternalLinkage;
00377     }
00378     // A non-promoted imported local definition stays local.
00379     // The ThinLTO pass will eventually force-import their definitions.
00380     return SGV->getLinkage();
00381 
00382   case GlobalValue::ExternalWeakLinkage:
00383     // External weak doesn't apply to definitions, must be a declaration.
00384     assert(!doImportAsDefinition(SGV));
00385     // Linkage stays external_weak.
00386     return SGV->getLinkage();
00387 
00388   case GlobalValue::CommonLinkage:
00389     // Linkage stays common on definitions.
00390     // The ThinLTO pass will eventually force-import their definitions.
00391     return SGV->getLinkage();
00392   }
00393 
00394   llvm_unreachable("unknown linkage type");
00395 }
00396 
00397 static GlobalValue::VisibilityTypes
00398 getMinVisibility(GlobalValue::VisibilityTypes A,
00399                  GlobalValue::VisibilityTypes B) {
00400   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
00401     return GlobalValue::HiddenVisibility;
00402   if (A == GlobalValue::ProtectedVisibility ||
00403       B == GlobalValue::ProtectedVisibility)
00404     return GlobalValue::ProtectedVisibility;
00405   return GlobalValue::DefaultVisibility;
00406 }
00407 
00408 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
00409                                    const GlobalVariable *&GVar) {
00410   const GlobalValue *GVal = M.getNamedValue(ComdatName);
00411   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
00412     GVal = GA->getBaseObject();
00413     if (!GVal)
00414       // We cannot resolve the size of the aliasee yet.
00415       return emitError("Linking COMDATs named '" + ComdatName +
00416                        "': COMDAT key involves incomputable alias size.");
00417   }
00418 
00419   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
00420   if (!GVar)
00421     return emitError(
00422         "Linking COMDATs named '" + ComdatName +
00423         "': GlobalVariable required for data dependent selection!");
00424 
00425   return false;
00426 }
00427 
00428 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
00429                                                  Comdat::SelectionKind Src,
00430                                                  Comdat::SelectionKind Dst,
00431                                                  Comdat::SelectionKind &Result,
00432                                                  bool &LinkFromSrc) {
00433   Module &DstM = Mover.getModule();
00434   // The ability to mix Comdat::SelectionKind::Any with
00435   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
00436   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
00437                          Dst == Comdat::SelectionKind::Largest;
00438   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
00439                          Src == Comdat::SelectionKind::Largest;
00440   if (DstAnyOrLargest && SrcAnyOrLargest) {
00441     if (Dst == Comdat::SelectionKind::Largest ||
00442         Src == Comdat::SelectionKind::Largest)
00443       Result = Comdat::SelectionKind::Largest;
00444     else
00445       Result = Comdat::SelectionKind::Any;
00446   } else if (Src == Dst) {
00447     Result = Dst;
00448   } else {
00449     return emitError("Linking COMDATs named '" + ComdatName +
00450                      "': invalid selection kinds!");
00451   }
00452 
00453   switch (Result) {
00454   case Comdat::SelectionKind::Any:
00455     // Go with Dst.
00456     LinkFromSrc = false;
00457     break;
00458   case Comdat::SelectionKind::NoDuplicates:
00459     return emitError("Linking COMDATs named '" + ComdatName +
00460                      "': noduplicates has been violated!");
00461   case Comdat::SelectionKind::ExactMatch:
00462   case Comdat::SelectionKind::Largest:
00463   case Comdat::SelectionKind::SameSize: {
00464     const GlobalVariable *DstGV;
00465     const GlobalVariable *SrcGV;
00466     if (getComdatLeader(DstM, ComdatName, DstGV) ||
00467         getComdatLeader(SrcM, ComdatName, SrcGV))
00468       return true;
00469 
00470     const DataLayout &DstDL = DstM.getDataLayout();
00471     const DataLayout &SrcDL = SrcM.getDataLayout();
00472     uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
00473     uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
00474     if (Result == Comdat::SelectionKind::ExactMatch) {
00475       if (SrcGV->getInitializer() != DstGV->getInitializer())
00476         return emitError("Linking COMDATs named '" + ComdatName +
00477                          "': ExactMatch violated!");
00478       LinkFromSrc = false;
00479     } else if (Result == Comdat::SelectionKind::Largest) {
00480       LinkFromSrc = SrcSize > DstSize;
00481     } else if (Result == Comdat::SelectionKind::SameSize) {
00482       if (SrcSize != DstSize)
00483         return emitError("Linking COMDATs named '" + ComdatName +
00484                          "': SameSize violated!");
00485       LinkFromSrc = false;
00486     } else {
00487       llvm_unreachable("unknown selection kind");
00488     }
00489     break;
00490   }
00491   }
00492 
00493   return false;
00494 }
00495 
00496 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
00497                                    Comdat::SelectionKind &Result,
00498                                    bool &LinkFromSrc) {
00499   Module &DstM = Mover.getModule();
00500   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
00501   StringRef ComdatName = SrcC->getName();
00502   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
00503   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
00504 
00505   if (DstCI == ComdatSymTab.end()) {
00506     // Use the comdat if it is only available in one of the modules.
00507     LinkFromSrc = true;
00508     Result = SSK;
00509     return false;
00510   }
00511 
00512   const Comdat *DstC = &DstCI->second;
00513   Comdat::SelectionKind DSK = DstC->getSelectionKind();
00514   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
00515                                        LinkFromSrc);
00516 }
00517 
00518 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
00519                                         const GlobalValue &Dest,
00520                                         const GlobalValue &Src) {
00521 
00522   // Should we unconditionally use the Src?
00523   if (shouldOverrideFromSrc()) {
00524     LinkFromSrc = true;
00525     return false;
00526   }
00527 
00528   // We always have to add Src if it has appending linkage.
00529   if (Src.hasAppendingLinkage()) {
00530     // Should have prevented importing for appending linkage in linkIfNeeded.
00531     assert(!isPerformingImport());
00532     LinkFromSrc = true;
00533     return false;
00534   }
00535 
00536   bool SrcIsDeclaration = Src.isDeclarationForLinker();
00537   bool DestIsDeclaration = Dest.isDeclarationForLinker();
00538 
00539   if (isPerformingImport()) {
00540     if (isa<Function>(&Src)) {
00541       // For functions, LinkFromSrc iff this is a function requested
00542       // for importing. For variables, decide below normally.
00543       LinkFromSrc = FunctionsToImport->count(&Src);
00544       return false;
00545     }
00546 
00547     // Check if this is an alias with an already existing definition
00548     // in Dest, which must have come from a prior importing pass from
00549     // the same Src module. Unlike imported function and variable
00550     // definitions, which are imported as available_externally and are
00551     // not definitions for the linker, that is not a valid linkage for
00552     // imported aliases which must be definitions. Simply use the existing
00553     // Dest copy.
00554     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
00555       assert(isa<GlobalAlias>(&Dest));
00556       LinkFromSrc = false;
00557       return false;
00558     }
00559   }
00560 
00561   if (SrcIsDeclaration) {
00562     // If Src is external or if both Src & Dest are external..  Just link the
00563     // external globals, we aren't adding anything.
00564     if (Src.hasDLLImportStorageClass()) {
00565       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
00566       LinkFromSrc = DestIsDeclaration;
00567       return false;
00568     }
00569     // If the Dest is weak, use the source linkage.
00570     if (Dest.hasExternalWeakLinkage()) {
00571       LinkFromSrc = true;
00572       return false;
00573     }
00574     // Link an available_externally over a declaration.
00575     LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
00576     return false;
00577   }
00578 
00579   if (DestIsDeclaration) {
00580     // If Dest is external but Src is not:
00581     LinkFromSrc = true;
00582     return false;
00583   }
00584 
00585   if (Src.hasCommonLinkage()) {
00586     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
00587       LinkFromSrc = true;
00588       return false;
00589     }
00590 
00591     if (!Dest.hasCommonLinkage()) {
00592       LinkFromSrc = false;
00593       return false;
00594     }
00595 
00596     const DataLayout &DL = Dest.getParent()->getDataLayout();
00597     uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
00598     uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
00599     LinkFromSrc = SrcSize > DestSize;
00600     return false;
00601   }
00602 
00603   if (Src.isWeakForLinker()) {
00604     assert(!Dest.hasExternalWeakLinkage());
00605     assert(!Dest.hasAvailableExternallyLinkage());
00606 
00607     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
00608       LinkFromSrc = true;
00609       return false;
00610     }
00611 
00612     LinkFromSrc = false;
00613     return false;
00614   }
00615 
00616   if (Dest.isWeakForLinker()) {
00617     assert(Src.hasExternalLinkage());
00618     LinkFromSrc = true;
00619     return false;
00620   }
00621 
00622   assert(!Src.hasExternalWeakLinkage());
00623   assert(!Dest.hasExternalWeakLinkage());
00624   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
00625          "Unexpected linkage type!");
00626   return emitError("Linking globals named '" + Src.getName() +
00627                    "': symbol multiply defined!");
00628 }
00629 
00630 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
00631   GlobalValue *DGV = getLinkedToGlobal(&GV);
00632 
00633   if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
00634     return false;
00635 
00636   if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
00637     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
00638     auto *SGVar = dyn_cast<GlobalVariable>(&GV);
00639     if (DGVar && SGVar) {
00640       if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
00641           (!DGVar->isConstant() || !SGVar->isConstant())) {
00642         DGVar->setConstant(false);
00643         SGVar->setConstant(false);
00644       }
00645       if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
00646         unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
00647         SGVar->setAlignment(Align);
00648         DGVar->setAlignment(Align);
00649       }
00650     }
00651 
00652     GlobalValue::VisibilityTypes Visibility =
00653         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
00654     DGV->setVisibility(Visibility);
00655     GV.setVisibility(Visibility);
00656 
00657     bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
00658     DGV->setUnnamedAddr(HasUnnamedAddr);
00659     GV.setUnnamedAddr(HasUnnamedAddr);
00660   }
00661 
00662   // Don't want to append to global_ctors list, for example, when we
00663   // are importing for ThinLTO, otherwise the global ctors and dtors
00664   // get executed multiple times for local variables (the latter causing
00665   // double frees).
00666   if (GV.hasAppendingLinkage() && isPerformingImport())
00667     return false;
00668 
00669   if (isPerformingImport() && !doImportAsDefinition(&GV))
00670     return false;
00671 
00672   if (!DGV && !shouldOverrideFromSrc() &&
00673       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
00674        GV.hasAvailableExternallyLinkage()))
00675     return false;
00676 
00677   if (GV.isDeclaration())
00678     return false;
00679 
00680   if (const Comdat *SC = GV.getComdat()) {
00681     bool LinkFromSrc;
00682     Comdat::SelectionKind SK;
00683     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
00684     if (LinkFromSrc)
00685       ValuesToLink.insert(&GV);
00686     return false;
00687   }
00688 
00689   bool LinkFromSrc = true;
00690   if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
00691     return true;
00692   if (LinkFromSrc)
00693     ValuesToLink.insert(&GV);
00694   return false;
00695 }
00696 
00697 void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
00698   // Add these to the internalize list
00699   if (!GV.hasLinkOnceLinkage())
00700     return;
00701 
00702   if (shouldInternalizeLinkedSymbols())
00703     Internalize.insert(GV.getName());
00704   Add(GV);
00705 
00706   const Comdat *SC = GV.getComdat();
00707   if (!SC)
00708     return;
00709   for (GlobalValue *GV2 : ComdatMembers[SC]) {
00710     if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
00711       Internalize.insert(GV2->getName());
00712     Add(*GV2);
00713   }
00714 }
00715 
00716 void ThinLTOGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
00717   if (GV.hasLocalLinkage() &&
00718       (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
00719     GV.setName(getName(&GV));
00720     GV.setLinkage(getLinkage(&GV));
00721     if (!GV.hasLocalLinkage())
00722       GV.setVisibility(GlobalValue::HiddenVisibility);
00723     if (isModuleExporting())
00724       NewExportedValues.insert(&GV);
00725     return;
00726   }
00727   GV.setLinkage(getLinkage(&GV));
00728 }
00729 
00730 void ThinLTOGlobalProcessing::processGlobalsForThinLTO() {
00731   for (GlobalVariable &GV : M.globals())
00732     processGlobalForThinLTO(GV);
00733   for (Function &SF : M)
00734     processGlobalForThinLTO(SF);
00735   for (GlobalAlias &GA : M.aliases())
00736     processGlobalForThinLTO(GA);
00737 }
00738 
00739 bool ThinLTOGlobalProcessing::run() {
00740   processGlobalsForThinLTO();
00741   return false;
00742 }
00743 
00744 bool ModuleLinker::run() {
00745   for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
00746     const Comdat &C = SMEC.getValue();
00747     if (ComdatsChosen.count(&C))
00748       continue;
00749     Comdat::SelectionKind SK;
00750     bool LinkFromSrc;
00751     if (getComdatResult(&C, SK, LinkFromSrc))
00752       return true;
00753     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
00754   }
00755 
00756   for (GlobalVariable &GV : SrcM.globals())
00757     if (const Comdat *SC = GV.getComdat())
00758       ComdatMembers[SC].push_back(&GV);
00759 
00760   for (Function &SF : SrcM)
00761     if (const Comdat *SC = SF.getComdat())
00762       ComdatMembers[SC].push_back(&SF);
00763 
00764   for (GlobalAlias &GA : SrcM.aliases())
00765     if (const Comdat *SC = GA.getComdat())
00766       ComdatMembers[SC].push_back(&GA);
00767 
00768   // Insert all of the globals in src into the DstM module... without linking
00769   // initializers (which could refer to functions not yet mapped over).
00770   for (GlobalVariable &GV : SrcM.globals())
00771     if (linkIfNeeded(GV))
00772       return true;
00773 
00774   for (Function &SF : SrcM)
00775     if (linkIfNeeded(SF))
00776       return true;
00777 
00778   for (GlobalAlias &GA : SrcM.aliases())
00779     if (linkIfNeeded(GA))
00780       return true;
00781 
00782   if (ImportIndex) {
00783     ThinLTOGlobalProcessing ThinLTOProcessing(SrcM, ImportIndex,
00784                                               FunctionsToImport);
00785     if (ThinLTOProcessing.run())
00786       return true;
00787     for (auto *GV : ThinLTOProcessing.getNewExportedValues())
00788       ValuesToLink.insert(GV);
00789   }
00790 
00791   for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
00792     GlobalValue *GV = ValuesToLink[I];
00793     const Comdat *SC = GV->getComdat();
00794     if (!SC)
00795       continue;
00796     for (GlobalValue *GV2 : ComdatMembers[SC])
00797       ValuesToLink.insert(GV2);
00798   }
00799 
00800   if (shouldInternalizeLinkedSymbols()) {
00801     for (GlobalValue *GV : ValuesToLink)
00802       Internalize.insert(GV->getName());
00803   }
00804 
00805   if (Mover.move(SrcM, ValuesToLink.getArrayRef(),
00806                  [this](GlobalValue &GV, IRMover::ValueAdder Add) {
00807                    addLazyFor(GV, Add);
00808                  },
00809                  ValIDToTempMDMap, false))
00810     return true;
00811   Module &DstM = Mover.getModule();
00812   for (auto &P : Internalize) {
00813     GlobalValue *GV = DstM.getNamedValue(P.first());
00814     GV->setLinkage(GlobalValue::InternalLinkage);
00815   }
00816 
00817   return false;
00818 }
00819 
00820 Linker::Linker(Module &M) : Mover(M) {}
00821 
00822 bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
00823                           const FunctionInfoIndex *Index,
00824                           DenseSet<const GlobalValue *> *FunctionsToImport,
00825                           DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
00826   ModuleLinker ModLinker(Mover, *Src, Flags, Index, FunctionsToImport,
00827                          ValIDToTempMDMap);
00828   return ModLinker.run();
00829 }
00830 
00831 bool Linker::linkInModuleForCAPI(Module &Src) {
00832   ModuleLinker ModLinker(Mover, Src, 0, nullptr, nullptr);
00833   return ModLinker.run();
00834 }
00835 
00836 bool Linker::linkInMetadata(Module &Src,
00837                             DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
00838   SetVector<GlobalValue *> ValuesToLink;
00839   if (Mover.move(
00840           Src, ValuesToLink.getArrayRef(),
00841           [this](GlobalValue &GV, IRMover::ValueAdder Add) { assert(false); },
00842           ValIDToTempMDMap, true))
00843     return true;
00844   return false;
00845 }
00846 
00847 //===----------------------------------------------------------------------===//
00848 // LinkModules entrypoint.
00849 //===----------------------------------------------------------------------===//
00850 
00851 /// This function links two modules together, with the resulting Dest module
00852 /// modified to be the composite of the two input modules. If an error occurs,
00853 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
00854 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
00855 /// relied on to be consistent.
00856 bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
00857                          unsigned Flags) {
00858   Linker L(Dest);
00859   return L.linkInModule(std::move(Src), Flags);
00860 }
00861 
00862 bool llvm::renameModuleForThinLTO(Module &M, const FunctionInfoIndex *Index) {
00863   ThinLTOGlobalProcessing ThinLTOProcessing(M, Index);
00864   return ThinLTOProcessing.run();
00865 }
00866 
00867 //===----------------------------------------------------------------------===//
00868 // C API.
00869 //===----------------------------------------------------------------------===//
00870 
00871 static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
00872   auto *Message = reinterpret_cast<std::string *>(C);
00873   raw_string_ostream Stream(*Message);
00874   DiagnosticPrinterRawOStream DP(Stream);
00875   DI.print(DP);
00876 }
00877 
00878 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
00879                          LLVMLinkerMode Unused, char **OutMessages) {
00880   Module *D = unwrap(Dest);
00881   LLVMContext &Ctx = D->getContext();
00882 
00883   LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
00884       Ctx.getDiagnosticHandler();
00885   void *OldDiagnosticContext = Ctx.getDiagnosticContext();
00886   std::string Message;
00887   Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
00888 
00889   Linker L(*D);
00890   Module *M = unwrap(Src);
00891   LLVMBool Result = L.linkInModuleForCAPI(*M);
00892 
00893   Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
00894 
00895   if (OutMessages && Result)
00896     *OutMessages = strdup(Message.c_str());
00897   return Result;
00898 }
00899 
00900 LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
00901   Module *D = unwrap(Dest);
00902   std::unique_ptr<Module> M(unwrap(Src));
00903   return Linker::linkModules(*D, std::move(M));
00904 }