1 //===-- X86Subtarget.cpp - X86 Subtarget Information ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the X86 specific subclass of TargetSubtargetInfo.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86Subtarget.h"
14 #include "MCTargetDesc/X86BaseInfo.h"
15 #include "X86.h"
16 #include "X86CallLowering.h"
17 #include "X86LegalizerInfo.h"
18 #include "X86MacroFusion.h"
19 #include "X86RegisterBankInfo.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
23 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/ConstantRange.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/CodeGen.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
35 
36 #if defined(_MSC_VER)
37 #include <intrin.h>
38 #endif
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "subtarget"
43 
44 #define GET_SUBTARGETINFO_TARGET_DESC
45 #define GET_SUBTARGETINFO_CTOR
46 #include "X86GenSubtargetInfo.inc"
47 
48 // Temporary option to control early if-conversion for x86 while adding machine
49 // models.
50 static cl::opt<bool>
51 X86EarlyIfConv("x86-early-ifcvt", cl::Hidden,
52                cl::desc("Enable early if-conversion on X86"));
53 
54 
55 /// Classify a blockaddress reference for the current subtarget according to how
56 /// we should reference it in a non-pcrel context.
57 unsigned char X86Subtarget::classifyBlockAddressReference() const {
58   return classifyLocalReference(nullptr);
59 }
60 
61 /// Classify a global variable reference for the current subtarget according to
62 /// how we should reference it in a non-pcrel context.
63 unsigned char
64 X86Subtarget::classifyGlobalReference(const GlobalValue *GV) const {
65   return classifyGlobalReference(GV, *GV->getParent());
66 }
67 
68 unsigned char
69 X86Subtarget::classifyLocalReference(const GlobalValue *GV) const {
70   // Tagged globals have non-zero upper bits, which makes direct references
71   // require a 64-bit immediate.  On the small code model this causes relocation
72   // errors, so we go through the GOT instead.
73   if (AllowTaggedGlobals && TM.getCodeModel() == CodeModel::Small && GV &&
74       !isa<Function>(GV))
75     return X86II::MO_GOTPCREL;
76 
77   // If we're not PIC, it's not very interesting.
78   if (!isPositionIndependent())
79     return X86II::MO_NO_FLAG;
80 
81   if (is64Bit()) {
82     // 64-bit ELF PIC local references may use GOTOFF relocations.
83     if (isTargetELF()) {
84       switch (TM.getCodeModel()) {
85       // 64-bit small code model is simple: All rip-relative.
86       case CodeModel::Tiny:
87         llvm_unreachable("Tiny codesize model not supported on X86");
88       case CodeModel::Small:
89       case CodeModel::Kernel:
90         return X86II::MO_NO_FLAG;
91 
92       // The large PIC code model uses GOTOFF.
93       case CodeModel::Large:
94         return X86II::MO_GOTOFF;
95 
96       // Medium is a hybrid: RIP-rel for code, GOTOFF for DSO local data.
97       case CodeModel::Medium:
98         // Constant pool and jump table handling pass a nullptr to this
99         // function so we need to use isa_and_nonnull.
100         if (isa_and_nonnull<Function>(GV))
101           return X86II::MO_NO_FLAG; // All code is RIP-relative
102         return X86II::MO_GOTOFF;    // Local symbols use GOTOFF.
103       }
104       llvm_unreachable("invalid code model");
105     }
106 
107     // Otherwise, this is either a RIP-relative reference or a 64-bit movabsq,
108     // both of which use MO_NO_FLAG.
109     return X86II::MO_NO_FLAG;
110   }
111 
112   // The COFF dynamic linker just patches the executable sections.
113   if (isTargetCOFF())
114     return X86II::MO_NO_FLAG;
115 
116   if (isTargetDarwin()) {
117     // 32 bit macho has no relocation for a-b if a is undefined, even if
118     // b is in the section that is being relocated.
119     // This means we have to use o load even for GVs that are known to be
120     // local to the dso.
121     if (GV && (GV->isDeclarationForLinker() || GV->hasCommonLinkage()))
122       return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
123 
124     return X86II::MO_PIC_BASE_OFFSET;
125   }
126 
127   return X86II::MO_GOTOFF;
128 }
129 
130 unsigned char X86Subtarget::classifyGlobalReference(const GlobalValue *GV,
131                                                     const Module &M) const {
132   // The static large model never uses stubs.
133   if (TM.getCodeModel() == CodeModel::Large && !isPositionIndependent())
134     return X86II::MO_NO_FLAG;
135 
136   // Absolute symbols can be referenced directly.
137   if (GV) {
138     if (Optional<ConstantRange> CR = GV->getAbsoluteSymbolRange()) {
139       // See if we can use the 8-bit immediate form. Note that some instructions
140       // will sign extend the immediate operand, so to be conservative we only
141       // accept the range [0,128).
142       if (CR->getUnsignedMax().ult(128))
143         return X86II::MO_ABS8;
144       else
145         return X86II::MO_NO_FLAG;
146     }
147   }
148 
149   if (TM.shouldAssumeDSOLocal(M, GV))
150     return classifyLocalReference(GV);
151 
152   if (isTargetCOFF()) {
153     // ExternalSymbolSDNode like _tls_index.
154     if (!GV)
155       return X86II::MO_NO_FLAG;
156     if (GV->hasDLLImportStorageClass())
157       return X86II::MO_DLLIMPORT;
158     return X86II::MO_COFFSTUB;
159   }
160   // Some JIT users use *-win32-elf triples; these shouldn't use GOT tables.
161   if (isOSWindows())
162     return X86II::MO_NO_FLAG;
163 
164   if (is64Bit()) {
165     // ELF supports a large, truly PIC code model with non-PC relative GOT
166     // references. Other object file formats do not. Use the no-flag, 64-bit
167     // reference for them.
168     if (TM.getCodeModel() == CodeModel::Large)
169       return isTargetELF() ? X86II::MO_GOT : X86II::MO_NO_FLAG;
170     return X86II::MO_GOTPCREL;
171   }
172 
173   if (isTargetDarwin()) {
174     if (!isPositionIndependent())
175       return X86II::MO_DARWIN_NONLAZY;
176     return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
177   }
178 
179   // 32-bit ELF references GlobalAddress directly in static relocation model.
180   // We cannot use MO_GOT because EBX may not be set up.
181   if (TM.getRelocationModel() == Reloc::Static)
182     return X86II::MO_NO_FLAG;
183   return X86II::MO_GOT;
184 }
185 
186 unsigned char
187 X86Subtarget::classifyGlobalFunctionReference(const GlobalValue *GV) const {
188   return classifyGlobalFunctionReference(GV, *GV->getParent());
189 }
190 
191 unsigned char
192 X86Subtarget::classifyGlobalFunctionReference(const GlobalValue *GV,
193                                               const Module &M) const {
194   if (TM.shouldAssumeDSOLocal(M, GV))
195     return X86II::MO_NO_FLAG;
196 
197   // Functions on COFF can be non-DSO local for three reasons:
198   // - They are intrinsic functions (!GV)
199   // - They are marked dllimport
200   // - They are extern_weak, and a stub is needed
201   if (isTargetCOFF()) {
202     if (!GV)
203       return X86II::MO_NO_FLAG;
204     if (GV->hasDLLImportStorageClass())
205       return X86II::MO_DLLIMPORT;
206     return X86II::MO_COFFSTUB;
207   }
208 
209   const Function *F = dyn_cast_or_null<Function>(GV);
210 
211   if (isTargetELF()) {
212     if (is64Bit() && F && (CallingConv::X86_RegCall == F->getCallingConv()))
213       // According to psABI, PLT stub clobbers XMM8-XMM15.
214       // In Regcall calling convention those registers are used for passing
215       // parameters. Thus we need to prevent lazy binding in Regcall.
216       return X86II::MO_GOTPCREL;
217     // If PLT must be avoided then the call should be via GOTPCREL.
218     if (((F && F->hasFnAttribute(Attribute::NonLazyBind)) ||
219          (!F && M.getRtLibUseGOT())) &&
220         is64Bit())
221        return X86II::MO_GOTPCREL;
222     // Reference ExternalSymbol directly in static relocation model.
223     if (!is64Bit() && !GV && TM.getRelocationModel() == Reloc::Static)
224       return X86II::MO_NO_FLAG;
225     return X86II::MO_PLT;
226   }
227 
228   if (is64Bit()) {
229     if (F && F->hasFnAttribute(Attribute::NonLazyBind))
230       // If the function is marked as non-lazy, generate an indirect call
231       // which loads from the GOT directly. This avoids runtime overhead
232       // at the cost of eager binding (and one extra byte of encoding).
233       return X86II::MO_GOTPCREL;
234     return X86II::MO_NO_FLAG;
235   }
236 
237   return X86II::MO_NO_FLAG;
238 }
239 
240 /// Return true if the subtarget allows calls to immediate address.
241 bool X86Subtarget::isLegalToCallImmediateAddr() const {
242   // FIXME: I386 PE/COFF supports PC relative calls using IMAGE_REL_I386_REL32
243   // but WinCOFFObjectWriter::RecordRelocation cannot emit them.  Once it does,
244   // the following check for Win32 should be removed.
245   if (In64BitMode || isTargetWin32())
246     return false;
247   return isTargetELF() || TM.getRelocationModel() == Reloc::Static;
248 }
249 
250 void X86Subtarget::initSubtargetFeatures(StringRef CPU, StringRef TuneCPU,
251                                          StringRef FS) {
252   if (CPU.empty())
253     CPU = "generic";
254 
255   if (TuneCPU.empty())
256     TuneCPU = "i586"; // FIXME: "generic" is more modern than llc tests expect.
257 
258   std::string FullFS = X86_MC::ParseX86Triple(TargetTriple);
259   assert(!FullFS.empty() && "Failed to parse X86 triple");
260 
261   if (!FS.empty())
262     FullFS = (Twine(FullFS) + "," + FS).str();
263 
264   // Parse features string and set the CPU.
265   ParseSubtargetFeatures(CPU, TuneCPU, FullFS);
266 
267   // All CPUs that implement SSE4.2 or SSE4A support unaligned accesses of
268   // 16-bytes and under that are reasonably fast. These features were
269   // introduced with Intel's Nehalem/Silvermont and AMD's Family10h
270   // micro-architectures respectively.
271   if (hasSSE42() || hasSSE4A())
272     IsUAMem16Slow = false;
273 
274   LLVM_DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel
275                     << ", 3DNowLevel " << X863DNowLevel << ", 64bit "
276                     << HasX86_64 << "\n");
277   if (In64BitMode && !HasX86_64)
278     report_fatal_error("64-bit code requested on a subtarget that doesn't "
279                        "support it!");
280 
281   // Stack alignment is 16 bytes on Darwin, Linux, kFreeBSD, NaCl, and for all
282   // 64-bit targets.  On Solaris (32-bit), stack alignment is 4 bytes
283   // following the i386 psABI, while on Illumos it is always 16 bytes.
284   if (StackAlignOverride)
285     stackAlignment = *StackAlignOverride;
286   else if (isTargetDarwin() || isTargetLinux() || isTargetKFreeBSD() ||
287            isTargetNaCl() || In64BitMode)
288     stackAlignment = Align(16);
289 
290   // Consume the vector width attribute or apply any target specific limit.
291   if (PreferVectorWidthOverride)
292     PreferVectorWidth = PreferVectorWidthOverride;
293   else if (Prefer128Bit)
294     PreferVectorWidth = 128;
295   else if (Prefer256Bit)
296     PreferVectorWidth = 256;
297 }
298 
299 X86Subtarget &X86Subtarget::initializeSubtargetDependencies(StringRef CPU,
300                                                             StringRef TuneCPU,
301                                                             StringRef FS) {
302   initSubtargetFeatures(CPU, TuneCPU, FS);
303   return *this;
304 }
305 
306 X86Subtarget::X86Subtarget(const Triple &TT, StringRef CPU, StringRef TuneCPU,
307                            StringRef FS, const X86TargetMachine &TM,
308                            MaybeAlign StackAlignOverride,
309                            unsigned PreferVectorWidthOverride,
310                            unsigned RequiredVectorWidth)
311     : X86GenSubtargetInfo(TT, CPU, TuneCPU, FS),
312       PICStyle(PICStyles::Style::None), TM(TM), TargetTriple(TT),
313       StackAlignOverride(StackAlignOverride),
314       PreferVectorWidthOverride(PreferVectorWidthOverride),
315       RequiredVectorWidth(RequiredVectorWidth),
316       InstrInfo(initializeSubtargetDependencies(CPU, TuneCPU, FS)),
317       TLInfo(TM, *this), FrameLowering(*this, getStackAlignment()) {
318   // Determine the PICStyle based on the target selected.
319   if (!isPositionIndependent())
320     setPICStyle(PICStyles::Style::None);
321   else if (is64Bit())
322     setPICStyle(PICStyles::Style::RIPRel);
323   else if (isTargetCOFF())
324     setPICStyle(PICStyles::Style::None);
325   else if (isTargetDarwin())
326     setPICStyle(PICStyles::Style::StubPIC);
327   else if (isTargetELF())
328     setPICStyle(PICStyles::Style::GOT);
329 
330   CallLoweringInfo.reset(new X86CallLowering(*getTargetLowering()));
331   Legalizer.reset(new X86LegalizerInfo(*this, TM));
332 
333   auto *RBI = new X86RegisterBankInfo(*getRegisterInfo());
334   RegBankInfo.reset(RBI);
335   InstSelector.reset(createX86InstructionSelector(TM, *this, *RBI));
336 }
337 
338 const CallLowering *X86Subtarget::getCallLowering() const {
339   return CallLoweringInfo.get();
340 }
341 
342 InstructionSelector *X86Subtarget::getInstructionSelector() const {
343   return InstSelector.get();
344 }
345 
346 const LegalizerInfo *X86Subtarget::getLegalizerInfo() const {
347   return Legalizer.get();
348 }
349 
350 const RegisterBankInfo *X86Subtarget::getRegBankInfo() const {
351   return RegBankInfo.get();
352 }
353 
354 bool X86Subtarget::enableEarlyIfConversion() const {
355   return hasCMov() && X86EarlyIfConv;
356 }
357 
358 void X86Subtarget::getPostRAMutations(
359     std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
360   Mutations.push_back(createX86MacroFusionDAGMutation());
361 }
362 
363 bool X86Subtarget::isPositionIndependent() const {
364   return TM.isPositionIndependent();
365 }
366