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