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/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/TargetLoweringObjectFile.h"
38 #include "llvm/CodeGen/TargetPassConfig.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/TargetRegistry.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 initializeX86CallFrameOptimizationPass(PassRegistry &);
62 void initializeX86CmovConverterPassPass(PassRegistry &);
63 void initializeX86ExecutionDepsFixPass(PassRegistry &);
64 void initializeX86DomainReassignmentPass(PassRegistry &);
65 void initializeX86FlagsCopyLoweringPassPass(PassRegistry &);
66 
67 } // end namespace llvm
68 
69 extern "C" void LLVMInitializeX86Target() {
70   // Register the target.
71   RegisterTargetMachine<X86TargetMachine> X(getTheX86_32Target());
72   RegisterTargetMachine<X86TargetMachine> Y(getTheX86_64Target());
73 
74   PassRegistry &PR = *PassRegistry::getPassRegistry();
75   initializeGlobalISel(PR);
76   initializeWinEHStatePassPass(PR);
77   initializeFixupBWInstPassPass(PR);
78   initializeEvexToVexInstPassPass(PR);
79   initializeFixupLEAPassPass(PR);
80   initializeX86CallFrameOptimizationPass(PR);
81   initializeX86CmovConverterPassPass(PR);
82   initializeX86ExecutionDepsFixPass(PR);
83   initializeX86DomainReassignmentPass(PR);
84   initializeX86FlagsCopyLoweringPassPass(PR);
85 }
86 
87 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
88   if (TT.isOSBinFormatMachO()) {
89     if (TT.getArch() == Triple::x86_64)
90       return llvm::make_unique<X86_64MachoTargetObjectFile>();
91     return llvm::make_unique<TargetLoweringObjectFileMachO>();
92   }
93 
94   if (TT.isOSFreeBSD())
95     return llvm::make_unique<X86FreeBSDTargetObjectFile>();
96   if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU())
97     return llvm::make_unique<X86LinuxNaClTargetObjectFile>();
98   if (TT.isOSSolaris())
99     return llvm::make_unique<X86SolarisTargetObjectFile>();
100   if (TT.isOSFuchsia())
101     return llvm::make_unique<X86FuchsiaTargetObjectFile>();
102   if (TT.isOSBinFormatELF())
103     return llvm::make_unique<X86ELFTargetObjectFile>();
104   if (TT.isKnownWindowsMSVCEnvironment() || TT.isWindowsCoreCLREnvironment())
105     return llvm::make_unique<X86WindowsTargetObjectFile>();
106   if (TT.isOSBinFormatCOFF())
107     return llvm::make_unique<TargetLoweringObjectFileCOFF>();
108   llvm_unreachable("unknown subtarget type");
109 }
110 
111 static std::string computeDataLayout(const Triple &TT) {
112   // X86 is little endian
113   std::string Ret = "e";
114 
115   Ret += DataLayout::getManglingComponent(TT);
116   // X86 and x32 have 32 bit pointers.
117   if ((TT.isArch64Bit() &&
118        (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
119       !TT.isArch64Bit())
120     Ret += "-p:32:32";
121 
122   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
123   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
124     Ret += "-i64:64";
125   else if (TT.isOSIAMCU())
126     Ret += "-i64:32-f64:32";
127   else
128     Ret += "-f64:32:64";
129 
130   // Some ABIs align long double to 128 bits, others to 32.
131   if (TT.isOSNaCl() || TT.isOSIAMCU())
132     ; // No f80
133   else if (TT.isArch64Bit() || TT.isOSDarwin())
134     Ret += "-f80:128";
135   else
136     Ret += "-f80:32";
137 
138   if (TT.isOSIAMCU())
139     Ret += "-f128:32";
140 
141   // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
142   if (TT.isArch64Bit())
143     Ret += "-n8:16:32:64";
144   else
145     Ret += "-n8:16:32";
146 
147   // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
148   if ((!TT.isArch64Bit() && TT.isOSWindows()) || TT.isOSIAMCU())
149     Ret += "-a:0:32-S32";
150   else
151     Ret += "-S128";
152 
153   return Ret;
154 }
155 
156 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
157                                            Optional<Reloc::Model> RM) {
158   bool is64Bit = TT.getArch() == Triple::x86_64;
159   if (!RM.hasValue()) {
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 getEffectiveCodeModel(Optional<CodeModel::Model> CM,
193                                               bool JIT, bool Is64Bit) {
194   if (CM)
195     return *CM;
196   if (JIT)
197     return Is64Bit ? CodeModel::Large : CodeModel::Small;
198   return CodeModel::Small;
199 }
200 
201 /// Create an X86 target.
202 ///
203 X86TargetMachine::X86TargetMachine(const Target &T, const Triple &TT,
204                                    StringRef CPU, StringRef FS,
205                                    const TargetOptions &Options,
206                                    Optional<Reloc::Model> RM,
207                                    Optional<CodeModel::Model> CM,
208                                    CodeGenOpt::Level OL, bool JIT)
209     : LLVMTargetMachine(
210           T, computeDataLayout(TT), TT, CPU, FS, Options,
211           getEffectiveRelocModel(TT, RM),
212           getEffectiveCodeModel(CM, JIT, TT.getArch() == Triple::x86_64), OL),
213       TLOF(createTLOF(getTargetTriple())) {
214   // Windows stack unwinder gets confused when execution flow "falls through"
215   // after a call to 'noreturn' function.
216   // To prevent that, we emit a trap for 'unreachable' IR instructions.
217   // (which on X86, happens to be the 'ud2' instruction)
218   // On PS4, the "return address" of a 'noreturn' call must still be within
219   // the calling function, and TrapUnreachable is an easy way to get that.
220   // The check here for 64-bit windows is a bit icky, but as we're unlikely
221   // to ever want to mix 32 and 64-bit windows code in a single module
222   // this should be fine.
223   if ((TT.isOSWindows() && TT.getArch() == Triple::x86_64) || TT.isPS4())
224     this->Options.TrapUnreachable = true;
225 
226   initAsmInfo();
227 }
228 
229 X86TargetMachine::~X86TargetMachine() = default;
230 
231 const X86Subtarget *
232 X86TargetMachine::getSubtargetImpl(const Function &F) const {
233   Attribute CPUAttr = F.getFnAttribute("target-cpu");
234   Attribute FSAttr = F.getFnAttribute("target-features");
235 
236   StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
237                       ? CPUAttr.getValueAsString()
238                       : (StringRef)TargetCPU;
239   StringRef FS = !FSAttr.hasAttribute(Attribute::None)
240                      ? FSAttr.getValueAsString()
241                      : (StringRef)TargetFS;
242 
243   SmallString<512> Key;
244   Key.reserve(CPU.size() + FS.size());
245   Key += CPU;
246   Key += FS;
247 
248   // FIXME: This is related to the code below to reset the target options,
249   // we need to know whether or not the soft float flag is set on the
250   // function before we can generate a subtarget. We also need to use
251   // it as a key for the subtarget since that can be the only difference
252   // between two functions.
253   bool SoftFloat =
254       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
255   // If the soft float attribute is set on the function turn on the soft float
256   // subtarget feature.
257   if (SoftFloat)
258     Key += FS.empty() ? "+soft-float" : ",+soft-float";
259 
260   FS = Key.substr(CPU.size());
261 
262   auto &I = SubtargetMap[Key];
263   if (!I) {
264     // This needs to be done before we create a new subtarget since any
265     // creation will depend on the TM and the code generation flags on the
266     // function that reside in TargetOptions.
267     resetTargetOptions(F);
268     I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
269                                         Options.StackAlignmentOverride);
270   }
271   return I.get();
272 }
273 
274 //===----------------------------------------------------------------------===//
275 // Command line options for x86
276 //===----------------------------------------------------------------------===//
277 static cl::opt<bool>
278 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
279   cl::desc("Minimize AVX to SSE transition penalty"),
280   cl::init(true));
281 
282 //===----------------------------------------------------------------------===//
283 // X86 TTI query.
284 //===----------------------------------------------------------------------===//
285 
286 TargetTransformInfo
287 X86TargetMachine::getTargetTransformInfo(const Function &F) {
288   return TargetTransformInfo(X86TTIImpl(this, F));
289 }
290 
291 //===----------------------------------------------------------------------===//
292 // Pass Pipeline Configuration
293 //===----------------------------------------------------------------------===//
294 
295 namespace {
296 
297 /// X86 Code Generator Pass Configuration Options.
298 class X86PassConfig : public TargetPassConfig {
299 public:
300   X86PassConfig(X86TargetMachine &TM, PassManagerBase &PM)
301     : TargetPassConfig(TM, PM) {}
302 
303   X86TargetMachine &getX86TargetMachine() const {
304     return getTM<X86TargetMachine>();
305   }
306 
307   ScheduleDAGInstrs *
308   createMachineScheduler(MachineSchedContext *C) const override {
309     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
310     DAG->addMutation(createX86MacroFusionDAGMutation());
311     return DAG;
312   }
313 
314   void addIRPasses() override;
315   bool addInstSelector() override;
316   bool addIRTranslator() override;
317   bool addLegalizeMachineIR() override;
318   bool addRegBankSelect() override;
319   bool addGlobalInstructionSelect() override;
320   bool addILPOpts() override;
321   bool addPreISel() override;
322   void addMachineSSAOptimization() override;
323   void addPreRegAlloc() override;
324   void addPostRegAlloc() override;
325   void addPreEmitPass() override;
326   void addPreEmitPass2() override;
327   void addPreSched2() override;
328 };
329 
330 class X86ExecutionDepsFix : public ExecutionDepsFix {
331 public:
332   static char ID;
333   X86ExecutionDepsFix() : ExecutionDepsFix(ID, X86::VR128XRegClass) {}
334   StringRef getPassName() const override {
335     return "X86 Execution Dependency Fix";
336   }
337 };
338 char X86ExecutionDepsFix::ID;
339 
340 } // end anonymous namespace
341 
342 INITIALIZE_PASS(X86ExecutionDepsFix, "x86-execution-deps-fix",
343                 "X86 Execution Dependency Fix", false, false)
344 
345 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
346   return new X86PassConfig(*this, PM);
347 }
348 
349 void X86PassConfig::addIRPasses() {
350   addPass(createAtomicExpandPass());
351 
352   TargetPassConfig::addIRPasses();
353 
354   if (TM->getOptLevel() != CodeGenOpt::None)
355     addPass(createInterleavedAccessPass());
356 
357   // Add passes that handle indirect branch removal and insertion of a retpoline
358   // thunk. These will be a no-op unless a function subtarget has the retpoline
359   // feature enabled.
360   addPass(createIndirectBrExpandPass());
361 }
362 
363 bool X86PassConfig::addInstSelector() {
364   // Install an instruction selector.
365   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
366 
367   // For ELF, cleanup any local-dynamic TLS accesses.
368   if (TM->getTargetTriple().isOSBinFormatELF() &&
369       getOptLevel() != CodeGenOpt::None)
370     addPass(createCleanupLocalDynamicTLSPass());
371 
372   addPass(createX86GlobalBaseRegPass());
373   return false;
374 }
375 
376 bool X86PassConfig::addIRTranslator() {
377   addPass(new IRTranslator());
378   return false;
379 }
380 
381 bool X86PassConfig::addLegalizeMachineIR() {
382   addPass(new Legalizer());
383   return false;
384 }
385 
386 bool X86PassConfig::addRegBankSelect() {
387   addPass(new RegBankSelect());
388   return false;
389 }
390 
391 bool X86PassConfig::addGlobalInstructionSelect() {
392   addPass(new InstructionSelect());
393   return false;
394 }
395 
396 bool X86PassConfig::addILPOpts() {
397   addPass(&EarlyIfConverterID);
398   if (EnableMachineCombinerPass)
399     addPass(&MachineCombinerID);
400   addPass(createX86CmovConverterPass());
401   return true;
402 }
403 
404 bool X86PassConfig::addPreISel() {
405   // Only add this pass for 32-bit x86 Windows.
406   const Triple &TT = TM->getTargetTriple();
407   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
408     addPass(createX86WinEHStatePass());
409   return true;
410 }
411 
412 void X86PassConfig::addPreRegAlloc() {
413   if (getOptLevel() != CodeGenOpt::None) {
414     addPass(&LiveRangeShrinkID);
415     addPass(createX86FixupSetCC());
416     addPass(createX86OptimizeLEAs());
417     addPass(createX86CallFrameOptimization());
418   }
419 
420   addPass(createX86FlagsCopyLoweringPass());
421   addPass(createX86WinAllocaExpander());
422 }
423 void X86PassConfig::addMachineSSAOptimization() {
424   addPass(createX86DomainReassignmentPass());
425   TargetPassConfig::addMachineSSAOptimization();
426 }
427 
428 void X86PassConfig::addPostRegAlloc() {
429   addPass(createX86FloatingPointStackifierPass());
430 }
431 
432 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
433 
434 void X86PassConfig::addPreEmitPass() {
435   if (getOptLevel() != CodeGenOpt::None)
436     addPass(new X86ExecutionDepsFix());
437 
438   if (UseVZeroUpper)
439     addPass(createX86IssueVZeroUpperPass());
440 
441   if (getOptLevel() != CodeGenOpt::None) {
442     addPass(createX86FixupBWInsts());
443     addPass(createX86PadShortFunctions());
444     addPass(createX86FixupLEAs());
445     addPass(createX86EvexToVexInsts());
446   }
447 }
448 
449 void X86PassConfig::addPreEmitPass2() {
450   addPass(createX86RetpolineThunksPass());
451 }
452