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