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 "X86.h"
16 #include "X86CallLowering.h"
17 #include "X86TargetObjectFile.h"
18 #include "X86TargetTransformInfo.h"
19 #include "llvm/CodeGen/GlobalISel/GISelAccessor.h"
20 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
21 #include "llvm/CodeGen/MachineScheduler.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/LegacyPassManager.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FormattedStream.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Target/TargetOptions.h"
30 using namespace llvm;
31 
32 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
33                                cl::desc("Enable the machine combiner pass"),
34                                cl::init(true), cl::Hidden);
35 
36 namespace llvm {
37 void initializeWinEHStatePassPass(PassRegistry &);
38 }
39 
40 extern "C" void LLVMInitializeX86Target() {
41   // Register the target.
42   RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
43   RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
44 
45   PassRegistry &PR = *PassRegistry::getPassRegistry();
46   initializeGlobalISel(PR);
47   initializeWinEHStatePassPass(PR);
48   initializeFixupBWInstPassPass(PR);
49 }
50 
51 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
52   if (TT.isOSBinFormatMachO()) {
53     if (TT.getArch() == Triple::x86_64)
54       return make_unique<X86_64MachoTargetObjectFile>();
55     return make_unique<TargetLoweringObjectFileMachO>();
56   }
57 
58   if (TT.isOSFreeBSD())
59     return make_unique<X86FreeBSDTargetObjectFile>();
60   if (TT.isOSLinux() || TT.isOSNaCl())
61     return make_unique<X86LinuxNaClTargetObjectFile>();
62   if (TT.isOSFuchsia())
63     return make_unique<X86FuchsiaTargetObjectFile>();
64   if (TT.isOSBinFormatELF())
65     return make_unique<X86ELFTargetObjectFile>();
66   if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
67     return make_unique<X86WindowsTargetObjectFile>();
68   if (TT.isOSBinFormatCOFF())
69     return make_unique<TargetLoweringObjectFileCOFF>();
70   llvm_unreachable("unknown subtarget type");
71 }
72 
73 static std::string computeDataLayout(const Triple &TT) {
74   // X86 is little endian
75   std::string Ret = "e";
76 
77   Ret += DataLayout::getManglingComponent(TT);
78   // X86 and x32 have 32 bit pointers.
79   if ((TT.isArch64Bit() &&
80        (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
81       !TT.isArch64Bit())
82     Ret += "-p:32:32";
83 
84   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
85   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
86     Ret += "-i64:64";
87   else if (TT.isOSIAMCU())
88     Ret += "-i64:32-f64:32";
89   else
90     Ret += "-f64:32:64";
91 
92   // Some ABIs align long double to 128 bits, others to 32.
93   if (TT.isOSNaCl() || TT.isOSIAMCU())
94     ; // No f80
95   else if (TT.isArch64Bit() || TT.isOSDarwin())
96     Ret += "-f80:128";
97   else
98     Ret += "-f80:32";
99 
100   if (TT.isOSIAMCU())
101     Ret += "-f128:32";
102 
103   // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
104   if (TT.isArch64Bit())
105     Ret += "-n8:16:32:64";
106   else
107     Ret += "-n8:16:32";
108 
109   // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
110   if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
111     Ret += "-a:0:32-S32";
112   else
113     Ret += "-S128";
114 
115   return Ret;
116 }
117 
118 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
119                                            Optional<Reloc::Model> RM) {
120   bool is64Bit = TT.getArch() == Triple::x86_64;
121   if (!RM.hasValue()) {
122     // Darwin defaults to PIC in 64 bit mode and dynamic-no-pic in 32 bit mode.
123     // Win64 requires rip-rel addressing, thus we force it to PIC. Otherwise we
124     // use static relocation model by default.
125     if (TT.isOSDarwin()) {
126       if (is64Bit)
127         return Reloc::PIC_;
128       return Reloc::DynamicNoPIC;
129     }
130     if (TT.isOSWindows() && is64Bit)
131       return Reloc::PIC_;
132     return Reloc::Static;
133   }
134 
135   // ELF and X86-64 don't have a distinct DynamicNoPIC model.  DynamicNoPIC
136   // is defined as a model for code which may be used in static or dynamic
137   // executables but not necessarily a shared library. On X86-32 we just
138   // compile in -static mode, in x86-64 we use PIC.
139   if (*RM == Reloc::DynamicNoPIC) {
140     if (is64Bit)
141       return Reloc::PIC_;
142     if (!TT.isOSDarwin())
143       return Reloc::Static;
144   }
145 
146   // If we are on Darwin, disallow static relocation model in X86-64 mode, since
147   // the Mach-O file format doesn't support it.
148   if (*RM == Reloc::Static && TT.isOSDarwin() && is64Bit)
149     return Reloc::PIC_;
150 
151   return *RM;
152 }
153 
154 /// Create an X86 target.
155 ///
156 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
157                                    StringRef CPU, StringRef FS,
158                                    const TargetOptions &Options,
159                                    Optional<Reloc::Model> RM,
160                                    CodeModel::Model CM, CodeGenOpt::Level OL)
161     : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
162                         getEffectiveRelocModel(TT, RM), CM, OL),
163       TLOF(createTLOF(getTargetTriple())) {
164   // Windows stack unwinder gets confused when execution flow "falls through"
165   // after a call to 'noreturn' function.
166   // To prevent that, we emit a trap for 'unreachable' IR instructions.
167   // (which on X86, happens to be the 'ud2' instruction)
168   // On PS4, the "return address" of a 'noreturn' call must still be within
169   // the calling function, and TrapUnreachable is an easy way to get that.
170   // The check here for 64-bit windows is a bit icky, but as we're unlikely
171   // to ever want to mix 32 and 64-bit windows code in a single module
172   // this should be fine.
173   if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4())
174     this->Options.TrapUnreachable = true;
175 
176   initAsmInfo();
177 }
178 
179 X86TargetMachine::~X86TargetMachine() {}
180 
181 #ifdef LLVM_BUILD_GLOBAL_ISEL
182 namespace {
183 struct X86GISelActualAccessor : public GISelAccessor {
184   std::unique_ptr<CallLowering> CL;
185   X86GISelActualAccessor(CallLowering* CL): CL(CL) {}
186   const CallLowering *getCallLowering() const override {
187     return CL.get();
188   }
189   const InstructionSelector *getInstructionSelector() const override {
190     //TODO: Implement
191     return nullptr;
192   }
193   const class LegalizerInfo *getLegalizerInfo() const override {
194     //TODO: Implement
195     return nullptr;
196   }
197   const RegisterBankInfo *getRegBankInfo() const override {
198     //TODO: Implement
199     return nullptr;
200   }
201 };
202 } // End anonymous namespace.
203 #endif
204 const X86Subtarget *
205 X86TargetMachine::getSubtargetImpl(const Function &F) const {
206   Attribute CPUAttr = F.getFnAttribute("target-cpu");
207   Attribute FSAttr = F.getFnAttribute("target-features");
208 
209   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
210                       ? CPUAttr.getValueAsString()
211                       : (StringRef)TargetCPU;
212   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
213                      ? FSAttr.getValueAsString()
214                      : (StringRef)TargetFS;
215 
216   SmallString<512> Key;
217   Key.reserve(CPU.size() + FS.size());
218   Key += CPU;
219   Key += FS;
220 
221   // FIXME: This is related to the code below to reset the target options,
222   // we need to know whether or not the soft float flag is set on the
223   // function before we can generate a subtarget. We also need to use
224   // it as a key for the subtarget since that can be the only difference
225   // between two functions.
226   bool SoftFloat =
227       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
228   // If the soft float attribute is set on the function turn on the soft float
229   // subtarget feature.
230   if (SoftFloat)
231     Key += FS.empty() ? "+soft-float" : ",+soft-float";
232 
233   FS = Key.substr(CPU.size());
234 
235   auto &I = SubtargetMap[Key];
236   if (!I) {
237     // This needs to be done before we create a new subtarget since any
238     // creation will depend on the TM and the code generation flags on the
239     // function that reside in TargetOptions.
240     resetTargetOptions(F);
241     I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
242                                         Options.StackAlignmentOverride);
243 #ifndef LLVM_BUILD_GLOBAL_ISEL
244     GISelAccessor *GISel = new GISelAccessor();
245 #else
246     X86GISelActualAccessor *GISel = new X86GISelActualAccessor(
247         new X86CallLowering(*I->getTargetLowering()));
248 #endif
249     I->setGISelAccessor(*GISel);
250   }
251   return I.get();
252 }
253 
254 //===----------------------------------------------------------------------===//
255 // Command line options for x86
256 //===----------------------------------------------------------------------===//
257 static cl::opt<bool>
258 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
259   cl::desc("Minimize AVX to SSE transition penalty"),
260   cl::init(true));
261 
262 //===----------------------------------------------------------------------===//
263 // X86 TTI query.
264 //===----------------------------------------------------------------------===//
265 
266 TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() {
267   return TargetIRAnalysis([this](const Function &F) {
268     return TargetTransformInfo(X86TTIImpl(this, F));
269   });
270 }
271 
272 
273 //===----------------------------------------------------------------------===//
274 // Pass Pipeline Configuration
275 //===----------------------------------------------------------------------===//
276 
277 namespace {
278 /// X86 Code Generator Pass Configuration Options.
279 class X86PassConfig : public TargetPassConfig {
280 public:
281   X86PassConfig(X86TargetMachine *TM, PassManagerBase &PM)
282     : TargetPassConfig(TM, PM) {}
283 
284   X86TargetMachine &getX86TargetMachine() const {
285     return getTM<X86TargetMachine>();
286   }
287 
288   ScheduleDAGInstrs *
289   createMachineScheduler(MachineSchedContext *C) const override {
290     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
291     DAG->addMutation(createMacroFusionDAGMutation(DAG->TII));
292     return DAG;
293   }
294 
295   void addIRPasses() override;
296   bool addInstSelector() override;
297 #ifdef LLVM_BUILD_GLOBAL_ISEL
298   bool addIRTranslator() override;
299   bool addLegalizeMachineIR() override;
300   bool addRegBankSelect() override;
301   bool addGlobalInstructionSelect() override;
302 #endif
303 bool addILPOpts() override;
304   bool addPreISel() override;
305   void addPreRegAlloc() override;
306   void addPostRegAlloc() override;
307   void addPreEmitPass() override;
308   void addPreSched2() override;
309 };
310 } // namespace
311 
312 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
313   return new X86PassConfig(this, PM);
314 }
315 
316 void X86PassConfig::addIRPasses() {
317   addPass(createAtomicExpandPass(&getX86TargetMachine()));
318 
319   TargetPassConfig::addIRPasses();
320 
321   if (TM->getOptLevel() != CodeGenOpt::None)
322     addPass(createInterleavedAccessPass(TM));
323 }
324 
325 bool X86PassConfig::addInstSelector() {
326   // Install an instruction selector.
327   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
328 
329   // For ELF, cleanup any local-dynamic TLS accesses.
330   if (TM->getTargetTriple().isOSBinFormatELF() &&
331       getOptLevel() != CodeGenOpt::None)
332     addPass(createCleanupLocalDynamicTLSPass());
333 
334   addPass(createX86GlobalBaseRegPass());
335   return false;
336 }
337 
338 #ifdef LLVM_BUILD_GLOBAL_ISEL
339 bool X86PassConfig::addIRTranslator() {
340   addPass(new IRTranslator());
341   return false;
342 }
343 
344 bool X86PassConfig::addLegalizeMachineIR() {
345   //TODO: Implement
346   return false;
347 }
348 
349 bool X86PassConfig::addRegBankSelect() {
350   //TODO: Implement
351   return false;
352 }
353 
354 bool X86PassConfig::addGlobalInstructionSelect() {
355   //TODO: Implement
356   return false;
357 }
358 #endif
359 
360 bool X86PassConfig::addILPOpts() {
361   addPass(&EarlyIfConverterID);
362   if (EnableMachineCombinerPass)
363     addPass(&MachineCombinerID);
364   return true;
365 }
366 
367 bool X86PassConfig::addPreISel() {
368   // Only add this pass for 32-bit x86 Windows.
369   const Triple &TT = TM->getTargetTriple();
370   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
371     addPass(createX86WinEHStatePass());
372   return true;
373 }
374 
375 void X86PassConfig::addPreRegAlloc() {
376   if (getOptLevel() != CodeGenOpt::None) {
377     addPass(createX86FixupSetCC());
378     addPass(createX86OptimizeLEAs());
379     addPass(createX86CallFrameOptimization());
380   }
381 
382   addPass(createX86WinAllocaExpander());
383 }
384 
385 void X86PassConfig::addPostRegAlloc() {
386   addPass(createX86FloatingPointStackifierPass());
387 }
388 
389 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
390 
391 void X86PassConfig::addPreEmitPass() {
392   if (getOptLevel() != CodeGenOpt::None)
393     addPass(createExecutionDependencyFixPass(&X86::VR128XRegClass));
394 
395   if (UseVZeroUpper)
396     addPass(createX86IssueVZeroUpperPass());
397 
398   if (getOptLevel() != CodeGenOpt::None) {
399     addPass(createX86FixupBWInsts());
400     addPass(createX86PadShortFunctions());
401     addPass(createX86FixupLEAs());
402   }
403 }
404