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