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