xref: /openbsd-src/gnu/llvm/llvm/lib/Linker/LinkModules.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the LLVM module linker.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "LinkDiagnosticInfo.h"
1409467b48Spatrick #include "llvm-c/Linker.h"
1509467b48Spatrick #include "llvm/ADT/SetVector.h"
1609467b48Spatrick #include "llvm/IR/Comdat.h"
1709467b48Spatrick #include "llvm/IR/GlobalValue.h"
1809467b48Spatrick #include "llvm/IR/LLVMContext.h"
1909467b48Spatrick #include "llvm/IR/Module.h"
2009467b48Spatrick #include "llvm/Linker/Linker.h"
2109467b48Spatrick #include "llvm/Support/Error.h"
2209467b48Spatrick using namespace llvm;
2309467b48Spatrick 
2409467b48Spatrick namespace {
2509467b48Spatrick 
26*d415bd75Srobert enum class LinkFrom { Dst, Src, Both };
27*d415bd75Srobert 
2809467b48Spatrick /// This is an implementation class for the LinkModules function, which is the
2909467b48Spatrick /// entrypoint for this file.
3009467b48Spatrick class ModuleLinker {
3109467b48Spatrick   IRMover &Mover;
3209467b48Spatrick   std::unique_ptr<Module> SrcM;
3309467b48Spatrick 
3409467b48Spatrick   SetVector<GlobalValue *> ValuesToLink;
3509467b48Spatrick 
3609467b48Spatrick   /// For symbol clashes, prefer those from Src.
3709467b48Spatrick   unsigned Flags;
3809467b48Spatrick 
3909467b48Spatrick   /// List of global value names that should be internalized.
4009467b48Spatrick   StringSet<> Internalize;
4109467b48Spatrick 
4209467b48Spatrick   /// Function that will perform the actual internalization. The reason for a
4309467b48Spatrick   /// callback is that the linker cannot call internalizeModule without
4409467b48Spatrick   /// creating a circular dependency between IPO and the linker.
4509467b48Spatrick   std::function<void(Module &, const StringSet<> &)> InternalizeCallback;
4609467b48Spatrick 
4709467b48Spatrick   /// Used as the callback for lazy linking.
4809467b48Spatrick   /// The mover has just hit GV and we have to decide if it, and other members
4909467b48Spatrick   /// of the same comdat, should be linked. Every member to be linked is passed
5009467b48Spatrick   /// to Add.
5109467b48Spatrick   void addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add);
5209467b48Spatrick 
shouldOverrideFromSrc()5309467b48Spatrick   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
shouldLinkOnlyNeeded()5409467b48Spatrick   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
5509467b48Spatrick 
5609467b48Spatrick   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
5709467b48Spatrick                             const GlobalValue &Src);
5809467b48Spatrick 
5909467b48Spatrick   /// Should we have mover and linker error diag info?
emitError(const Twine & Message)6009467b48Spatrick   bool emitError(const Twine &Message) {
6109467b48Spatrick     SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
6209467b48Spatrick     return true;
6309467b48Spatrick   }
6409467b48Spatrick 
6509467b48Spatrick   bool getComdatLeader(Module &M, StringRef ComdatName,
6609467b48Spatrick                        const GlobalVariable *&GVar);
6709467b48Spatrick   bool computeResultingSelectionKind(StringRef ComdatName,
6809467b48Spatrick                                      Comdat::SelectionKind Src,
6909467b48Spatrick                                      Comdat::SelectionKind Dst,
7009467b48Spatrick                                      Comdat::SelectionKind &Result,
71*d415bd75Srobert                                      LinkFrom &From);
72*d415bd75Srobert   DenseMap<const Comdat *, std::pair<Comdat::SelectionKind, LinkFrom>>
7309467b48Spatrick       ComdatsChosen;
7409467b48Spatrick   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
75*d415bd75Srobert                        LinkFrom &From);
7609467b48Spatrick   // Keep track of the lazy linked global members of each comdat in source.
7709467b48Spatrick   DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
7809467b48Spatrick 
7909467b48Spatrick   /// Given a global in the source module, return the global in the
8009467b48Spatrick   /// destination module that is being linked to, if any.
getLinkedToGlobal(const GlobalValue * SrcGV)8109467b48Spatrick   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
8209467b48Spatrick     Module &DstM = Mover.getModule();
8309467b48Spatrick     // If the source has no name it can't link.  If it has local linkage,
8409467b48Spatrick     // there is no name match-up going on.
8509467b48Spatrick     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
8609467b48Spatrick       return nullptr;
8709467b48Spatrick 
8809467b48Spatrick     // Otherwise see if we have a match in the destination module's symtab.
8909467b48Spatrick     GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
9009467b48Spatrick     if (!DGV)
9109467b48Spatrick       return nullptr;
9209467b48Spatrick 
9309467b48Spatrick     // If we found a global with the same name in the dest module, but it has
9409467b48Spatrick     // internal linkage, we are really not doing any linkage here.
9509467b48Spatrick     if (DGV->hasLocalLinkage())
9609467b48Spatrick       return nullptr;
9709467b48Spatrick 
9809467b48Spatrick     // Otherwise, we do in fact link to the destination global.
9909467b48Spatrick     return DGV;
10009467b48Spatrick   }
10109467b48Spatrick 
10209467b48Spatrick   /// Drop GV if it is a member of a comdat that we are dropping.
10309467b48Spatrick   /// This can happen with COFF's largest selection kind.
10409467b48Spatrick   void dropReplacedComdat(GlobalValue &GV,
10509467b48Spatrick                           const DenseSet<const Comdat *> &ReplacedDstComdats);
10609467b48Spatrick 
107*d415bd75Srobert   bool linkIfNeeded(GlobalValue &GV, SmallVectorImpl<GlobalValue *> &GVToClone);
10809467b48Spatrick 
10909467b48Spatrick public:
ModuleLinker(IRMover & Mover,std::unique_ptr<Module> SrcM,unsigned Flags,std::function<void (Module &,const StringSet<> &)> InternalizeCallback={})11009467b48Spatrick   ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
11109467b48Spatrick                std::function<void(Module &, const StringSet<> &)>
11209467b48Spatrick                    InternalizeCallback = {})
11309467b48Spatrick       : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
11409467b48Spatrick         InternalizeCallback(std::move(InternalizeCallback)) {}
11509467b48Spatrick 
11609467b48Spatrick   bool run();
11709467b48Spatrick };
118*d415bd75Srobert } // namespace
11909467b48Spatrick 
12009467b48Spatrick static GlobalValue::VisibilityTypes
getMinVisibility(GlobalValue::VisibilityTypes A,GlobalValue::VisibilityTypes B)12109467b48Spatrick getMinVisibility(GlobalValue::VisibilityTypes A,
12209467b48Spatrick                  GlobalValue::VisibilityTypes B) {
12309467b48Spatrick   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
12409467b48Spatrick     return GlobalValue::HiddenVisibility;
12509467b48Spatrick   if (A == GlobalValue::ProtectedVisibility ||
12609467b48Spatrick       B == GlobalValue::ProtectedVisibility)
12709467b48Spatrick     return GlobalValue::ProtectedVisibility;
12809467b48Spatrick   return GlobalValue::DefaultVisibility;
12909467b48Spatrick }
13009467b48Spatrick 
getComdatLeader(Module & M,StringRef ComdatName,const GlobalVariable * & GVar)13109467b48Spatrick bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
13209467b48Spatrick                                    const GlobalVariable *&GVar) {
13309467b48Spatrick   const GlobalValue *GVal = M.getNamedValue(ComdatName);
13409467b48Spatrick   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
135*d415bd75Srobert     GVal = GA->getAliaseeObject();
13609467b48Spatrick     if (!GVal)
13709467b48Spatrick       // We cannot resolve the size of the aliasee yet.
13809467b48Spatrick       return emitError("Linking COMDATs named '" + ComdatName +
13909467b48Spatrick                        "': COMDAT key involves incomputable alias size.");
14009467b48Spatrick   }
14109467b48Spatrick 
14209467b48Spatrick   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
14309467b48Spatrick   if (!GVar)
14409467b48Spatrick     return emitError(
14509467b48Spatrick         "Linking COMDATs named '" + ComdatName +
14609467b48Spatrick         "': GlobalVariable required for data dependent selection!");
14709467b48Spatrick 
14809467b48Spatrick   return false;
14909467b48Spatrick }
15009467b48Spatrick 
computeResultingSelectionKind(StringRef ComdatName,Comdat::SelectionKind Src,Comdat::SelectionKind Dst,Comdat::SelectionKind & Result,LinkFrom & From)15109467b48Spatrick bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
15209467b48Spatrick                                                  Comdat::SelectionKind Src,
15309467b48Spatrick                                                  Comdat::SelectionKind Dst,
15409467b48Spatrick                                                  Comdat::SelectionKind &Result,
155*d415bd75Srobert                                                  LinkFrom &From) {
15609467b48Spatrick   Module &DstM = Mover.getModule();
15709467b48Spatrick   // The ability to mix Comdat::SelectionKind::Any with
15809467b48Spatrick   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
15909467b48Spatrick   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
16009467b48Spatrick                          Dst == Comdat::SelectionKind::Largest;
16109467b48Spatrick   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
16209467b48Spatrick                          Src == Comdat::SelectionKind::Largest;
16309467b48Spatrick   if (DstAnyOrLargest && SrcAnyOrLargest) {
16409467b48Spatrick     if (Dst == Comdat::SelectionKind::Largest ||
16509467b48Spatrick         Src == Comdat::SelectionKind::Largest)
16609467b48Spatrick       Result = Comdat::SelectionKind::Largest;
16709467b48Spatrick     else
16809467b48Spatrick       Result = Comdat::SelectionKind::Any;
16909467b48Spatrick   } else if (Src == Dst) {
17009467b48Spatrick     Result = Dst;
17109467b48Spatrick   } else {
17209467b48Spatrick     return emitError("Linking COMDATs named '" + ComdatName +
17309467b48Spatrick                      "': invalid selection kinds!");
17409467b48Spatrick   }
17509467b48Spatrick 
17609467b48Spatrick   switch (Result) {
17709467b48Spatrick   case Comdat::SelectionKind::Any:
17809467b48Spatrick     // Go with Dst.
179*d415bd75Srobert     From = LinkFrom::Dst;
18009467b48Spatrick     break;
181*d415bd75Srobert   case Comdat::SelectionKind::NoDeduplicate:
182*d415bd75Srobert     From = LinkFrom::Both;
18373471bf0Spatrick     break;
18409467b48Spatrick   case Comdat::SelectionKind::ExactMatch:
18509467b48Spatrick   case Comdat::SelectionKind::Largest:
18609467b48Spatrick   case Comdat::SelectionKind::SameSize: {
18709467b48Spatrick     const GlobalVariable *DstGV;
18809467b48Spatrick     const GlobalVariable *SrcGV;
18909467b48Spatrick     if (getComdatLeader(DstM, ComdatName, DstGV) ||
19009467b48Spatrick         getComdatLeader(*SrcM, ComdatName, SrcGV))
19109467b48Spatrick       return true;
19209467b48Spatrick 
19309467b48Spatrick     const DataLayout &DstDL = DstM.getDataLayout();
19409467b48Spatrick     const DataLayout &SrcDL = SrcM->getDataLayout();
19509467b48Spatrick     uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
19609467b48Spatrick     uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
19709467b48Spatrick     if (Result == Comdat::SelectionKind::ExactMatch) {
19809467b48Spatrick       if (SrcGV->getInitializer() != DstGV->getInitializer())
19909467b48Spatrick         return emitError("Linking COMDATs named '" + ComdatName +
20009467b48Spatrick                          "': ExactMatch violated!");
201*d415bd75Srobert       From = LinkFrom::Dst;
20209467b48Spatrick     } else if (Result == Comdat::SelectionKind::Largest) {
203*d415bd75Srobert       From = SrcSize > DstSize ? LinkFrom::Src : LinkFrom::Dst;
20409467b48Spatrick     } else if (Result == Comdat::SelectionKind::SameSize) {
20509467b48Spatrick       if (SrcSize != DstSize)
20609467b48Spatrick         return emitError("Linking COMDATs named '" + ComdatName +
20709467b48Spatrick                          "': SameSize violated!");
208*d415bd75Srobert       From = LinkFrom::Dst;
20909467b48Spatrick     } else {
21009467b48Spatrick       llvm_unreachable("unknown selection kind");
21109467b48Spatrick     }
21209467b48Spatrick     break;
21309467b48Spatrick   }
21409467b48Spatrick   }
21509467b48Spatrick 
21609467b48Spatrick   return false;
21709467b48Spatrick }
21809467b48Spatrick 
getComdatResult(const Comdat * SrcC,Comdat::SelectionKind & Result,LinkFrom & From)21909467b48Spatrick bool ModuleLinker::getComdatResult(const Comdat *SrcC,
22009467b48Spatrick                                    Comdat::SelectionKind &Result,
221*d415bd75Srobert                                    LinkFrom &From) {
22209467b48Spatrick   Module &DstM = Mover.getModule();
22309467b48Spatrick   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
22409467b48Spatrick   StringRef ComdatName = SrcC->getName();
22509467b48Spatrick   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
22609467b48Spatrick   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
22709467b48Spatrick 
22809467b48Spatrick   if (DstCI == ComdatSymTab.end()) {
22909467b48Spatrick     // Use the comdat if it is only available in one of the modules.
230*d415bd75Srobert     From = LinkFrom::Src;
23109467b48Spatrick     Result = SSK;
23209467b48Spatrick     return false;
23309467b48Spatrick   }
23409467b48Spatrick 
23509467b48Spatrick   const Comdat *DstC = &DstCI->second;
23609467b48Spatrick   Comdat::SelectionKind DSK = DstC->getSelectionKind();
237*d415bd75Srobert   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, From);
23809467b48Spatrick }
23909467b48Spatrick 
shouldLinkFromSource(bool & LinkFromSrc,const GlobalValue & Dest,const GlobalValue & Src)24009467b48Spatrick bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
24109467b48Spatrick                                         const GlobalValue &Dest,
24209467b48Spatrick                                         const GlobalValue &Src) {
24309467b48Spatrick 
24409467b48Spatrick   // Should we unconditionally use the Src?
24509467b48Spatrick   if (shouldOverrideFromSrc()) {
24609467b48Spatrick     LinkFromSrc = true;
24709467b48Spatrick     return false;
24809467b48Spatrick   }
24909467b48Spatrick 
25009467b48Spatrick   // We always have to add Src if it has appending linkage.
25173471bf0Spatrick   if (Src.hasAppendingLinkage() || Dest.hasAppendingLinkage()) {
25209467b48Spatrick     LinkFromSrc = true;
25309467b48Spatrick     return false;
25409467b48Spatrick   }
25509467b48Spatrick 
25609467b48Spatrick   bool SrcIsDeclaration = Src.isDeclarationForLinker();
25709467b48Spatrick   bool DestIsDeclaration = Dest.isDeclarationForLinker();
25809467b48Spatrick 
25909467b48Spatrick   if (SrcIsDeclaration) {
26009467b48Spatrick     // If Src is external or if both Src & Dest are external..  Just link the
26109467b48Spatrick     // external globals, we aren't adding anything.
26209467b48Spatrick     if (Src.hasDLLImportStorageClass()) {
26309467b48Spatrick       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
26409467b48Spatrick       LinkFromSrc = DestIsDeclaration;
26509467b48Spatrick       return false;
26609467b48Spatrick     }
26709467b48Spatrick     // If the Dest is weak, use the source linkage.
26809467b48Spatrick     if (Dest.hasExternalWeakLinkage()) {
26909467b48Spatrick       LinkFromSrc = true;
27009467b48Spatrick       return false;
27109467b48Spatrick     }
27209467b48Spatrick     // Link an available_externally over a declaration.
27309467b48Spatrick     LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
27409467b48Spatrick     return false;
27509467b48Spatrick   }
27609467b48Spatrick 
27709467b48Spatrick   if (DestIsDeclaration) {
27809467b48Spatrick     // If Dest is external but Src is not:
27909467b48Spatrick     LinkFromSrc = true;
28009467b48Spatrick     return false;
28109467b48Spatrick   }
28209467b48Spatrick 
28309467b48Spatrick   if (Src.hasCommonLinkage()) {
28409467b48Spatrick     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
28509467b48Spatrick       LinkFromSrc = true;
28609467b48Spatrick       return false;
28709467b48Spatrick     }
28809467b48Spatrick 
28909467b48Spatrick     if (!Dest.hasCommonLinkage()) {
29009467b48Spatrick       LinkFromSrc = false;
29109467b48Spatrick       return false;
29209467b48Spatrick     }
29309467b48Spatrick 
29409467b48Spatrick     const DataLayout &DL = Dest.getParent()->getDataLayout();
29509467b48Spatrick     uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
29609467b48Spatrick     uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
29709467b48Spatrick     LinkFromSrc = SrcSize > DestSize;
29809467b48Spatrick     return false;
29909467b48Spatrick   }
30009467b48Spatrick 
30109467b48Spatrick   if (Src.isWeakForLinker()) {
30209467b48Spatrick     assert(!Dest.hasExternalWeakLinkage());
30309467b48Spatrick     assert(!Dest.hasAvailableExternallyLinkage());
30409467b48Spatrick 
30509467b48Spatrick     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
30609467b48Spatrick       LinkFromSrc = true;
30709467b48Spatrick       return false;
30809467b48Spatrick     }
30909467b48Spatrick 
31009467b48Spatrick     LinkFromSrc = false;
31109467b48Spatrick     return false;
31209467b48Spatrick   }
31309467b48Spatrick 
31409467b48Spatrick   if (Dest.isWeakForLinker()) {
31509467b48Spatrick     assert(Src.hasExternalLinkage());
31609467b48Spatrick     LinkFromSrc = true;
31709467b48Spatrick     return false;
31809467b48Spatrick   }
31909467b48Spatrick 
32009467b48Spatrick   assert(!Src.hasExternalWeakLinkage());
32109467b48Spatrick   assert(!Dest.hasExternalWeakLinkage());
32209467b48Spatrick   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
32309467b48Spatrick          "Unexpected linkage type!");
32409467b48Spatrick   return emitError("Linking globals named '" + Src.getName() +
32509467b48Spatrick                    "': symbol multiply defined!");
32609467b48Spatrick }
32709467b48Spatrick 
linkIfNeeded(GlobalValue & GV,SmallVectorImpl<GlobalValue * > & GVToClone)328*d415bd75Srobert bool ModuleLinker::linkIfNeeded(GlobalValue &GV,
329*d415bd75Srobert                                 SmallVectorImpl<GlobalValue *> &GVToClone) {
33009467b48Spatrick   GlobalValue *DGV = getLinkedToGlobal(&GV);
33109467b48Spatrick 
33209467b48Spatrick   if (shouldLinkOnlyNeeded()) {
33309467b48Spatrick     // Always import variables with appending linkage.
33409467b48Spatrick     if (!GV.hasAppendingLinkage()) {
33509467b48Spatrick       // Don't import globals unless they are referenced by the destination
33609467b48Spatrick       // module.
33709467b48Spatrick       if (!DGV)
33809467b48Spatrick         return false;
33909467b48Spatrick       // Don't import globals that are already defined in the destination module
34009467b48Spatrick       if (!DGV->isDeclaration())
34109467b48Spatrick         return false;
34209467b48Spatrick     }
34309467b48Spatrick   }
34409467b48Spatrick 
34509467b48Spatrick   if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
34609467b48Spatrick     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
34709467b48Spatrick     auto *SGVar = dyn_cast<GlobalVariable>(&GV);
34809467b48Spatrick     if (DGVar && SGVar) {
34909467b48Spatrick       if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
35009467b48Spatrick           (!DGVar->isConstant() || !SGVar->isConstant())) {
35109467b48Spatrick         DGVar->setConstant(false);
35209467b48Spatrick         SGVar->setConstant(false);
35309467b48Spatrick       }
35409467b48Spatrick       if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
355*d415bd75Srobert         MaybeAlign DAlign = DGVar->getAlign();
356*d415bd75Srobert         MaybeAlign SAlign = SGVar->getAlign();
357*d415bd75Srobert         MaybeAlign Align = std::nullopt;
358*d415bd75Srobert         if (DAlign || SAlign)
359*d415bd75Srobert           Align = std::max(DAlign.valueOrOne(), SAlign.valueOrOne());
360*d415bd75Srobert 
36109467b48Spatrick         SGVar->setAlignment(Align);
36209467b48Spatrick         DGVar->setAlignment(Align);
36309467b48Spatrick       }
36409467b48Spatrick     }
36509467b48Spatrick 
36609467b48Spatrick     GlobalValue::VisibilityTypes Visibility =
36709467b48Spatrick         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
36809467b48Spatrick     DGV->setVisibility(Visibility);
36909467b48Spatrick     GV.setVisibility(Visibility);
37009467b48Spatrick 
37109467b48Spatrick     GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::getMinUnnamedAddr(
37209467b48Spatrick         DGV->getUnnamedAddr(), GV.getUnnamedAddr());
37309467b48Spatrick     DGV->setUnnamedAddr(UnnamedAddr);
37409467b48Spatrick     GV.setUnnamedAddr(UnnamedAddr);
37509467b48Spatrick   }
37609467b48Spatrick 
37709467b48Spatrick   if (!DGV && !shouldOverrideFromSrc() &&
37809467b48Spatrick       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
37909467b48Spatrick        GV.hasAvailableExternallyLinkage()))
38009467b48Spatrick     return false;
38109467b48Spatrick 
38209467b48Spatrick   if (GV.isDeclaration())
38309467b48Spatrick     return false;
38409467b48Spatrick 
385*d415bd75Srobert   LinkFrom ComdatFrom = LinkFrom::Dst;
38609467b48Spatrick   if (const Comdat *SC = GV.getComdat()) {
387*d415bd75Srobert     std::tie(std::ignore, ComdatFrom) = ComdatsChosen[SC];
388*d415bd75Srobert     if (ComdatFrom == LinkFrom::Dst)
38909467b48Spatrick       return false;
39009467b48Spatrick   }
39109467b48Spatrick 
39209467b48Spatrick   bool LinkFromSrc = true;
39309467b48Spatrick   if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
39409467b48Spatrick     return true;
395*d415bd75Srobert   if (DGV && ComdatFrom == LinkFrom::Both)
396*d415bd75Srobert     GVToClone.push_back(LinkFromSrc ? DGV : &GV);
39709467b48Spatrick   if (LinkFromSrc)
39809467b48Spatrick     ValuesToLink.insert(&GV);
39909467b48Spatrick   return false;
40009467b48Spatrick }
40109467b48Spatrick 
addLazyFor(GlobalValue & GV,const IRMover::ValueAdder & Add)40209467b48Spatrick void ModuleLinker::addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add) {
40309467b48Spatrick   // Add these to the internalize list
40409467b48Spatrick   if (!GV.hasLinkOnceLinkage() && !GV.hasAvailableExternallyLinkage() &&
40509467b48Spatrick       !shouldLinkOnlyNeeded())
40609467b48Spatrick     return;
40709467b48Spatrick 
40809467b48Spatrick   if (InternalizeCallback)
40909467b48Spatrick     Internalize.insert(GV.getName());
41009467b48Spatrick   Add(GV);
41109467b48Spatrick 
41209467b48Spatrick   const Comdat *SC = GV.getComdat();
41309467b48Spatrick   if (!SC)
41409467b48Spatrick     return;
41509467b48Spatrick   for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
41609467b48Spatrick     GlobalValue *DGV = getLinkedToGlobal(GV2);
41709467b48Spatrick     bool LinkFromSrc = true;
41809467b48Spatrick     if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
41909467b48Spatrick       return;
42009467b48Spatrick     if (!LinkFromSrc)
42109467b48Spatrick       continue;
42209467b48Spatrick     if (InternalizeCallback)
42309467b48Spatrick       Internalize.insert(GV2->getName());
42409467b48Spatrick     Add(*GV2);
42509467b48Spatrick   }
42609467b48Spatrick }
42709467b48Spatrick 
dropReplacedComdat(GlobalValue & GV,const DenseSet<const Comdat * > & ReplacedDstComdats)42809467b48Spatrick void ModuleLinker::dropReplacedComdat(
42909467b48Spatrick     GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
43009467b48Spatrick   Comdat *C = GV.getComdat();
43109467b48Spatrick   if (!C)
43209467b48Spatrick     return;
43309467b48Spatrick   if (!ReplacedDstComdats.count(C))
43409467b48Spatrick     return;
43509467b48Spatrick   if (GV.use_empty()) {
43609467b48Spatrick     GV.eraseFromParent();
43709467b48Spatrick     return;
43809467b48Spatrick   }
43909467b48Spatrick 
44009467b48Spatrick   if (auto *F = dyn_cast<Function>(&GV)) {
44109467b48Spatrick     F->deleteBody();
44209467b48Spatrick   } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
44309467b48Spatrick     Var->setInitializer(nullptr);
44409467b48Spatrick   } else {
44509467b48Spatrick     auto &Alias = cast<GlobalAlias>(GV);
44609467b48Spatrick     Module &M = *Alias.getParent();
44709467b48Spatrick     GlobalValue *Declaration;
44809467b48Spatrick     if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
44909467b48Spatrick       Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
45009467b48Spatrick     } else {
45109467b48Spatrick       Declaration =
45273471bf0Spatrick           new GlobalVariable(M, Alias.getValueType(), /*isConstant*/ false,
45309467b48Spatrick                              GlobalValue::ExternalLinkage,
45409467b48Spatrick                              /*Initializer*/ nullptr);
45509467b48Spatrick     }
45609467b48Spatrick     Declaration->takeName(&Alias);
45709467b48Spatrick     Alias.replaceAllUsesWith(Declaration);
45809467b48Spatrick     Alias.eraseFromParent();
45909467b48Spatrick   }
46009467b48Spatrick }
46109467b48Spatrick 
run()46209467b48Spatrick bool ModuleLinker::run() {
46309467b48Spatrick   Module &DstM = Mover.getModule();
46409467b48Spatrick   DenseSet<const Comdat *> ReplacedDstComdats;
46509467b48Spatrick 
46609467b48Spatrick   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
46709467b48Spatrick     const Comdat &C = SMEC.getValue();
46809467b48Spatrick     if (ComdatsChosen.count(&C))
46909467b48Spatrick       continue;
47009467b48Spatrick     Comdat::SelectionKind SK;
471*d415bd75Srobert     LinkFrom From;
472*d415bd75Srobert     if (getComdatResult(&C, SK, From))
47309467b48Spatrick       return true;
474*d415bd75Srobert     ComdatsChosen[&C] = std::make_pair(SK, From);
47509467b48Spatrick 
476*d415bd75Srobert     if (From != LinkFrom::Src)
47709467b48Spatrick       continue;
47809467b48Spatrick 
47909467b48Spatrick     Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
48009467b48Spatrick     Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
48109467b48Spatrick     if (DstCI == ComdatSymTab.end())
48209467b48Spatrick       continue;
48309467b48Spatrick 
48409467b48Spatrick     // The source comdat is replacing the dest one.
48509467b48Spatrick     const Comdat *DstC = &DstCI->second;
48609467b48Spatrick     ReplacedDstComdats.insert(DstC);
48709467b48Spatrick   }
48809467b48Spatrick 
48909467b48Spatrick   // Alias have to go first, since we are not able to find their comdats
49009467b48Spatrick   // otherwise.
491*d415bd75Srobert   for (GlobalAlias &GV : llvm::make_early_inc_range(DstM.aliases()))
49209467b48Spatrick     dropReplacedComdat(GV, ReplacedDstComdats);
49309467b48Spatrick 
494*d415bd75Srobert   for (GlobalVariable &GV : llvm::make_early_inc_range(DstM.globals()))
49509467b48Spatrick     dropReplacedComdat(GV, ReplacedDstComdats);
49609467b48Spatrick 
497*d415bd75Srobert   for (Function &GV : llvm::make_early_inc_range(DstM))
49809467b48Spatrick     dropReplacedComdat(GV, ReplacedDstComdats);
49909467b48Spatrick 
50009467b48Spatrick   for (GlobalVariable &GV : SrcM->globals())
50109467b48Spatrick     if (GV.hasLinkOnceLinkage())
50209467b48Spatrick       if (const Comdat *SC = GV.getComdat())
50309467b48Spatrick         LazyComdatMembers[SC].push_back(&GV);
50409467b48Spatrick 
50509467b48Spatrick   for (Function &SF : *SrcM)
50609467b48Spatrick     if (SF.hasLinkOnceLinkage())
50709467b48Spatrick       if (const Comdat *SC = SF.getComdat())
50809467b48Spatrick         LazyComdatMembers[SC].push_back(&SF);
50909467b48Spatrick 
51009467b48Spatrick   for (GlobalAlias &GA : SrcM->aliases())
51109467b48Spatrick     if (GA.hasLinkOnceLinkage())
51209467b48Spatrick       if (const Comdat *SC = GA.getComdat())
51309467b48Spatrick         LazyComdatMembers[SC].push_back(&GA);
51409467b48Spatrick 
51509467b48Spatrick   // Insert all of the globals in src into the DstM module... without linking
51609467b48Spatrick   // initializers (which could refer to functions not yet mapped over).
517*d415bd75Srobert   SmallVector<GlobalValue *, 0> GVToClone;
51809467b48Spatrick   for (GlobalVariable &GV : SrcM->globals())
519*d415bd75Srobert     if (linkIfNeeded(GV, GVToClone))
52009467b48Spatrick       return true;
52109467b48Spatrick 
52209467b48Spatrick   for (Function &SF : *SrcM)
523*d415bd75Srobert     if (linkIfNeeded(SF, GVToClone))
52409467b48Spatrick       return true;
52509467b48Spatrick 
52609467b48Spatrick   for (GlobalAlias &GA : SrcM->aliases())
527*d415bd75Srobert     if (linkIfNeeded(GA, GVToClone))
52809467b48Spatrick       return true;
52909467b48Spatrick 
530*d415bd75Srobert   for (GlobalIFunc &GI : SrcM->ifuncs())
531*d415bd75Srobert     if (linkIfNeeded(GI, GVToClone))
532*d415bd75Srobert       return true;
533*d415bd75Srobert 
534*d415bd75Srobert   // For a variable in a comdat nodeduplicate, its initializer should be
535*d415bd75Srobert   // preserved (its content may be implicitly used by other members) even if
536*d415bd75Srobert   // symbol resolution does not pick it. Clone it into an unnamed private
537*d415bd75Srobert   // variable.
538*d415bd75Srobert   for (GlobalValue *GV : GVToClone) {
539*d415bd75Srobert     if (auto *Var = dyn_cast<GlobalVariable>(GV)) {
540*d415bd75Srobert       auto *NewVar = new GlobalVariable(*Var->getParent(), Var->getValueType(),
541*d415bd75Srobert                                         Var->isConstant(), Var->getLinkage(),
542*d415bd75Srobert                                         Var->getInitializer());
543*d415bd75Srobert       NewVar->copyAttributesFrom(Var);
544*d415bd75Srobert       NewVar->setVisibility(GlobalValue::DefaultVisibility);
545*d415bd75Srobert       NewVar->setLinkage(GlobalValue::PrivateLinkage);
546*d415bd75Srobert       NewVar->setDSOLocal(true);
547*d415bd75Srobert       NewVar->setComdat(Var->getComdat());
548*d415bd75Srobert       if (Var->getParent() != &Mover.getModule())
549*d415bd75Srobert         ValuesToLink.insert(NewVar);
550*d415bd75Srobert     } else {
551*d415bd75Srobert       emitError("linking '" + GV->getName() +
552*d415bd75Srobert                 "': non-variables in comdat nodeduplicate are not handled");
553*d415bd75Srobert     }
554*d415bd75Srobert   }
555*d415bd75Srobert 
55609467b48Spatrick   for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
55709467b48Spatrick     GlobalValue *GV = ValuesToLink[I];
55809467b48Spatrick     const Comdat *SC = GV->getComdat();
55909467b48Spatrick     if (!SC)
56009467b48Spatrick       continue;
56109467b48Spatrick     for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
56209467b48Spatrick       GlobalValue *DGV = getLinkedToGlobal(GV2);
56309467b48Spatrick       bool LinkFromSrc = true;
56409467b48Spatrick       if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
56509467b48Spatrick         return true;
56609467b48Spatrick       if (LinkFromSrc)
56709467b48Spatrick         ValuesToLink.insert(GV2);
56809467b48Spatrick     }
56909467b48Spatrick   }
57009467b48Spatrick 
57109467b48Spatrick   if (InternalizeCallback) {
57209467b48Spatrick     for (GlobalValue *GV : ValuesToLink)
57309467b48Spatrick       Internalize.insert(GV->getName());
57409467b48Spatrick   }
57509467b48Spatrick 
57609467b48Spatrick   // FIXME: Propagate Errors through to the caller instead of emitting
57709467b48Spatrick   // diagnostics.
57809467b48Spatrick   bool HasErrors = false;
579*d415bd75Srobert   if (Error E =
580*d415bd75Srobert           Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
581*d415bd75Srobert                      IRMover::LazyCallback(
58209467b48Spatrick                          [this](GlobalValue &GV, IRMover::ValueAdder Add) {
58309467b48Spatrick                            addLazyFor(GV, Add);
584*d415bd75Srobert                          }),
58509467b48Spatrick                      /* IsPerformingImport */ false)) {
58609467b48Spatrick     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
58709467b48Spatrick       DstM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, EIB.message()));
58809467b48Spatrick       HasErrors = true;
58909467b48Spatrick     });
59009467b48Spatrick   }
59109467b48Spatrick   if (HasErrors)
59209467b48Spatrick     return true;
59309467b48Spatrick 
59409467b48Spatrick   if (InternalizeCallback)
59509467b48Spatrick     InternalizeCallback(DstM, Internalize);
59609467b48Spatrick 
59709467b48Spatrick   return false;
59809467b48Spatrick }
59909467b48Spatrick 
Linker(Module & M)60009467b48Spatrick Linker::Linker(Module &M) : Mover(M) {}
60109467b48Spatrick 
linkInModule(std::unique_ptr<Module> Src,unsigned Flags,std::function<void (Module &,const StringSet<> &)> InternalizeCallback)60209467b48Spatrick bool Linker::linkInModule(
60309467b48Spatrick     std::unique_ptr<Module> Src, unsigned Flags,
60409467b48Spatrick     std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
60509467b48Spatrick   ModuleLinker ModLinker(Mover, std::move(Src), Flags,
60609467b48Spatrick                          std::move(InternalizeCallback));
60709467b48Spatrick   return ModLinker.run();
60809467b48Spatrick }
60909467b48Spatrick 
61009467b48Spatrick //===----------------------------------------------------------------------===//
61109467b48Spatrick // LinkModules entrypoint.
61209467b48Spatrick //===----------------------------------------------------------------------===//
61309467b48Spatrick 
61409467b48Spatrick /// This function links two modules together, with the resulting Dest module
61509467b48Spatrick /// modified to be the composite of the two input modules. If an error occurs,
61609467b48Spatrick /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
61709467b48Spatrick /// Upon failure, the Dest module could be in a modified state, and shouldn't be
61809467b48Spatrick /// relied on to be consistent.
linkModules(Module & Dest,std::unique_ptr<Module> Src,unsigned Flags,std::function<void (Module &,const StringSet<> &)> InternalizeCallback)61909467b48Spatrick bool Linker::linkModules(
62009467b48Spatrick     Module &Dest, std::unique_ptr<Module> Src, unsigned Flags,
62109467b48Spatrick     std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
62209467b48Spatrick   Linker L(Dest);
62309467b48Spatrick   return L.linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
62409467b48Spatrick }
62509467b48Spatrick 
62609467b48Spatrick //===----------------------------------------------------------------------===//
62709467b48Spatrick // C API.
62809467b48Spatrick //===----------------------------------------------------------------------===//
62909467b48Spatrick 
LLVMLinkModules2(LLVMModuleRef Dest,LLVMModuleRef Src)63009467b48Spatrick LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
63109467b48Spatrick   Module *D = unwrap(Dest);
63209467b48Spatrick   std::unique_ptr<Module> M(unwrap(Src));
63309467b48Spatrick   return Linker::linkModules(*D, std::move(M));
63409467b48Spatrick }
635