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