xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86TargetMachine.cpp (revision 9dba64be9536c28e4800e06512b7f29b43ade345)
1 //===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
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 defines the X86 specific subclass of TargetMachine.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86TargetMachine.h"
14 #include "MCTargetDesc/X86MCTargetDesc.h"
15 #include "TargetInfo/X86TargetInfo.h"
16 #include "X86.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"
49 #include <memory>
50 #include <string>
51 
52 using namespace llvm;
53 
54 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
55                                cl::desc("Enable the machine combiner pass"),
56                                cl::init(true), cl::Hidden);
57 
58 static cl::opt<bool> EnableCondBrFoldingPass("x86-condbr-folding",
59                                cl::desc("Enable the conditional branch "
60                                         "folding pass"),
61                                cl::init(false), cl::Hidden);
62 
63 extern "C" void LLVMInitializeX86Target() {
64   // Register the target.
65   RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
66   RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
67 
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);
85 }
86 
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>();
92   }
93 
94   if (TT.isOSFreeBSD())
95     return std::make_unique<X86FreeBSDTargetObjectFile>();
96   if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU())
97     return std::make_unique<X86LinuxNaClTargetObjectFile>();
98   if (TT.isOSSolaris())
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");
107 }
108 
109 static std::string computeDataLayout(const Triple &TT) {
110   // X86 is little endian
111   std::string Ret = "e";
112 
113   Ret += DataLayout::getManglingComponent(TT);
114   // X86 and x32 have 32 bit pointers.
115   if ((TT.isArch64Bit() &&
116        (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
117       !TT.isArch64Bit())
118     Ret += "-p:32:32";
119 
120   // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers.
121   Ret += "-p270:32:32-p271:32:32-p272:64:64";
122 
123   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
124   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
125     Ret += "-i64:64";
126   else if (TT.isOSIAMCU())
127     Ret += "-i64:32-f64:32";
128   else
129     Ret += "-f64:32:64";
130 
131   // Some ABIs align long double to 128 bits, others to 32.
132   if (TT.isOSNaCl() || TT.isOSIAMCU())
133     ; // No f80
134   else if (TT.isArch64Bit() || TT.isOSDarwin())
135     Ret += "-f80:128";
136   else
137     Ret += "-f80:32";
138 
139   if (TT.isOSIAMCU())
140     Ret += "-f128:32";
141 
142   // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
143   if (TT.isArch64Bit())
144     Ret += "-n8:16:32:64";
145   else
146     Ret += "-n8:16:32";
147 
148   // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
149   if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
150     Ret += "-a:0:32-S32";
151   else
152     Ret += "-S128";
153 
154   return Ret;
155 }
156 
157 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
158                                            bool JIT,
159                                            Optional<Reloc::Model> RM) {
160   bool is64Bit = TT.getArch() == Triple::x86_64;
161   if (!RM.hasValue()) {
162     // JIT codegen should use static relocations by default, since it's
163     // typically executed in process and not relocatable.
164     if (JIT)
165       return Reloc::Static;
166 
167     // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
168     // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
169     // use static relocation model by default.
170     if (TT.isOSDarwin()) {
171       if (is64Bit)
172         return Reloc::PIC_;
173       return Reloc::DynamicNoPIC;
174     }
175     if (TT.isOSWindows() && is64Bit)
176       return Reloc::PIC_;
177     return Reloc::Static;
178   }
179 
180   // ELF and X86-64 don't have a distinct DynamicNoPIC model.  DynamicNoPIC
181   // is defined as a model for code which may be used in static or dynamic
182   // executables but not necessarily a shared library. On X86-32 we just
183   // compile in -static mode, in x86-64 we use PIC.
184   if (*RM == Reloc::DynamicNoPIC) {
185     if (is64Bit)
186       return Reloc::PIC_;
187     if (!TT.isOSDarwin())
188       return Reloc::Static;
189   }
190 
191   // If we are on Darwin, disallow static relocation model in X86-64 mode, since
192   // the Mach-O file format doesn't support it.
193   if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
194     return Reloc::PIC_;
195 
196   return *RM;
197 }
198 
199 static CodeModel::Model getEffectiveX86CodeModel(Optional<CodeModel::Model> CM,
200                                                  bool JIT, bool Is64Bit) {
201   if (CM) {
202     if (*CM == CodeModel::Tiny)
203       report_fatal_error("Target does not support the tiny CodeModel", false);
204     return *CM;
205   }
206   if (JIT)
207     return Is64Bit ? CodeModel::Large : CodeModel::Small;
208   return CodeModel::Small;
209 }
210 
211 /// Create an X86 target.
212 ///
213 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
214                                    StringRef CPU, StringRef FS,
215                                    const TargetOptions &Options,
216                                    Optional<Reloc::Model> RM,
217                                    Optional<CodeModel::Model> CM,
218                                    CodeGenOpt::Level OL, bool JIT)
219     : LLVMTargetMachine(
220           T, computeDataLayout(TT), TT, CPU, FS, Options,
221           getEffectiveRelocModel(TT, JIT, RM),
222           getEffectiveX86CodeModel(CM, JIT, TT.getArch() == Triple::x86_64),
223           OL),
224       TLOF(createTLOF(getTargetTriple())) {
225   // On PS4, the "return address" of a 'noreturn' call must still be within
226   // the calling function, and TrapUnreachable is an easy way to get that.
227   if (TT.isPS4() || TT.isOSBinFormatMachO()) {
228     this->Options.TrapUnreachable = true;
229     this->Options.NoTrapAfterNoreturn = TT.isOSBinFormatMachO();
230   }
231 
232   // Outlining is available for x86-64.
233   if (TT.getArch() == Triple::x86_64)
234     setMachineOutliner(true);
235 
236   initAsmInfo();
237 }
238 
239 X86TargetMachine::~X86TargetMachine() = default;
240 
241 const X86Subtarget *
242 X86TargetMachine::getSubtargetImpl(const Function &F) const {
243   Attribute CPUAttr = F.getFnAttribute("target-cpu");
244   Attribute FSAttr = F.getFnAttribute("target-features");
245 
246   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
247                       ? CPUAttr.getValueAsString()
248                       : (StringRef)TargetCPU;
249   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
250                      ? FSAttr.getValueAsString()
251                      : (StringRef)TargetFS;
252 
253   SmallString<512> Key;
254   Key.reserve(CPU.size() + FS.size());
255   Key += CPU;
256   Key += FS;
257 
258   // FIXME: This is related to the code below to reset the target options,
259   // we need to know whether or not the soft float flag is set on the
260   // function before we can generate a subtarget. We also need to use
261   // it as a key for the subtarget since that can be the only difference
262   // between two functions.
263   bool SoftFloat =
264       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
265   // If the soft float attribute is set on the function turn on the soft float
266   // subtarget feature.
267   if (SoftFloat)
268     Key += FS.empty() ? "+soft-float" : ",+soft-float";
269 
270   // Keep track of the key width after all features are added so we can extract
271   // the feature string out later.
272   unsigned CPUFSWidth = Key.size();
273 
274   // Extract prefer-vector-width attribute.
275   unsigned PreferVectorWidthOverride = 0;
276   if (F.hasFnAttribute("prefer-vector-width")) {
277     StringRef Val = F.getFnAttribute("prefer-vector-width").getValueAsString();
278     unsigned Width;
279     if (!Val.getAsInteger(0, Width)) {
280       Key += ",prefer-vector-width=";
281       Key += Val;
282       PreferVectorWidthOverride = Width;
283     }
284   }
285 
286   // Extract min-legal-vector-width attribute.
287   unsigned RequiredVectorWidth = UINT32_MAX;
288   if (F.hasFnAttribute("min-legal-vector-width")) {
289     StringRef Val =
290         F.getFnAttribute("min-legal-vector-width").getValueAsString();
291     unsigned Width;
292     if (!Val.getAsInteger(0, Width)) {
293       Key += ",min-legal-vector-width=";
294       Key += Val;
295       RequiredVectorWidth = Width;
296     }
297   }
298 
299   // Extracted here so that we make sure there is backing for the StringRef. If
300   // we assigned earlier, its possible the SmallString reallocated leaving a
301   // dangling StringRef.
302   FS = Key.slice(CPU.size(), CPUFSWidth);
303 
304   auto &I = SubtargetMap[Key];
305   if (!I) {
306     // This needs to be done before we create a new subtarget since any
307     // creation will depend on the TM and the code generation flags on the
308     // function that reside in TargetOptions.
309     resetTargetOptions(F);
310     I = std::make_unique<X86Subtarget>(
311         TargetTriple, CPU, FS, *this,
312         MaybeAlign(Options.StackAlignmentOverride), PreferVectorWidthOverride,
313         RequiredVectorWidth);
314   }
315   return I.get();
316 }
317 
318 //===----------------------------------------------------------------------===//
319 // Command line options for x86
320 //===----------------------------------------------------------------------===//
321 static cl::opt<bool>
322 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
323   cl::desc("Minimize AVX to SSE transition penalty"),
324   cl::init(true));
325 
326 //===----------------------------------------------------------------------===//
327 // X86 TTI query.
328 //===----------------------------------------------------------------------===//
329 
330 TargetTransformInfo
331 X86TargetMachine::getTargetTransformInfo(const Function &F) {
332   return TargetTransformInfo(X86TTIImpl(this, F));
333 }
334 
335 //===----------------------------------------------------------------------===//
336 // Pass Pipeline Configuration
337 //===----------------------------------------------------------------------===//
338 
339 namespace {
340 
341 /// X86 Code Generator Pass Configuration Options.
342 class X86PassConfig : public TargetPassConfig {
343 public:
344   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
345     : TargetPassConfig(TM, PM) {}
346 
347   X86TargetMachine &getX86TargetMachine() const {
348     return getTM<X86TargetMachine>();
349   }
350 
351   ScheduleDAGInstrs *
352   createMachineScheduler(MachineSchedContext *C) const override {
353     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
354     DAG->addMutation(createX86MacroFusionDAGMutation());
355     return DAG;
356   }
357 
358   ScheduleDAGInstrs *
359   createPostMachineScheduler(MachineSchedContext *C) const override {
360     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
361     DAG->addMutation(createX86MacroFusionDAGMutation());
362     return DAG;
363   }
364 
365   void addIRPasses() override;
366   bool addInstSelector() override;
367   bool addIRTranslator() override;
368   bool addLegalizeMachineIR() override;
369   bool addRegBankSelect() override;
370   bool addGlobalInstructionSelect() override;
371   bool addILPOpts() override;
372   bool addPreISel() override;
373   void addMachineSSAOptimization() override;
374   void addPreRegAlloc() override;
375   void addPostRegAlloc() override;
376   void addPreEmitPass() override;
377   void addPreEmitPass2() override;
378   void addPreSched2() override;
379 
380   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
381 };
382 
383 class X86ExecutionDomainFix : public ExecutionDomainFix {
384 public:
385   static char ID;
386   X86ExecutionDomainFix() : ExecutionDomainFix(ID, X86::VR128XRegClass) {}
387   StringRef getPassName() const override {
388     return "X86 Execution Dependency Fix";
389   }
390 };
391 char X86ExecutionDomainFix::ID;
392 
393 } // end anonymous namespace
394 
395 INITIALIZE_PASS_BEGIN(X86ExecutionDomainFix, "x86-execution-domain-fix",
396   "X86 Execution Domain Fix", false, false)
397 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
398 INITIALIZE_PASS_END(X86ExecutionDomainFix, "x86-execution-domain-fix",
399   "X86 Execution Domain Fix", false, false)
400 
401 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
402   return new X86PassConfig(*this, PM);
403 }
404 
405 void X86PassConfig::addIRPasses() {
406   addPass(createAtomicExpandPass());
407 
408   TargetPassConfig::addIRPasses();
409 
410   if (TM->getOptLevel() != CodeGenOpt::None)
411     addPass(createInterleavedAccessPass());
412 
413   // Add passes that handle indirect branch removal and insertion of a retpoline
414   // thunk. These will be a no-op unless a function subtarget has the retpoline
415   // feature enabled.
416   addPass(createIndirectBrExpandPass());
417 }
418 
419 bool X86PassConfig::addInstSelector() {
420   // Install an instruction selector.
421   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
422 
423   // For ELF, cleanup any local-dynamic TLS accesses.
424   if (TM->getTargetTriple().isOSBinFormatELF() &&
425       getOptLevel() != CodeGenOpt::None)
426     addPass(createCleanupLocalDynamicTLSPass());
427 
428   addPass(createX86GlobalBaseRegPass());
429   return false;
430 }
431 
432 bool X86PassConfig::addIRTranslator() {
433   addPass(new IRTranslator());
434   return false;
435 }
436 
437 bool X86PassConfig::addLegalizeMachineIR() {
438   addPass(new Legalizer());
439   return false;
440 }
441 
442 bool X86PassConfig::addRegBankSelect() {
443   addPass(new RegBankSelect());
444   return false;
445 }
446 
447 bool X86PassConfig::addGlobalInstructionSelect() {
448   addPass(new InstructionSelect());
449   return false;
450 }
451 
452 bool X86PassConfig::addILPOpts() {
453   if (EnableCondBrFoldingPass)
454     addPass(createX86CondBrFolding());
455   addPass(&EarlyIfConverterID);
456   if (EnableMachineCombinerPass)
457     addPass(&MachineCombinerID);
458   addPass(createX86CmovConverterPass());
459   return true;
460 }
461 
462 bool X86PassConfig::addPreISel() {
463   // Only add this pass for 32-bit x86 Windows.
464   const Triple &TT = TM->getTargetTriple();
465   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
466     addPass(createX86WinEHStatePass());
467   return true;
468 }
469 
470 void X86PassConfig::addPreRegAlloc() {
471   if (getOptLevel() != CodeGenOpt::None) {
472     addPass(&LiveRangeShrinkID);
473     addPass(createX86FixupSetCC());
474     addPass(createX86OptimizeLEAs());
475     addPass(createX86CallFrameOptimization());
476     addPass(createX86AvoidStoreForwardingBlocks());
477   }
478 
479   addPass(createX86SpeculativeLoadHardeningPass());
480   addPass(createX86FlagsCopyLoweringPass());
481   addPass(createX86WinAllocaExpander());
482 }
483 void X86PassConfig::addMachineSSAOptimization() {
484   addPass(createX86DomainReassignmentPass());
485   TargetPassConfig::addMachineSSAOptimization();
486 }
487 
488 void X86PassConfig::addPostRegAlloc() {
489   addPass(createX86FloatingPointStackifierPass());
490 }
491 
492 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
493 
494 void X86PassConfig::addPreEmitPass() {
495   if (getOptLevel() != CodeGenOpt::None) {
496     addPass(new X86ExecutionDomainFix());
497     addPass(createBreakFalseDeps());
498   }
499 
500   addPass(createX86IndirectBranchTrackingPass());
501 
502   if (UseVZeroUpper)
503     addPass(createX86IssueVZeroUpperPass());
504 
505   if (getOptLevel() != CodeGenOpt::None) {
506     addPass(createX86FixupBWInsts());
507     addPass(createX86PadShortFunctions());
508     addPass(createX86FixupLEAs());
509     addPass(createX86EvexToVexInsts());
510   }
511   addPass(createX86DiscriminateMemOpsPass());
512   addPass(createX86InsertPrefetchPass());
513 }
514 
515 void X86PassConfig::addPreEmitPass2() {
516   const Triple &TT = TM->getTargetTriple();
517   const MCAsmInfo *MAI = TM->getMCAsmInfo();
518 
519   addPass(createX86RetpolineThunksPass());
520 
521   // Insert extra int3 instructions after trailing call instructions to avoid
522   // issues in the unwinder.
523   if (TT.isOSWindows() && TT.getArch() == Triple::x86_64)
524     addPass(createX86AvoidTrailingCallPass());
525 
526   // Verify basic block incoming and outgoing cfa offset and register values and
527   // correct CFA calculation rule where needed by inserting appropriate CFI
528   // instructions.
529   if (!TT.isOSDarwin() &&
530       (!TT.isOSWindows() ||
531        MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI))
532     addPass(createCFIInstrInserter());
533 }
534 
535 std::unique_ptr<CSEConfigBase> X86PassConfig::getCSEConfig() const {
536   return getStandardCSEConfigForOpt(TM->getOptLevel());
537 }
538