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