64 : DstStructTypesSet(DstStructTypesSet) {}
69 void addTypeMapping(
Type *DstTy,
Type *SrcTy);
73 void linkDefinedTypeBodies();
83 return cast<FunctionType>(
get((
Type *)
T));
88 for (
auto &Pair : MappedTypes) {
89 dbgs() <<
"TypeMap: ";
90 Pair.first->print(
dbgs());
92 Pair.second->print(
dbgs());
98 Type *remapType(
Type *SrcTy)
override {
return get(SrcTy); }
100 bool areTypesIsomorphic(
Type *DstTy,
Type *SrcTy);
104 void TypeMapTy::addTypeMapping(
Type *DstTy,
Type *SrcTy) {
105 assert(SpeculativeTypes.empty());
106 assert(SpeculativeDstOpaqueTypes.empty());
110 if (!areTypesIsomorphic(DstTy, SrcTy)) {
113 for (
Type *Ty : SpeculativeTypes)
114 MappedTypes.erase(Ty);
116 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
117 SpeculativeDstOpaqueTypes.size());
118 for (
StructType *Ty : SpeculativeDstOpaqueTypes)
119 DstResolvedOpaqueTypes.erase(Ty);
121 for (
Type *Ty : SpeculativeTypes)
122 if (
auto *STy = dyn_cast<StructType>(Ty))
126 SpeculativeTypes.clear();
127 SpeculativeDstOpaqueTypes.clear();
132 bool TypeMapTy::areTypesIsomorphic(
Type *DstTy,
Type *SrcTy) {
138 Type *&Entry = MappedTypes[SrcTy];
140 return Entry == DstTy;
144 if (DstTy == SrcTy) {
152 if (
StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
154 if (SSTy->isOpaque()) {
156 SpeculativeTypes.push_back(SrcTy);
164 if (cast<StructType>(DstTy)->isOpaque()) {
166 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
168 SrcDefinitionsToResolve.push_back(SSTy);
169 SpeculativeTypes.push_back(SrcTy);
170 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
181 if (isa<IntegerType>(DstTy))
183 if (
PointerType *PT = dyn_cast<PointerType>(DstTy)) {
184 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
187 }
else if (
FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
188 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
190 }
else if (
StructType *DSTy = dyn_cast<StructType>(DstTy)) {
192 if (DSTy->isLiteral() != SSTy->
isLiteral() ||
193 DSTy->isPacked() != SSTy->
isPacked())
195 }
else if (
ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
196 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
198 }
else if (
VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
199 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
206 SpeculativeTypes.push_back(SrcTy);
217 void TypeMapTy::linkDefinedTypeBodies() {
219 for (
StructType *SrcSTy : SrcDefinitionsToResolve) {
220 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
224 Elements.
resize(SrcSTy->getNumElements());
225 for (
unsigned I = 0, E = Elements.
size();
I != E; ++
I)
226 Elements[
I] =
get(SrcSTy->getElementType(
I));
228 DstSTy->
setBody(Elements, SrcSTy->isPacked());
229 DstStructTypesSet.switchToNonOpaque(DstSTy);
231 SrcDefinitionsToResolve.clear();
232 DstResolvedOpaqueTypes.clear();
246 DstStructTypesSet.addNonOpaque(DTy);
251 return get(Ty, Visited);
256 Type **Entry = &MappedTypes[Ty];
261 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
265 for (
auto &Pair : MappedTypes) {
266 assert(!(Pair.first != Ty && Pair.second == Ty) &&
267 "mapping to a source type");
272 if (!IsUniqued && !Visited.
insert(cast<StructType>(Ty)).second) {
287 bool AnyChange =
false;
295 Entry = &MappedTypes[Ty];
297 if (
auto *DTy = dyn_cast<StructType>(*Entry)) {
299 auto *STy = cast<StructType>(Ty);
300 finishType(DTy, STy, ElementTypes);
308 if (!AnyChange && IsUniqued)
317 cast<ArrayType>(Ty)->getNumElements());
320 cast<VectorType>(Ty)->getNumElements());
323 cast<PointerType>(Ty)->getAddressSpace());
327 cast<FunctionType>(Ty)->isVarArg());
329 auto *STy = cast<StructType>(Ty);
336 DstStructTypesSet.addOpaque(STy);
341 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
343 return *Entry = OldT;
347 DstStructTypesSet.addNonOpaque(STy);
352 finishType(DTy, STy, ElementTypes);
371 std::vector<GlobalValue *> &LazilyLinkGlobalValues;
374 ValueMaterializerTy(TypeMapTy &TypeMap,
Module *DstM,
375 std::vector<GlobalValue *> &LazilyLinkGlobalValues)
377 LazilyLinkGlobalValues(LazilyLinkGlobalValues) {}
379 Value *materializeValueFor(
Value *V)
override;
400 ValueMaterializerTy ValMaterializer;
408 struct AppendingVarInfo {
414 std::vector<AppendingVarInfo> AppendingVars;
420 std::vector<GlobalValue *> LazilyLinkGlobalValues;
428 bool OverrideFromSrc;
433 bool OverrideFromSrc)
434 : DstM(dstM), SrcM(srcM), TypeMap(Set),
435 ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
436 DiagnosticHandler(DiagnosticHandler), OverrideFromSrc(OverrideFromSrc) {
442 bool shouldLinkFromSource(
bool &LinkFromSrc,
const GlobalValue &Dest,
446 bool emitError(
const Twine &Message) {
447 DiagnosticHandler(LinkDiagnosticInfo(
DS_Error, Message));
451 void emitWarning(
const Twine &Message) {
452 DiagnosticHandler(LinkDiagnosticInfo(
DS_Warning, Message));
457 bool computeResultingSelectionKind(
StringRef ComdatName,
462 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
489 void computeTypeMapping();
492 void upgradeMismatchedGlobals();
498 bool linkModuleFlagsMetadata();
500 void linkAppendingVarInit(
const AppendingVarInfo &AVI);
507 void linkNamedMDNodes();
508 void stripReplacedSubprograms();
526 ConflictGV->setName(Name);
527 assert(ConflictGV->getName() != Name &&
"forceRenaming didn't work");
542 if (a == GlobalValue::HiddenVisibility)
544 if (b == GlobalValue::HiddenVisibility)
546 if (a == GlobalValue::ProtectedVisibility)
548 if (b == GlobalValue::ProtectedVisibility)
584 auto *PTy = cast<PointerType>(TypeMap.get(SGA->
getType()));
591 if (
auto *SGVar = dyn_cast<GlobalVariable>(SGV))
593 else if (
auto *SF = dyn_cast<Function>(SGV))
601 Value *ValueMaterializerTy::materializeValueFor(
Value *V) {
608 if (
Comdat *
SC = SGV->getComdat()) {
609 if (
auto *DGO = dyn_cast<GlobalObject>(DGV)) {
610 Comdat *DC = DstM->getOrInsertComdat(
SC->getName());
615 LazilyLinkGlobalValues.push_back(SGV);
622 if (
const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
623 GVal = GA->getBaseObject();
626 return emitError(
"Linking COMDATs named '" + ComdatName +
627 "': COMDAT key involves incomputable alias size.");
630 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
633 "Linking COMDATs named '" + ComdatName +
634 "': GlobalVariable required for data dependent selection!");
639 bool ModuleLinker::computeResultingSelectionKind(
StringRef ComdatName,
647 Dst == Comdat::SelectionKind::Largest;
649 Src == Comdat::SelectionKind::Largest;
650 if (DstAnyOrLargest && SrcAnyOrLargest) {
651 if (Dst == Comdat::SelectionKind::Largest ||
652 Src == Comdat::SelectionKind::Largest)
653 Result = Comdat::SelectionKind::Largest;
656 }
else if (Src == Dst) {
659 return emitError(
"Linking COMDATs named '" + ComdatName +
660 "': invalid selection kinds!");
668 case Comdat::SelectionKind::NoDuplicates:
669 return emitError(
"Linking COMDATs named '" + ComdatName +
670 "': noduplicates has been violated!");
671 case Comdat::SelectionKind::ExactMatch:
672 case Comdat::SelectionKind::Largest:
673 case Comdat::SelectionKind::SameSize: {
676 if (getComdatLeader(DstM, ComdatName, DstGV) ||
677 getComdatLeader(SrcM, ComdatName, SrcGV))
680 const DataLayout &DstDL = DstM->getDataLayout();
681 const DataLayout &SrcDL = SrcM->getDataLayout();
686 if (Result == Comdat::SelectionKind::ExactMatch) {
688 return emitError(
"Linking COMDATs named '" + ComdatName +
689 "': ExactMatch violated!");
691 }
else if (Result == Comdat::SelectionKind::Largest) {
692 LinkFromSrc = SrcSize > DstSize;
693 }
else if (Result == Comdat::SelectionKind::SameSize) {
694 if (SrcSize != DstSize)
695 return emitError(
"Linking COMDATs named '" + ComdatName +
696 "': SameSize violated!");
708 bool ModuleLinker::getComdatResult(
const Comdat *SrcC,
716 if (DstCI == ComdatSymTab.
end()) {
723 const Comdat *DstC = &DstCI->second;
725 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
729 bool ModuleLinker::shouldLinkFromSource(
bool &LinkFromSrc,
733 if (OverrideFromSrc) {
747 if (SrcIsDeclaration) {
752 LinkFromSrc = DestIsDeclaration;
760 if (DestIsDeclaration) {
780 LinkFromSrc = SrcSize > DestSize;
806 "Unexpected linkage type!");
807 return emitError(
"Linking globals named '" + Src.
getName() +
808 "': symbol multiply defined!");
815 void ModuleLinker::computeTypeMapping() {
822 TypeMap.addTypeMapping(DGV->
getType(), SGV.getType());
828 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
829 TypeMap.addTypeMapping(DAT->
getElementType(), SAT->getElementType());
834 TypeMap.addTypeMapping(DGV->
getType(), SGV.getType());
839 TypeMap.addTypeMapping(DGV->
getType(), SGV.getType());
846 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
852 size_t DotPos =
ST->getName().rfind(
'.');
853 if (DotPos == 0 || DotPos == StringRef::npos ||
854 ST->getName().back() ==
'.' ||
855 !isdigit(static_cast<unsigned char>(
ST->getName()[DotPos + 1])))
859 StructType *DST = DstM->getTypeByName(
ST->getName().substr(0, DotPos));
880 if (TypeMap.DstStructTypesSet.hasType(DST))
881 TypeMap.addTypeMapping(DST,
ST);
886 TypeMap.linkDefinedTypeBodies();
892 assert(OldTy->getNumElements() == 2 &&
"Expected to upgrade from 2 elements");
896 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
903 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
906 std::vector<Constant *> Initializers;
908 Value *
Null = Constant::getNullValue(VoidPtrTy);
911 Initializers.push_back(ConstantStruct::get(
916 "Failed to copy all array elements");
919 ATy = ArrayType::get(NewTy, Initializers.size());
920 Constant *NewInit = ConstantArray::get(ATy, Initializers);
924 GV->isExternallyInitialized());
927 assert(GV->use_empty() &&
"program cannot use initializer list");
928 GV->eraseFromParent();
931 void ModuleLinker::upgradeMismatchedGlobalArray(
StringRef Name) {
933 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
936 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
949 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
950 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
951 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
955 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
961 void ModuleLinker::upgradeMismatchedGlobals() {
962 upgradeMismatchedGlobalArray(
"llvm.global_ctors");
963 upgradeMismatchedGlobalArray(
"llvm.global_dtors");
972 return emitError(
"Linking globals named '" + SrcGV->
getName() +
973 "': can only link appending global with another appending global!");
981 if (EltTy != SrcTy->getElementType())
982 return emitError(
"Appending variables with different element types!");
984 return emitError(
"Appending variables linked with different const'ness!");
988 "Appending variables with different alignment need to be linked!");
992 "Appending variables with different visibility need to be linked!");
996 "Appending variables with different unnamed_addr need to be linked!");
1000 "Appending variables with different section name need to be linked!");
1002 uint64_t NewSize = DstTy->
getNumElements() + SrcTy->getNumElements();
1003 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1015 AppendingVarInfo AVI;
1019 AppendingVars.push_back(AVI);
1023 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->
getType()));
1029 DoNotLinkFromSource.insert(SrcGV);
1034 bool ModuleLinker::linkGlobalValueProto(
GlobalValue *SGV) {
1039 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
1040 cast<GlobalVariable>(SGV));
1042 bool LinkFromSrc =
true;
1049 std::tie(SK, LinkFromSrc) = ComdatsChosen[
SC];
1050 C = DstM->getOrInsertComdat(
SC->getName());
1053 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1060 DoNotLinkFromSource.insert(SGV);
1065 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->
getType()));
1075 if (!LinkFromSrc && !DGV)
1084 if (!DGV && !OverrideFromSrc &&
1087 DoNotLinkFromSource.insert(SGV);
1093 if (DGV && isa<Function>(DGV))
1094 if (
auto *NewF = dyn_cast<Function>(NewGV))
1095 OverridingFunctions.insert(NewF);
1101 if (
auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1103 NewGO->setComdat(C);
1109 if (
auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1110 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1112 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1113 (!DGVar->isConstant() || !SGVar->isConstant()))
1131 unsigned NumElements = cast<ArrayType>(C->
getType())->getNumElements();
1133 for (
unsigned i = 0; i != NumElements; ++i)
1137 void ModuleLinker::linkAppendingVarInit(
const AppendingVarInfo &AVI) {
1145 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1148 bool IsNewStructor =
1149 (Name ==
"llvm.global_ctors" || Name ==
"llvm.global_dtors") &&
1150 cast<StructType>(NewType->
getElementType())->getNumElements() == 3;
1152 for (
auto *V : SrcElements) {
1153 if (IsNewStructor) {
1154 Constant *Key = V->getAggregateElement(2);
1155 if (DoNotLinkFromSource.count(Key))
1161 if (IsNewStructor) {
1163 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1166 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1185 return emitError(EC.message());
1195 &TypeMap, &ValMaterializer));
1200 &TypeMap, &ValMaterializer));
1205 DI->setName(Arg.getName());
1215 for (
const auto &
I : MDs)
1246 bool ModuleLinker::linkGlobalValueBody(
GlobalValue &Src) {
1249 if (
auto *
F = dyn_cast<Function>(&Src))
1250 return linkFunctionBody(cast<Function>(*Dst), *
F);
1251 if (
auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1252 linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1255 linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1260 void ModuleLinker::linkNamedMDNodes() {
1261 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1262 for (
const NamedMDNode &NMD : SrcM->named_metadata()) {
1264 if (&NMD == SrcModFlags)
1266 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(NMD.getName());
1268 for (
const MDNode *
op : NMD.operands())
1280 void ModuleLinker::stripReplacedSubprograms() {
1282 if (OverridingFunctions.empty())
1286 auto Functions = std::move(OverridingFunctions);
1287 OverridingFunctions.clear();
1291 NamedMDNode *CompileUnits = DstM->getNamedMetadata(
"llvm.dbg.cu");
1295 auto *CU = cast<DICompileUnit>(CompileUnits->
getOperand(
I));
1296 assert(CU &&
"Expected valid compile unit");
1299 if (!SP || !
SP->getFunction() || !Functions.count(
SP->getFunction()))
1304 SP->replaceFunction(
nullptr);
1310 bool ModuleLinker::linkModuleFlagsMetadata() {
1312 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1313 if (!SrcModFlags)
return false;
1317 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1336 Flags[
ID] = std::make_pair(Op,
I);
1342 bool HasErr =
false;
1346 mdconst::extract<ConstantInt>(SrcOp->
getOperand(0));
1350 std::tie(DstOp, DstIndex) = Flags.
lookup(ID);
1351 unsigned SrcBehaviorValue = SrcBehavior->
getZExtValue();
1354 if (SrcBehaviorValue == Module::Require) {
1372 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1373 unsigned DstBehaviorValue = DstBehavior->
getZExtValue();
1376 if (DstBehaviorValue == Module::Override) {
1378 if (SrcBehaviorValue == Module::Override &&
1379 SrcOp->
getOperand(2) != DstOp->getOperand(2)) {
1380 HasErr |= emitError(
"linking module flags '" + ID->getString() +
1381 "': IDs have conflicting override values");
1384 }
else if (SrcBehaviorValue == Module::Override) {
1387 Flags[
ID].first = SrcOp;
1392 if (SrcBehaviorValue != DstBehaviorValue) {
1393 HasErr |= emitError(
"linking module flags '" + ID->getString() +
1394 "': IDs have conflicting behaviors");
1398 auto replaceDstValue = [&](
MDNode *New) {
1399 Metadata *FlagOps[] = {DstOp->getOperand(0),
ID, New};
1400 MDNode *
Flag = MDNode::get(DstM->getContext(), FlagOps);
1406 switch (SrcBehaviorValue) {
1407 case Module::Require:
1411 if (SrcOp->
getOperand(2) != DstOp->getOperand(2)) {
1412 HasErr |= emitError(
"linking module flags '" + ID->getString() +
1413 "': IDs have conflicting values");
1417 case Module::Warning: {
1419 if (SrcOp->
getOperand(2) != DstOp->getOperand(2)) {
1420 emitWarning(
"linking module flags '" + ID->getString() +
1421 "': IDs have conflicting values");
1425 case Module::Append: {
1426 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1431 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1433 replaceDstValue(MDNode::get(DstM->getContext(), MDs));
1436 case Module::AppendUnique: {
1438 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1441 Elts.
insert(SrcValue->op_begin(), SrcValue->op_end());
1443 replaceDstValue(MDNode::get(DstM->getContext(),
1451 for (
unsigned I = 0, E = Requirements.
size();
I != E; ++
I) {
1452 MDNode *Requirement = Requirements[
I];
1458 HasErr |= emitError(
"linking module flags '" + Flag->
getString() +
1459 "': does not have the required value");
1484 return SrcTriple.
str();
1486 return DstTriple.
str();
1489 bool ModuleLinker::run() {
1490 assert(DstM &&
"Null destination module");
1491 assert(SrcM &&
"Null source module");
1495 if (DstM->getDataLayout().isDefault())
1496 DstM->setDataLayout(SrcM->getDataLayout());
1498 if (SrcM->getDataLayout() != DstM->getDataLayout()) {
1499 emitWarning(
"Linking two modules of different data layouts: '" +
1500 SrcM->getModuleIdentifier() +
"' is '" +
1501 SrcM->getDataLayoutStr() +
"' whereas '" +
1502 DstM->getModuleIdentifier() +
"' is '" +
1503 DstM->getDataLayoutStr() +
"'\n");
1507 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1508 DstM->setTargetTriple(SrcM->getTargetTriple());
1510 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
1512 if (!SrcM->getTargetTriple().empty() && !
triplesMatch(SrcTriple, DstTriple))
1513 emitWarning(
"Linking two modules of different target triples: " +
1514 SrcM->getModuleIdentifier() +
"' is '" +
1515 SrcM->getTargetTriple() +
"' whereas '" +
1516 DstM->getModuleIdentifier() +
"' is '" +
1517 DstM->getTargetTriple() +
"'\n");
1519 DstM->setTargetTriple(
mergeTriples(SrcTriple, DstTriple));
1522 if (!SrcM->getModuleInlineAsm().empty()) {
1523 if (DstM->getModuleInlineAsm().empty())
1524 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1526 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+
"\n"+
1527 SrcM->getModuleInlineAsm());
1531 computeTypeMapping();
1533 ComdatsChosen.clear();
1534 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
1535 const Comdat &C = SMEC.getValue();
1536 if (ComdatsChosen.count(&C))
1540 if (getComdatResult(&C, SK, LinkFromSrc))
1542 ComdatsChosen[&
C] = std::make_pair(SK, LinkFromSrc);
1546 upgradeMismatchedGlobals();
1551 if (linkGlobalValueProto(&GV))
1560 if (linkGlobalValueProto(&
F))
1565 if (linkGlobalValueProto(&GA))
1568 for (
const AppendingVarInfo &AppendingVar : AppendingVars)
1569 linkAppendingVarInit(AppendingVar);
1571 for (
const auto &Entry : DstM->getComdatSymbolTable()) {
1572 const Comdat &C = Entry.getValue();
1585 stripReplacedSubprograms();
1591 if (SF.isDeclaration())
1595 if (DoNotLinkFromSource.count(&SF))
1598 if (linkGlobalValueBody(SF))
1604 if (DoNotLinkFromSource.count(&Src))
1606 linkGlobalValueBody(Src);
1615 if (linkModuleFlagsMetadata())
1622 if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1624 linkGlobalValueBody(Src);
1628 while (!LazilyLinkGlobalValues.empty()) {
1630 LazilyLinkGlobalValues.pop_back();
1632 assert(!SGV->
isDeclaration() &&
"users should not pass down decls");
1633 if (linkGlobalValueBody(*SGV))
1641 : ETypes(E), IsPacked(P) {}
1644 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1649 if (ETypes != That.
ETypes)
1679 return LHS ==
KeyTy(RHS);
1695 NonOpaqueStructTypes.insert(Ty);
1700 NonOpaqueStructTypes.insert(Ty);
1701 bool Removed = OpaqueStructTypes.erase(Ty);
1708 OpaqueStructTypes.insert(Ty);
1715 auto I = NonOpaqueStructTypes.find_as(Key);
1716 if (
I == NonOpaqueStructTypes.end())
1723 return OpaqueStructTypes.count(Ty);
1724 auto I = NonOpaqueStructTypes.find(Ty);
1725 if (
I == NonOpaqueStructTypes.end())
1731 this->Composite = M;
1732 this->DiagnosticHandler = DiagnosticHandler;
1735 StructTypes.
run(*M,
true);
1738 IdentifiedStructTypes.addOpaque(Ty);
1740 IdentifiedStructTypes.addNonOpaque(Ty);
1745 init(M, DiagnosticHandler);
1759 Composite =
nullptr;
1763 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1764 DiagnosticHandler, OverrideSymbols);
1765 bool RetCode = TheLinker.run();
1766 Composite->dropTriviallyDeadConstantArrays();
1771 init(Dst, DiagnosticHandler);
1785 Linker L(Dest, DiagnosticHandler);
1801 std::string Message;
1808 if (OutMessages && Result) {
1810 *OutMessages = strdup(Message.c_str());
void setVisibility(VisibilityTypes V)
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
bool operator!=(const KeyTy &that) const
void setPersonalityFn(Constant *C)
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
LinkageTypes getLinkage() const
VisibilityTypes getVisibility() const
virtual void copyAttributesFrom(const GlobalValue *Src)
Copy all additional attributes (those not needed to create a GlobalValue) from the GlobalValue Src to...
LLVM Argument representation.
Constant * getPrologueData() const
static GlobalAlias * copyGlobalAliasProto(TypeMapTy &TypeMap, Module &DstM, const GlobalAlias *SGA)
Set up prototypes for any aliases that come over from the source module.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
bool isOpaque() const
isOpaque - Return true if this is a type with an identity that has no body specified yet...
bool operator==(const KeyTy &that) const
static bool LinkModules(Module *Dest, Module *Src, DiagnosticHandlerFunction DiagnosticHandler)
This function links two modules together, with the resulting Dest module modified to be the composite...
A Module instance is used to store all the information related to an LLVM module. ...
ArrayRef< Type * > ETypes
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
unsigned getNumOperands() const
unsigned getNumOperands() const
Return number of MDNode operands.
void addOperand(MDNode *M)
bool hasAppendingLinkage() const
static PointerType * get(Type *ElementType, unsigned AddressSpace)
PointerType::get - This constructs a pointer to an object of the specified type in a numbered address...
iterator find(StringRef Key)
bool hasAvailableExternallyLinkage() const
static volatile int * Null
op_iterator op_begin() const
const std::string & str() const
bool hasPrologueData() const
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static bool isLessConstraining(GlobalValue::VisibilityTypes a, GlobalValue::VisibilityTypes b)
ELFYAML::ELF_STV Visibility
void reserve(size_type N)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void setOperand(unsigned I, MDNode *New)
iterator end()
Get an iterator to the end of the SetVector.
const Constant * getAliasee() const
static void getArrayElements(const Constant *C, SmallVectorImpl< Constant * > &Dest)
op_iterator op_end() const
size_type size() const
Determine the number of elements in the SetVector.
Type * getPointerElementType() const
StringRef getName() const
Return a constant reference to the value's name.
static bool triplesMatch(const Triple &T0, const Triple &T1)
bool hasCommonLinkage() const
static StructType * getEmptyKey()
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
StructType - Class to represent struct types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isLiteral() const
isLiteral - Return true if this type is uniqued by structural equivalence, false if it is a struct de...
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
void setName(const Twine &Name)
Change the name of the value.
Interface for custom diagnostic printing.
void eraseFromParent() override
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV)
copy additional attributes (those not needed to construct a GlobalValue) from the SrcGV to the DestGV...
StringRef getName() const
Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
FunctionType - Class to represent function types.
bool insert(const value_type &X)
Insert a new element into the SetVector.
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
unsigned getAlignment() const
ArrayType - Class to represent array types.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
iterator begin()
Get an iterator to the beginning of the SetVector.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
FunctionType::get - This static method is the primary way of constructing a FunctionType.
This class provides the core functionality of linking in LLVM.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
TypeID getTypeID() const
getTypeID - Return the type id for the type.
static void forceRenaming(GlobalValue *GV, StringRef Name)
The LLVM SymbolTable class autorenames globals that conflict in the symbol table. ...
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void switchToNonOpaque(StructType *Ty)
void takeName(Value *V)
Transfer the name from V to this value.
bool linkInModule(Module *Src, bool OverrideSymbols=false)
Link Src into the composite.
Type * getElementType() const
PointerType - Class to represent pointers.
RF_IgnoreMissingEntries - If this flag is set, the remapper ignores entries that are not in the value...
SubArchType getSubArch() const
getSubArch - get the parsed subarchitecture type for this triple.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
static void upgradeGlobalArray(GlobalVariable *GV)
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, LLVMLinkerMode Unused, char **OutMessages)
static GlobalVariable * copyGlobalVariableProto(TypeMapTy &TypeMap, Module &DstM, const GlobalVariable *SGVar)
Loop through the global variables in the src module and merge them into the dest module.
ValueMaterializer - This is a class that can be implemented by clients to materialize Values on deman...
DataLayout * unwrap(LLVMTargetDataRef P)
This is the base abstract class for diagnostic reporting in the backend.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Type * getContainedType(unsigned i) const
getContainedType - This method is used to implement the type iterator (defined at the end of the file...
This is an important base class in LLVM.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static void RemapInstruction(Instruction *I, ValueToValueMapTy &VMap)
RemapInstruction - Convert the instruction operands from referencing the current values into those sp...
bool hasPersonalityFn() const
Get the personality function associated with this function.
static Function * copyFunctionProto(TypeMapTy &TypeMap, Module &DstM, const Function *SF)
Link the function in the source module into the destination module if needed, setting up mapping info...
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
KeyTy(ArrayRef< Type * > E, bool P)
uint64_t getNumElements() const
MDNode * getOperand(unsigned i) const
bool hasType(StructType *Ty)
Value * getOperand(unsigned i) const
SelectionKind getSelectionKind() const
void addOpaque(StructType *Ty)
Constant * getAggregateElement(unsigned Elt) const
getAggregateElement - For aggregates (struct/array/vector) return the constant that corresponds to th...
void setConstant(bool Val)
unsigned getNumContainedTypes() const
getNumContainedTypes - Return the number of types in the derived type.
bool hasWeakLinkage() const
LLVMContext & getContext() const
All values hold a context through their type.
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
setBody - Specify a body for an opaque identified type.
void setModule(Module *Dst)
Set the composite to the passed-in module.
Triple - Helper class for working with autoconf configuration names.
static unsigned getHashValue(const KeyTy &Key)
const char * getSection() const
bool hasExternalWeakLinkage() const
StringRef getString() const
bool hasExternalLinkage() const
bool hasDLLImportStorageClass() const
const MDOperand & getOperand(unsigned I) const
A SetVector that performs no allocations if smaller than a certain size.
const BasicBlockListType & getBasicBlockList() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
15: SIMD 'packed' format, or other vector type
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
void run(const Module &M, bool onlyNamed)
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
StructType::get - This static method is the primary way to create a literal StructType.
bool hasName() const
hasName - Return true if this is a named struct that has a non-empty name.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple)
void setUnnamedAddr(bool Val)
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Get all current metadata attachments.
std::function< void(const DiagnosticInfo &)> DiagnosticHandlerFunction
CHAIN = SC CHAIN, Imm128 - System call.
static bool isEqual(const KeyTy &LHS, const StructType *RHS)
void splice(iterator where, iplist &L2)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
VectorType - Class to represent vector types.
ConstantArray - Constant Array Declarations.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
StringRef getName() const
getName - Return the name for this struct type if it has an identity.
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
void addNonOpaque(StructType *Ty)
ValueMapTypeRemapper - This is a class that can be implemented by clients to remap types when cloning...
bool isOSVersionLT(unsigned Major, unsigned Minor=0, unsigned Micro=0) const
isOSVersionLT - Helper function for doing comparisons against version numbers included in the target ...
Basic diagnostic printer that uses an underlying raw_ostream.
StructType * findNonOpaque(ArrayRef< Type * > ETypes, bool IsPacked)
ThreadLocalMode getThreadLocalMode() const
bool hasLinkOnceLinkage() const
void setName(StringRef Name)
setName - Change the name of this type to the specified name, or to a name with a suffix if there is ...
PointerType * getType() const
Global values are always pointers.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Constant * getPersonalityFn() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
FunctionType * getFunctionType() const
void setPrologueData(Constant *PrologueData)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
ArrayType::get - This static method is the primary way to construct an ArrayType. ...
bool hasPrefixData() const
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Constant * getPrefixData() const
bool hasLocalLinkage() const
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
void copyAttributesFrom(const GlobalValue *Src) override
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
unsigned getAlignment() const
A raw_ostream that writes to an std::string.
static GlobalValue * copyGlobalValueProto(TypeMapTy &TypeMap, Module &DstM, const GlobalValue *SGV)
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
bool hasUnnamedAddr() const
static VectorType * get(Type *ElementType, unsigned NumElements)
VectorType::get - This static method is the primary way to construct an VectorType.
void dematerialize()
If this GlobalValue is read in, and if the GVMaterializer supports it, release the memory for the fun...
static StructType * create(LLVMContext &Context, StringRef Name)
StructType::create - This creates an identified struct.
virtual void eraseFromParent()=0
This method unlinks 'this' from the containing module and deletes it.
unsigned getNumOperands() const
VendorType getVendor() const
getVendor - Get the parsed vendor type of this triple.
C - The default llvm calling convention, compatible with C.
StringRef - Represent a constant reference to a string, i.e.
bool operator==(uint64_t V1, const APInt &V2)
TypeFinder - Walk over a module, identifying all of the types that are used by the module...
std::error_code materialize()
Make sure this GlobalValue is fully read.
bool isDeclarationForLinker() const
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
static StructType * getTombstoneKey()
void setAliasee(Constant *Aliasee)
These methods retrive and set alias target.
iterator_range< arg_iterator > args()
bool erase(const KeyT &Val)
LLVMContext & getContext() const
Get the global data context.
void setPrefixData(Constant *PrefixData)