1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the X86 specific subclass of TargetMachine.
11 //===----------------------------------------------------------------------===//
13 #include "X86TargetMachine.h"
14 #include "MCTargetDesc/X86MCTargetDesc.h"
15 #include "TargetInfo/X86TargetInfo.h"
17 #include "X86CallLowering.h"
18 #include "X86LegalizerInfo.h"
19 #include "X86MacroFusion.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetObjectFile.h"
22 #include "X86TargetTransformInfo.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/CodeGen/ExecutionDomainFix.h"
30 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
31 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
32 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
33 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
34 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
35 #include "llvm/CodeGen/MachineScheduler.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/CodeGen/TargetPassConfig.h"
38 #include "llvm/IR/Attributes.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetOptions.h"
54 static cl::opt
<bool> EnableMachineCombinerPass("x86-machine-combiner",
55 cl::desc("Enable the machine combiner pass"),
56 cl::init(true), cl::Hidden
);
58 static cl::opt
<bool> EnableCondBrFoldingPass("x86-condbr-folding",
59 cl::desc("Enable the conditional branch "
61 cl::init(false), cl::Hidden
);
63 extern "C" void LLVMInitializeX86Target() {
64 // Register the target.
65 RegisterTargetMachine
<X86TargetMachine
> X(getTheX86_32Target());
66 RegisterTargetMachine
<X86TargetMachine
> Y(getTheX86_64Target());
68 PassRegistry
&PR
= *PassRegistry::getPassRegistry();
69 initializeGlobalISel(PR
);
70 initializeWinEHStatePassPass(PR
);
71 initializeFixupBWInstPassPass(PR
);
72 initializeEvexToVexInstPassPass(PR
);
73 initializeFixupLEAPassPass(PR
);
74 initializeFPSPass(PR
);
75 initializeX86CallFrameOptimizationPass(PR
);
76 initializeX86CmovConverterPassPass(PR
);
77 initializeX86ExpandPseudoPass(PR
);
78 initializeX86ExecutionDomainFixPass(PR
);
79 initializeX86DomainReassignmentPass(PR
);
80 initializeX86AvoidSFBPassPass(PR
);
81 initializeX86SpeculativeLoadHardeningPassPass(PR
);
82 initializeX86FlagsCopyLoweringPassPass(PR
);
83 initializeX86CondBrFoldingPassPass(PR
);
84 initializeX86OptimizeLEAPassPass(PR
);
87 static std::unique_ptr
<TargetLoweringObjectFile
> createTLOF(const Triple
&TT
) {
88 if (TT
.isOSBinFormatMachO()) {
89 if (TT
.getArch() == Triple::x86_64
)
90 return std::make_unique
<X86_64MachoTargetObjectFile
>();
91 return std::make_unique
<TargetLoweringObjectFileMachO
>();
95 return std::make_unique
<X86FreeBSDTargetObjectFile
>();
96 if (TT
.isOSLinux() || TT
.isOSNaCl() || TT
.isOSIAMCU())
97 return std::make_unique
<X86LinuxNaClTargetObjectFile
>();
99 return std::make_unique
<X86SolarisTargetObjectFile
>();
100 if (TT
.isOSFuchsia())
101 return std::make_unique
<X86FuchsiaTargetObjectFile
>();
102 if (TT
.isOSBinFormatELF())
103 return std::make_unique
<X86ELFTargetObjectFile
>();
104 if (TT
.isOSBinFormatCOFF())
105 return std::make_unique
<TargetLoweringObjectFileCOFF
>();
106 llvm_unreachable("unknown subtarget type");
109 static std::string
computeDataLayout(const Triple
&TT
) {
110 // X86 is little endian
111 std::string Ret
= "e";
113 Ret
+= DataLayout::getManglingComponent(TT
);
114 // X86 and x32 have 32 bit pointers.
115 if ((TT
.isArch64Bit() &&
116 (TT
.getEnvironment() == Triple::GNUX32
|| TT
.isOSNaCl())) ||
120 // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
121 if (TT
.isArch64Bit() || TT
.isOSWindows() || TT
.isOSNaCl())
123 else if (TT
.isOSIAMCU())
124 Ret
+= "-i64:32-f64:32";
128 // Some ABIs align long double to 128 bits, others to 32.
129 if (TT
.isOSNaCl() || TT
.isOSIAMCU())
131 else if (TT
.isArch64Bit() || TT
.isOSDarwin())
139 // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
140 if (TT
.isArch64Bit())
141 Ret
+= "-n8:16:32:64";
145 // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
146 if ((!TT
.isArch64Bit() && TT
.isOSWindows()) || TT
.isOSIAMCU())
147 Ret
+= "-a:0:32-S32";
154 static Reloc::Model
getEffectiveRelocModel(const Triple
&TT
,
156 Optional
<Reloc::Model
> RM
) {
157 bool is64Bit
= TT
.getArch() == Triple::x86_64
;
158 if (!RM
.hasValue()) {
159 // JIT codegen should use static relocations by default, since it's
160 // typically executed in process and not relocatable.
162 return Reloc::Static
;
164 // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
165 // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
166 // use static relocation model by default.
167 if (TT
.isOSDarwin()) {
170 return Reloc::DynamicNoPIC
;
172 if (TT
.isOSWindows() && is64Bit
)
174 return Reloc::Static
;
177 // ELF and X86-64 don't have a distinct DynamicNoPIC model. DynamicNoPIC
178 // is defined as a model for code which may be used in static or dynamic
179 // executables but not necessarily a shared library. On X86-32 we just
180 // compile in -static mode, in x86-64 we use PIC.
181 if (*RM
== Reloc::DynamicNoPIC
) {
184 if (!TT
.isOSDarwin())
185 return Reloc::Static
;
188 // If we are on Darwin, disallow static relocation model in X86-64 mode, since
189 // the Mach-O file format doesn't support it.
190 if (*RM
== Reloc::Static
&& TT
.isOSDarwin() && is64Bit
)
196 static CodeModel::Model
getEffectiveX86CodeModel(Optional
<CodeModel::Model
> CM
,
197 bool JIT
, bool Is64Bit
) {
199 if (*CM
== CodeModel::Tiny
)
200 report_fatal_error("Target does not support the tiny CodeModel", false);
204 return Is64Bit
? CodeModel::Large
: CodeModel::Small
;
205 return CodeModel::Small
;
208 /// Create an X86 target.
210 X86TargetMachine::X86TargetMachine(const Target
&T
, const Triple
&TT
,
211 StringRef CPU
, StringRef FS
,
212 const TargetOptions
&Options
,
213 Optional
<Reloc::Model
> RM
,
214 Optional
<CodeModel::Model
> CM
,
215 CodeGenOpt::Level OL
, bool JIT
)
217 T
, computeDataLayout(TT
), TT
, CPU
, FS
, Options
,
218 getEffectiveRelocModel(TT
, JIT
, RM
),
219 getEffectiveX86CodeModel(CM
, JIT
, TT
.getArch() == Triple::x86_64
),
221 TLOF(createTLOF(getTargetTriple())) {
222 // Windows stack unwinder gets confused when execution flow "falls through"
223 // after a call to 'noreturn' function.
224 // To prevent that, we emit a trap for 'unreachable' IR instructions.
225 // (which on X86, happens to be the 'ud2' instruction)
226 // On PS4, the "return address" of a 'noreturn' call must still be within
227 // the calling function, and TrapUnreachable is an easy way to get that.
228 // The check here for 64-bit windows is a bit icky, but as we're unlikely
229 // to ever want to mix 32 and 64-bit windows code in a single module
230 // this should be fine.
231 if ((TT
.isOSWindows() && TT
.getArch() == Triple::x86_64
) || TT
.isPS4() ||
232 TT
.isOSBinFormatMachO()) {
233 this->Options
.TrapUnreachable
= true;
234 this->Options
.NoTrapAfterNoreturn
= TT
.isOSBinFormatMachO();
237 // Outlining is available for x86-64.
238 if (TT
.getArch() == Triple::x86_64
)
239 setMachineOutliner(true);
244 X86TargetMachine::~X86TargetMachine() = default;
247 X86TargetMachine::getSubtargetImpl(const Function
&F
) const {
248 Attribute CPUAttr
= F
.getFnAttribute("target-cpu");
249 Attribute FSAttr
= F
.getFnAttribute("target-features");
251 StringRef CPU
= !CPUAttr
.hasAttribute(Attribute::None
)
252 ? CPUAttr
.getValueAsString()
253 : (StringRef
)TargetCPU
;
254 StringRef FS
= !FSAttr
.hasAttribute(Attribute::None
)
255 ? FSAttr
.getValueAsString()
256 : (StringRef
)TargetFS
;
258 SmallString
<512> Key
;
259 Key
.reserve(CPU
.size() + FS
.size());
263 // FIXME: This is related to the code below to reset the target options,
264 // we need to know whether or not the soft float flag is set on the
265 // function before we can generate a subtarget. We also need to use
266 // it as a key for the subtarget since that can be the only difference
267 // between two functions.
269 F
.getFnAttribute("use-soft-float").getValueAsString() == "true";
270 // If the soft float attribute is set on the function turn on the soft float
271 // subtarget feature.
273 Key
+= FS
.empty() ? "+soft-float" : ",+soft-float";
275 // Keep track of the key width after all features are added so we can extract
276 // the feature string out later.
277 unsigned CPUFSWidth
= Key
.size();
279 // Extract prefer-vector-width attribute.
280 unsigned PreferVectorWidthOverride
= 0;
281 if (F
.hasFnAttribute("prefer-vector-width")) {
282 StringRef Val
= F
.getFnAttribute("prefer-vector-width").getValueAsString();
284 if (!Val
.getAsInteger(0, Width
)) {
285 Key
+= ",prefer-vector-width=";
287 PreferVectorWidthOverride
= Width
;
291 // Extract min-legal-vector-width attribute.
292 unsigned RequiredVectorWidth
= UINT32_MAX
;
293 if (F
.hasFnAttribute("min-legal-vector-width")) {
295 F
.getFnAttribute("min-legal-vector-width").getValueAsString();
297 if (!Val
.getAsInteger(0, Width
)) {
298 Key
+= ",min-legal-vector-width=";
300 RequiredVectorWidth
= Width
;
304 // Extracted here so that we make sure there is backing for the StringRef. If
305 // we assigned earlier, its possible the SmallString reallocated leaving a
306 // dangling StringRef.
307 FS
= Key
.slice(CPU
.size(), CPUFSWidth
);
309 auto &I
= SubtargetMap
[Key
];
311 // This needs to be done before we create a new subtarget since any
312 // creation will depend on the TM and the code generation flags on the
313 // function that reside in TargetOptions.
314 resetTargetOptions(F
);
315 I
= std::make_unique
<X86Subtarget
>(TargetTriple
, CPU
, FS
, *this,
316 Options
.StackAlignmentOverride
,
317 PreferVectorWidthOverride
,
318 RequiredVectorWidth
);
323 //===----------------------------------------------------------------------===//
324 // Command line options for x86
325 //===----------------------------------------------------------------------===//
327 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden
,
328 cl::desc("Minimize AVX to SSE transition penalty"),
331 //===----------------------------------------------------------------------===//
333 //===----------------------------------------------------------------------===//
336 X86TargetMachine::getTargetTransformInfo(const Function
&F
) {
337 return TargetTransformInfo(X86TTIImpl(this, F
));
340 //===----------------------------------------------------------------------===//
341 // Pass Pipeline Configuration
342 //===----------------------------------------------------------------------===//
346 /// X86 Code Generator Pass Configuration Options.
347 class X86PassConfig
: public TargetPassConfig
{
349 X86PassConfig(X86TargetMachine
&TM
, PassManagerBase
&PM
)
350 : TargetPassConfig(TM
, PM
) {}
352 X86TargetMachine
&getX86TargetMachine() const {
353 return getTM
<X86TargetMachine
>();
357 createMachineScheduler(MachineSchedContext
*C
) const override
{
358 ScheduleDAGMILive
*DAG
= createGenericSchedLive(C
);
359 DAG
->addMutation(createX86MacroFusionDAGMutation());
364 createPostMachineScheduler(MachineSchedContext
*C
) const override
{
365 ScheduleDAGMI
*DAG
= createGenericSchedPostRA(C
);
366 DAG
->addMutation(createX86MacroFusionDAGMutation());
370 void addIRPasses() override
;
371 bool addInstSelector() override
;
372 bool addIRTranslator() override
;
373 bool addLegalizeMachineIR() override
;
374 bool addRegBankSelect() override
;
375 bool addGlobalInstructionSelect() override
;
376 bool addILPOpts() override
;
377 bool addPreISel() override
;
378 void addMachineSSAOptimization() override
;
379 void addPreRegAlloc() override
;
380 void addPostRegAlloc() override
;
381 void addPreEmitPass() override
;
382 void addPreEmitPass2() override
;
383 void addPreSched2() override
;
385 std::unique_ptr
<CSEConfigBase
> getCSEConfig() const override
;
388 class X86ExecutionDomainFix
: public ExecutionDomainFix
{
391 X86ExecutionDomainFix() : ExecutionDomainFix(ID
, X86::VR128XRegClass
) {}
392 StringRef
getPassName() const override
{
393 return "X86 Execution Dependency Fix";
396 char X86ExecutionDomainFix::ID
;
398 } // end anonymous namespace
400 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix
, "x86-execution-domain-fix",
401 "X86 Execution Domain Fix", false, false)
402 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis
)
403 INITIALIZE_PASS_END(X86ExecutionDomainFix
, "x86-execution-domain-fix",
404 "X86 Execution Domain Fix", false, false)
406 TargetPassConfig
*X86TargetMachine::createPassConfig(PassManagerBase
&PM
) {
407 return new X86PassConfig(*this, PM
);
410 void X86PassConfig::addIRPasses() {
411 addPass(createAtomicExpandPass());
413 TargetPassConfig::addIRPasses();
415 if (TM
->getOptLevel() != CodeGenOpt::None
)
416 addPass(createInterleavedAccessPass());
418 // Add passes that handle indirect branch removal and insertion of a retpoline
419 // thunk. These will be a no-op unless a function subtarget has the retpoline
421 addPass(createIndirectBrExpandPass());
424 bool X86PassConfig::addInstSelector() {
425 // Install an instruction selector.
426 addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
428 // For ELF, cleanup any local-dynamic TLS accesses.
429 if (TM
->getTargetTriple().isOSBinFormatELF() &&
430 getOptLevel() != CodeGenOpt::None
)
431 addPass(createCleanupLocalDynamicTLSPass());
433 addPass(createX86GlobalBaseRegPass());
437 bool X86PassConfig::addIRTranslator() {
438 addPass(new IRTranslator());
442 bool X86PassConfig::addLegalizeMachineIR() {
443 addPass(new Legalizer());
447 bool X86PassConfig::addRegBankSelect() {
448 addPass(new RegBankSelect());
452 bool X86PassConfig::addGlobalInstructionSelect() {
453 addPass(new InstructionSelect());
457 bool X86PassConfig::addILPOpts() {
458 if (EnableCondBrFoldingPass
)
459 addPass(createX86CondBrFolding());
460 addPass(&EarlyIfConverterID
);
461 if (EnableMachineCombinerPass
)
462 addPass(&MachineCombinerID
);
463 addPass(createX86CmovConverterPass());
467 bool X86PassConfig::addPreISel() {
468 // Only add this pass for 32-bit x86 Windows.
469 const Triple
&TT
= TM
->getTargetTriple();
470 if (TT
.isOSWindows() && TT
.getArch() == Triple::x86
)
471 addPass(createX86WinEHStatePass());
475 void X86PassConfig::addPreRegAlloc() {
476 if (getOptLevel() != CodeGenOpt::None
) {
477 addPass(&LiveRangeShrinkID
);
478 addPass(createX86FixupSetCC());
479 addPass(createX86OptimizeLEAs());
480 addPass(createX86CallFrameOptimization());
481 addPass(createX86AvoidStoreForwardingBlocks());
484 addPass(createX86SpeculativeLoadHardeningPass());
485 addPass(createX86FlagsCopyLoweringPass());
486 addPass(createX86WinAllocaExpander());
488 void X86PassConfig::addMachineSSAOptimization() {
489 addPass(createX86DomainReassignmentPass());
490 TargetPassConfig::addMachineSSAOptimization();
493 void X86PassConfig::addPostRegAlloc() {
494 addPass(createX86FloatingPointStackifierPass());
497 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
499 void X86PassConfig::addPreEmitPass() {
500 if (getOptLevel() != CodeGenOpt::None
) {
501 addPass(new X86ExecutionDomainFix());
502 addPass(createBreakFalseDeps());
505 addPass(createX86IndirectBranchTrackingPass());
508 addPass(createX86IssueVZeroUpperPass());
510 if (getOptLevel() != CodeGenOpt::None
) {
511 addPass(createX86FixupBWInsts());
512 addPass(createX86PadShortFunctions());
513 addPass(createX86FixupLEAs());
514 addPass(createX86EvexToVexInsts());
516 addPass(createX86DiscriminateMemOpsPass());
517 addPass(createX86InsertPrefetchPass());
520 void X86PassConfig::addPreEmitPass2() {
521 addPass(createX86RetpolineThunksPass());
522 // Verify basic block incoming and outgoing cfa offset and register values and
523 // correct CFA calculation rule where needed by inserting appropriate CFI
525 const Triple
&TT
= TM
->getTargetTriple();
526 const MCAsmInfo
*MAI
= TM
->getMCAsmInfo();
527 if (!TT
.isOSDarwin() &&
528 (!TT
.isOSWindows() ||
529 MAI
->getExceptionHandlingType() == ExceptionHandling::DwarfCFI
))
530 addPass(createCFIInstrInserter());
533 std::unique_ptr
<CSEConfigBase
> X86PassConfig::getCSEConfig() const {
534 return getStandardCSEConfigForOpt(TM
->getOptLevel());