xref: /llvm-project/llvm/lib/Target/X86/X86TargetObjectFile.cpp (revision 618c67a018ec523a2a3116421bd2a690cf696564)
1 //===-- X86TargetObjectFile.cpp - X86 Object Info -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "X86TargetObjectFile.h"
11 #include "llvm/ADT/StringExtras.h"
12 #include "llvm/IR/Mangler.h"
13 #include "llvm/IR/Operator.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCSectionCOFF.h"
17 #include "llvm/MC/MCSectionELF.h"
18 #include "llvm/MC/MCValue.h"
19 #include "llvm/Support/Dwarf.h"
20 #include "llvm/Target/TargetLowering.h"
21 
22 using namespace llvm;
23 using namespace dwarf;
24 
25 const MCExpr *X86_64MachoTargetObjectFile::getTTypeGlobalReference(
26     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
27     const TargetMachine &TM, MachineModuleInfo *MMI,
28     MCStreamer &Streamer) const {
29 
30   // On Darwin/X86-64, we can reference dwarf symbols with foo@GOTPCREL+4, which
31   // is an indirect pc-relative reference.
32   if ((Encoding & DW_EH_PE_indirect) && (Encoding & DW_EH_PE_pcrel)) {
33     const MCSymbol *Sym = TM.getSymbol(GV, Mang);
34     const MCExpr *Res =
35       MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_GOTPCREL, getContext());
36     const MCExpr *Four = MCConstantExpr::Create(4, getContext());
37     return MCBinaryExpr::CreateAdd(Res, Four, getContext());
38   }
39 
40   return TargetLoweringObjectFileMachO::getTTypeGlobalReference(
41       GV, Encoding, Mang, TM, MMI, Streamer);
42 }
43 
44 MCSymbol *X86_64MachoTargetObjectFile::getCFIPersonalitySymbol(
45     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
46     MachineModuleInfo *MMI) const {
47   return TM.getSymbol(GV, Mang);
48 }
49 
50 const MCExpr *X86_64MachoTargetObjectFile::getIndirectSymViaGOTPCRel(
51     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
52     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
53   // On Darwin/X86-64, we need to use foo@GOTPCREL+4 to access the got entry
54   // from a data section. In case there's an additional offset, then use
55   // foo@GOTPCREL+4+<offset>.
56   unsigned FinalOff = Offset+MV.getConstant()+4;
57   const MCExpr *Res =
58     MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_GOTPCREL, getContext());
59   const MCExpr *Off = MCConstantExpr::Create(FinalOff, getContext());
60   return MCBinaryExpr::CreateAdd(Res, Off, getContext());
61 }
62 
63 const MCExpr *X86ELFTargetObjectFile::getDebugThreadLocalSymbol(
64     const MCSymbol *Sym) const {
65   return MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_DTPOFF, getContext());
66 }
67 
68 void
69 X86LinuxTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM) {
70   TargetLoweringObjectFileELF::Initialize(Ctx, TM);
71   InitializeELF(TM.Options.UseInitArray);
72 }
73 
74 const MCExpr *X86WindowsTargetObjectFile::getExecutableRelativeSymbol(
75     const ConstantExpr *CE, Mangler &Mang, const TargetMachine &TM) const {
76   // We are looking for the difference of two symbols, need a subtraction
77   // operation.
78   const SubOperator *Sub = dyn_cast<SubOperator>(CE);
79   if (!Sub)
80     return nullptr;
81 
82   // Symbols must first be numbers before we can subtract them, we need to see a
83   // ptrtoint on both subtraction operands.
84   const PtrToIntOperator *SubLHS =
85       dyn_cast<PtrToIntOperator>(Sub->getOperand(0));
86   const PtrToIntOperator *SubRHS =
87       dyn_cast<PtrToIntOperator>(Sub->getOperand(1));
88   if (!SubLHS || !SubRHS)
89     return nullptr;
90 
91   // Our symbols should exist in address space zero, cowardly no-op if
92   // otherwise.
93   if (SubLHS->getPointerAddressSpace() != 0 ||
94       SubRHS->getPointerAddressSpace() != 0)
95     return nullptr;
96 
97   // Both ptrtoint instructions must wrap global objects:
98   // - Only global variables are eligible for image relative relocations.
99   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
100   const auto *GOLHS = dyn_cast<GlobalObject>(SubLHS->getPointerOperand());
101   const auto *GVRHS = dyn_cast<GlobalVariable>(SubRHS->getPointerOperand());
102   if (!GOLHS || !GVRHS)
103     return nullptr;
104 
105   // We expect __ImageBase to be a global variable without a section, externally
106   // defined.
107   //
108   // It should look something like this: @__ImageBase = external constant i8
109   if (GVRHS->isThreadLocal() || GVRHS->getName() != "__ImageBase" ||
110       !GVRHS->hasExternalLinkage() || GVRHS->hasInitializer() ||
111       GVRHS->hasSection())
112     return nullptr;
113 
114   // An image-relative, thread-local, symbol makes no sense.
115   if (GOLHS->isThreadLocal())
116     return nullptr;
117 
118   return MCSymbolRefExpr::Create(TM.getSymbol(GOLHS, Mang),
119                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
120                                  getContext());
121 }
122 
123 static std::string APIntToHexString(const APInt &AI) {
124   unsigned Width = (AI.getBitWidth() / 8) * 2;
125   std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
126   unsigned Size = HexString.size();
127   assert(Width >= Size && "hex string is too large!");
128   HexString.insert(HexString.begin(), Width - Size, '0');
129 
130   return HexString;
131 }
132 
133 
134 static std::string scalarConstantToHexString(const Constant *C) {
135   Type *Ty = C->getType();
136   APInt AI;
137   if (isa<UndefValue>(C)) {
138     AI = APInt(Ty->getPrimitiveSizeInBits(), /*val=*/0);
139   } else if (Ty->isFloatTy() || Ty->isDoubleTy()) {
140     const auto *CFP = cast<ConstantFP>(C);
141     AI = CFP->getValueAPF().bitcastToAPInt();
142   } else if (Ty->isIntegerTy()) {
143     const auto *CI = cast<ConstantInt>(C);
144     AI = CI->getValue();
145   } else {
146     llvm_unreachable("unexpected constant pool element type!");
147   }
148   return APIntToHexString(AI);
149 }
150 
151 const MCSection *
152 X86WindowsTargetObjectFile::getSectionForConstant(SectionKind Kind,
153                                                   const Constant *C) const {
154   if (Kind.isReadOnly()) {
155     if (C) {
156       Type *Ty = C->getType();
157       SmallString<32> COMDATSymName;
158       if (Ty->isFloatTy() || Ty->isDoubleTy()) {
159         COMDATSymName = "__real@";
160         COMDATSymName += scalarConstantToHexString(C);
161       } else if (const auto *VTy = dyn_cast<VectorType>(Ty)) {
162         uint64_t NumBits = VTy->getBitWidth();
163         if (NumBits == 128 || NumBits == 256) {
164           COMDATSymName = NumBits == 128 ? "__xmm@" : "__ymm@";
165           for (int I = VTy->getNumElements() - 1, E = -1; I != E; --I)
166             COMDATSymName +=
167                 scalarConstantToHexString(C->getAggregateElement(I));
168         }
169       }
170       if (!COMDATSymName.empty()) {
171         unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
172                                    COFF::IMAGE_SCN_MEM_READ |
173                                    COFF::IMAGE_SCN_LNK_COMDAT;
174         return getContext().getCOFFSection(".rdata", Characteristics, Kind,
175                                            COMDATSymName,
176                                            COFF::IMAGE_COMDAT_SELECT_ANY);
177       }
178     }
179   }
180 
181   return TargetLoweringObjectFile::getSectionForConstant(Kind, C);
182 }
183