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