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