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 "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 "X86TargetMachine.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/ExecutionDepsFix.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 initializeX86CmovConverterPassPass(PassRegistry &);
62 void initializeX86ExecutionDepsFixPass(PassRegistry &);
63 
64 } // end namespace llvm
65 
66 extern "C" void LLVMInitializeX86Target() {
67   // Register the target.
68   RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
69   RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
70 
71   PassRegistry &PR = *PassRegistry::getPassRegistry();
72   initializeGlobalISel(PR);
73   initializeWinEHStatePassPass(PR);
74   initializeFixupBWInstPassPass(PR);
75   initializeEvexToVexInstPassPass(PR);
76   initializeFixupLEAPassPass(PR);
77   initializeX86CmovConverterPassPass(PR);
78   initializeX86ExecutionDepsFixPass(PR);
79 }
80 
81 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
82   if (TT.isOSBinFormatMachO()) {
83     if (TT.getArch() == Triple::x86_64)
84       return llvm::make_unique<X86_64MachoTargetObjectFile>();
85     return llvm::make_unique<TargetLoweringObjectFileMachO>();
86   }
87 
88   if (TT.isOSFreeBSD())
89     return llvm::make_unique<X86FreeBSDTargetObjectFile>();
90   if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU())
91     return llvm::make_unique<X86LinuxNaClTargetObjectFile>();
92   if (TT.isOSSolaris())
93     return llvm::make_unique<X86SolarisTargetObjectFile>();
94   if (TT.isOSFuchsia())
95     return llvm::make_unique<X86FuchsiaTargetObjectFile>();
96   if (TT.isOSBinFormatELF())
97     return llvm::make_unique<X86ELFTargetObjectFile>();
98   if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
99     return llvm::make_unique<X86WindowsTargetObjectFile>();
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                                            Optional<Reloc::Model> RM) {
152   bool is64Bit = TT.getArch() == Triple::x86_64;
153   if (!RM.hasValue()) {
154     // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
155     // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
156     // use static relocation model by default.
157     if (TT.isOSDarwin()) {
158       if (is64Bit)
159         return Reloc::PIC_;
160       return Reloc::DynamicNoPIC;
161     }
162     if (TT.isOSWindows() && is64Bit)
163       return Reloc::PIC_;
164     return Reloc::Static;
165   }
166 
167   // ELF and X86-64 don't have a distinct DynamicNoPIC model.  DynamicNoPIC
168   // is defined as a model for code which may be used in static or dynamic
169   // executables but not necessarily a shared library. On X86-32 we just
170   // compile in -static mode, in x86-64 we use PIC.
171   if (*RM == Reloc::DynamicNoPIC) {
172     if (is64Bit)
173       return Reloc::PIC_;
174     if (!TT.isOSDarwin())
175       return Reloc::Static;
176   }
177 
178   // If we are on Darwin, disallow static relocation model in X86-64 mode, since
179   // the Mach-O file format doesn't support it.
180   if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
181     return Reloc::PIC_;
182 
183   return *RM;
184 }
185 
186 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM,
187                                               bool JIT, bool Is64Bit) {
188   if (CM)
189     return *CM;
190   if (JIT)
191     return Is64Bit ? CodeModel::Large : CodeModel::Small;
192   return CodeModel::Small;
193 }
194 
195 /// Create an X86 target.
196 ///
197 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
198                                    StringRef CPU, StringRef FS,
199                                    const TargetOptions &Options,
200                                    Optional<Reloc::Model> RM,
201                                    Optional<CodeModel::Model> CM,
202                                    CodeGenOpt::Level OL, bool JIT)
203     : LLVMTargetMachine(
204           T, computeDataLayout(TT), TT, CPU, FS, Options,
205           getEffectiveRelocModel(TT, RM),
206           getEffectiveCodeModel(CM, JIT, TT.getArch() == Triple::x86_64), OL),
207       TLOF(createTLOF(getTargetTriple())) {
208   // Windows stack unwinder gets confused when execution flow "falls through"
209   // after a call to 'noreturn' function.
210   // To prevent that, we emit a trap for 'unreachable' IR instructions.
211   // (which on X86, happens to be the 'ud2' instruction)
212   // On PS4, the "return address" of a 'noreturn' call must still be within
213   // the calling function, and TrapUnreachable is an easy way to get that.
214   // The check here for 64-bit windows is a bit icky, but as we're unlikely
215   // to ever want to mix 32 and 64-bit windows code in a single module
216   // this should be fine.
217   if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4())
218     this->Options.TrapUnreachable = true;
219 
220   initAsmInfo();
221 }
222 
223 X86TargetMachine::~X86TargetMachine() = default;
224 
225 const X86Subtarget *
226 X86TargetMachine::getSubtargetImpl(const Function &F) const {
227   Attribute CPUAttr = F.getFnAttribute("target-cpu");
228   Attribute FSAttr = F.getFnAttribute("target-features");
229 
230   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
231                       ? CPUAttr.getValueAsString()
232                       : (StringRef)TargetCPU;
233   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
234                      ? FSAttr.getValueAsString()
235                      : (StringRef)TargetFS;
236 
237   SmallString<512> Key;
238   Key.reserve(CPU.size() + FS.size());
239   Key += CPU;
240   Key += FS;
241 
242   // FIXME: This is related to the code below to reset the target options,
243   // we need to know whether or not the soft float flag is set on the
244   // function before we can generate a subtarget. We also need to use
245   // it as a key for the subtarget since that can be the only difference
246   // between two functions.
247   bool SoftFloat =
248       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
249   // If the soft float attribute is set on the function turn on the soft float
250   // subtarget feature.
251   if (SoftFloat)
252     Key += FS.empty() ? "+soft-float" : ",+soft-float";
253 
254   FS = Key.substr(CPU.size());
255 
256   auto &I = SubtargetMap[Key];
257   if (!I) {
258     // This needs to be done before we create a new subtarget since any
259     // creation will depend on the TM and the code generation flags on the
260     // function that reside in TargetOptions.
261     resetTargetOptions(F);
262     I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
263                                         Options.StackAlignmentOverride);
264   }
265   return I.get();
266 }
267 
268 //===----------------------------------------------------------------------===//
269 // Command line options for x86
270 //===----------------------------------------------------------------------===//
271 static cl::opt<bool>
272 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
273   cl::desc("Minimize AVX to SSE transition penalty"),
274   cl::init(true));
275 
276 //===----------------------------------------------------------------------===//
277 // X86 TTI query.
278 //===----------------------------------------------------------------------===//
279 
280 TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() {
281   return TargetIRAnalysis([this](const Function &F) {
282     return TargetTransformInfo(X86TTIImpl(this, F));
283   });
284 }
285 
286 //===----------------------------------------------------------------------===//
287 // Pass Pipeline Configuration
288 //===----------------------------------------------------------------------===//
289 
290 namespace {
291 
292 /// X86 Code Generator Pass Configuration Options.
293 class X86PassConfig : public TargetPassConfig {
294 public:
295   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
296     : TargetPassConfig(TM, PM) {}
297 
298   X86TargetMachine &getX86TargetMachine() const {
299     return getTM<X86TargetMachine>();
300   }
301 
302   ScheduleDAGInstrs *
303   createMachineScheduler(MachineSchedContext *C) const override {
304     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
305     DAG->addMutation(createX86MacroFusionDAGMutation());
306     return DAG;
307   }
308 
309   void addIRPasses() override;
310   bool addInstSelector() override;
311   bool addIRTranslator() override;
312   bool addLegalizeMachineIR() override;
313   bool addRegBankSelect() override;
314   bool addGlobalInstructionSelect() override;
315   bool addILPOpts() override;
316   bool addPreISel() override;
317   void addPreRegAlloc() override;
318   void addPostRegAlloc() override;
319   void addPreEmitPass() override;
320   void addPreSched2() override;
321 };
322 
323 class X86ExecutionDepsFix : public ExecutionDepsFix {
324 public:
325   static char ID;
326   X86ExecutionDepsFix() : ExecutionDepsFix(ID, X86::VR128XRegClass) {}
327   StringRef getPassName() const override {
328     return "X86 Execution Dependency Fix";
329   }
330 };
331 char X86ExecutionDepsFix::ID;
332 
333 } // end anonymous namespace
334 
335 INITIALIZE_PASS(X86ExecutionDepsFix, "x86-execution-deps-fix",
336                 "X86 Execution Dependency Fix", false, false)
337 
338 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
339   return new X86PassConfig(*this, PM);
340 }
341 
342 void X86PassConfig::addIRPasses() {
343   addPass(createAtomicExpandPass());
344 
345   TargetPassConfig::addIRPasses();
346 
347   if (TM->getOptLevel() != CodeGenOpt::None)
348     addPass(createInterleavedAccessPass());
349 }
350 
351 bool X86PassConfig::addInstSelector() {
352   // Install an instruction selector.
353   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
354 
355   // For ELF, cleanup any local-dynamic TLS accesses.
356   if (TM->getTargetTriple().isOSBinFormatELF() &&
357       getOptLevel() != CodeGenOpt::None)
358     addPass(createCleanupLocalDynamicTLSPass());
359 
360   addPass(createX86GlobalBaseRegPass());
361   return false;
362 }
363 
364 bool X86PassConfig::addIRTranslator() {
365   addPass(new IRTranslator());
366   return false;
367 }
368 
369 bool X86PassConfig::addLegalizeMachineIR() {
370   addPass(new Legalizer());
371   return false;
372 }
373 
374 bool X86PassConfig::addRegBankSelect() {
375   addPass(new RegBankSelect());
376   return false;
377 }
378 
379 bool X86PassConfig::addGlobalInstructionSelect() {
380   addPass(new InstructionSelect());
381   return false;
382 }
383 
384 bool X86PassConfig::addILPOpts() {
385   addPass(&EarlyIfConverterID);
386   if (EnableMachineCombinerPass)
387     addPass(&MachineCombinerID);
388   addPass(createX86CmovConverterPass());
389   return true;
390 }
391 
392 bool X86PassConfig::addPreISel() {
393   // Only add this pass for 32-bit x86 Windows.
394   const Triple &TT = TM->getTargetTriple();
395   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
396     addPass(createX86WinEHStatePass());
397   return true;
398 }
399 
400 void X86PassConfig::addPreRegAlloc() {
401   if (getOptLevel() != CodeGenOpt::None) {
402     addPass(&LiveRangeShrinkID);
403     addPass(createX86FixupSetCC());
404     addPass(createX86OptimizeLEAs());
405     addPass(createX86CallFrameOptimization());
406   }
407 
408   addPass(createX86WinAllocaExpander());
409 }
410 
411 void X86PassConfig::addPostRegAlloc() {
412   addPass(createX86FloatingPointStackifierPass());
413 }
414 
415 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
416 
417 void X86PassConfig::addPreEmitPass() {
418   if (getOptLevel() != CodeGenOpt::None)
419     addPass(new X86ExecutionDepsFix());
420 
421   if (UseVZeroUpper)
422     addPass(createX86IssueVZeroUpperPass());
423 
424   if (getOptLevel() != CodeGenOpt::None) {
425     addPass(createX86FixupBWInsts());
426     addPass(createX86PadShortFunctions());
427     addPass(createX86FixupLEAs());
428     addPass(createX86EvexToVexInsts());
429   }
430 }
431