LLVM  5.0.0
X86TargetMachine.cpp
Go to the documentation of this file.
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 
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"
36 #include "llvm/CodeGen/Passes.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"
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 
62 
63 } // end namespace llvm
64 
65 extern "C" void LLVMInitializeX86Target() {
66  // Register the target.
69 
77 }
78 
79 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
80  if (TT.isOSBinFormatMachO()) {
81  if (TT.getArch() == Triple::x86_64)
82  return llvm::make_unique<X86_64MachoTargetObjectFile>();
83  return llvm::make_unique<TargetLoweringObjectFileMachO>();
84  }
85 
86  if (TT.isOSFreeBSD())
87  return llvm::make_unique<X86FreeBSDTargetObjectFile>();
88  if (TT.isOSLinux() || TT.isOSNaCl() || TT.isOSIAMCU())
89  return llvm::make_unique<X86LinuxNaClTargetObjectFile>();
90  if (TT.isOSSolaris())
91  return llvm::make_unique<X86SolarisTargetObjectFile>();
92  if (TT.isOSFuchsia())
93  return llvm::make_unique<X86FuchsiaTargetObjectFile>();
94  if (TT.isOSBinFormatELF())
95  return llvm::make_unique<X86ELFTargetObjectFile>();
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 
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 
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 ///
187  StringRef CPU, StringRef FS,
188  const TargetOptions &Options,
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 
210 
211 const X86Subtarget *
213  Attribute CPUAttr = F.getFnAttribute("target-cpu");
214  Attribute FSAttr = F.getFnAttribute("target-features");
215 
216  StringRef CPU = !CPUAttr.hasAttribute(Attribute::None)
217  ? CPUAttr.getValueAsString()
218  : (StringRef)TargetCPU;
220  ? FSAttr.getValueAsString()
221  : (StringRef)TargetFS;
222 
223  SmallString<512> Key;
224  Key.reserve(CPU.size() + FS.size());
225  Key += CPU;
226  Key += FS;
227 
228  // FIXME: This is related to the code below to reset the target options,
229  // we need to know whether or not the soft float flag is set on the
230  // function before we can generate a subtarget. We also need to use
231  // it as a key for the subtarget since that can be the only difference
232  // between two functions.
233  bool SoftFloat =
234  F.getFnAttribute("use-soft-float").getValueAsString() == "true";
235  // If the soft float attribute is set on the function turn on the soft float
236  // subtarget feature.
237  if (SoftFloat)
238  Key += FS.empty() ? "+soft-float" : ",+soft-float";
239 
240  FS = Key.substr(CPU.size());
241 
242  auto &I = SubtargetMap[Key];
243  if (!I) {
244  // This needs to be done before we create a new subtarget since any
245  // creation will depend on the TM and the code generation flags on the
246  // function that reside in TargetOptions.
248  I = llvm::make_unique<X86Subtarget>(TargetTriple, CPU, FS, *this,
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 
267  return TargetIRAnalysis([this](const Function &F) {
268  return TargetTransformInfo(X86TTIImpl(this, F));
269  });
270 }
271 
272 //===----------------------------------------------------------------------===//
273 // Pass Pipeline Configuration
274 //===----------------------------------------------------------------------===//
275 
276 namespace {
277 
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 
289  createMachineScheduler(MachineSchedContext *C) const override {
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 
311 class X86ExecutionDepsFix : public ExecutionDepsFix {
312 public:
313  static char ID;
314  X86ExecutionDepsFix() : ExecutionDepsFix(ID, X86::VR128XRegClass) {}
315  StringRef getPassName() const override {
316  return "X86 Execution Dependency Fix";
317  }
318 };
320 
321 } // end anonymous namespace
322 
323 INITIALIZE_PASS(X86ExecutionDepsFix, "x86-execution-deps-fix",
324  "X86 Execution Dependency Fix", false, false)
325 
326 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
327  return new X86PassConfig(*this, PM);
328 }
329 
330 void X86PassConfig::addIRPasses() {
331  addPass(createAtomicExpandPass());
332 
334 
335  if (TM->getOptLevel() != CodeGenOpt::None)
336  addPass(createInterleavedAccessPass());
337 }
338 
339 bool X86PassConfig::addInstSelector() {
340  // Install an instruction selector.
341  addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
342 
343  // For ELF, cleanup any local-dynamic TLS accesses.
344  if (TM->getTargetTriple().isOSBinFormatELF() &&
345  getOptLevel() != CodeGenOpt::None)
347 
348  addPass(createX86GlobalBaseRegPass());
349  return false;
350 }
351 
352 #ifdef LLVM_BUILD_GLOBAL_ISEL
353 bool X86PassConfig::addIRTranslator() {
354  addPass(new IRTranslator());
355  return false;
356 }
357 
358 bool X86PassConfig::addLegalizeMachineIR() {
359  addPass(new Legalizer());
360  return false;
361 }
362 
363 bool X86PassConfig::addRegBankSelect() {
364  addPass(new RegBankSelect());
365  return false;
366 }
367 
368 bool X86PassConfig::addGlobalInstructionSelect() {
369  addPass(new InstructionSelect());
370  return false;
371 }
372 #endif
373 
374 bool X86PassConfig::addILPOpts() {
375  addPass(&EarlyIfConverterID);
377  addPass(&MachineCombinerID);
378  addPass(createX86CmovConverterPass());
379  return true;
380 }
381 
382 bool X86PassConfig::addPreISel() {
383  // Only add this pass for 32-bit x86 Windows.
384  const Triple &TT = TM->getTargetTriple();
385  if (TT.isOSWindows() && TT.getArch() == Triple::x86)
386  addPass(createX86WinEHStatePass());
387  return true;
388 }
389 
390 void X86PassConfig::addPreRegAlloc() {
391  if (getOptLevel() != CodeGenOpt::None) {
392  addPass(&LiveRangeShrinkID);
393  addPass(createX86FixupSetCC());
394  addPass(createX86OptimizeLEAs());
396  }
397 
398  addPass(createX86WinAllocaExpander());
399 }
400 
401 void X86PassConfig::addPostRegAlloc() {
403 }
404 
405 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
406 
407 void X86PassConfig::addPreEmitPass() {
408  if (getOptLevel() != CodeGenOpt::None)
409  addPass(new X86ExecutionDepsFix());
410 
411  if (UseVZeroUpper)
412  addPass(createX86IssueVZeroUpperPass());
413 
414  if (getOptLevel() != CodeGenOpt::None) {
415  addPass(createX86FixupBWInsts());
416  addPass(createX86PadShortFunctions());
417  addPass(createX86FixupLEAs());
418  addPass(createX86EvexToVexInsts());
419  }
420 }
char & MachineCombinerID
This pass performs instruction combining using trace metrics to estimate critical-path and resource d...
static std::unique_ptr< TargetLoweringObjectFile > createTLOF(const Triple &TT)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void LLVMInitializeX86Target()
static cl::opt< bool > EnableMachineCombinerPass("x86-machine-combiner", cl::desc("Enable the machine combiner pass"), cl::init(true), cl::Hidden)
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:587
FunctionPass * createX86OptimizeLEAs()
Return a pass that removes redundant LEA instructions and redundant address recalculations.
FunctionPass * createX86FixupBWInsts()
Return a Machine IR pass that selectively replaces certain byte and word instructions by equivalent 3...
bool hasValue() const
Definition: Optional.h:133
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
void initializeFixupBWInstPassPass(PassRegistry &)
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with...
Definition: TargetMachine.h:75
FunctionPass * createX86FixupSetCC()
Return a pass that transforms setcc + movzx pairs into xor + setcc.
This file a TargetTransformInfo::Concept conforming object specific to the X86 target machine...
static std::string computeDataLayout(const Triple &TT)
TargetIRAnalysis getTargetIRAnalysis() override
Get a TargetIRAnalysis implementation for the target.
char & EarlyIfConverterID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions...
Analysis pass providing the TargetTransformInfo.
std::unique_ptr< ScheduleDAGMutation > createX86MacroFusionDAGMutation()
Note that you have to add: DAG.addMutation(createX86MacroFusionDAGMutation()); to X86PassConfig::crea...
FunctionPass * createX86CallFrameOptimization()
Return a pass that optimizes the code-size of x86 call sequences.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:262
bool isOSIAMCU() const
Definition: Triple.h:496
FunctionPass * createX86IssueVZeroUpperPass()
This pass inserts AVX vzeroupper instructions before each call to avoid transition penalty between fu...
FunctionPass * createX86EvexToVexInsts()
This pass replaces EVEX ecnoded of AVX-512 instructiosn by VEX encoding when possible in order to red...
StringRef substr(size_t Start, size_t N=StringRef::npos) const
Return a reference to the substring from [Start, Start + N).
Definition: SmallString.h:246
void reserve(size_type N)
Definition: SmallVector.h:377
X86TargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional< Reloc::Model > RM, CodeModel::Model CM, CodeGenOpt::Level OL)
Create an X86 target.
bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
Definition: Attributes.cpp:202
static const char * getManglingComponent(const Triple &T)
Definition: DataLayout.cpp:154
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:551
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
FunctionPass * createX86PadShortFunctions()
Return a pass that pads short functions with NOOPs.
FunctionPass * createX86CmovConverterPass()
This pass converts X86 cmov instructions into branch when profitable.
This file contains the simple types necessary to represent the attributes associated with functions a...
No attributes have been set.
Definition: Attributes.h:72
Target-Independent Code Generator Pass Configuration Options.
bool isArch64Bit() const
Test whether the architecture is 64-bit.
Definition: Triple.cpp:1223
bool isOSLinux() const
Tests whether the OS is Linux.
Definition: Triple.h:561
#define F(x, y, z)
Definition: MD5.cpp:55
bool isOSNaCl() const
Tests whether the OS is NaCl (Native Client)
Definition: Triple.h:556
void initializeEvexToVexInstPassPass(PassRegistry &)
FunctionPass * createX86FixupLEAs()
Return a pass that selectively replaces certain instructions (like add, sub, inc, dec...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:281
ScheduleDAGMILive * createGenericSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
char & LiveRangeShrinkID
LiveRangeShrink pass.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
void initializeX86ExecutionDepsFixPass(PassRegistry &)
static Reloc::Model getEffectiveRelocModel(Optional< Reloc::Model > RM)
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
Definition: RegBankSelect.h:91
FunctionPass * createX86ExpandPseudoPass()
Return a Machine IR pass that expands X86-specific pseudo instructions into a sequence of actual inst...
FunctionPass * createX86GlobalBaseRegPass()
This pass initializes a global base register for PIC on x86-32.
static bool is64Bit(const char *name)
FunctionPass * createInterleavedAccessPass()
InterleavedAccess Pass - This pass identifies and matches interleaved memory accesses to target speci...
bool isOSFuchsia() const
Definition: Triple.h:482
const X86Subtarget * getSubtargetImpl() const =delete
void initializeFixupLEAPassPass(PassRegistry &)
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
This class describes a target machine that is implemented with the LLVM target-independent code gener...
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:582
bool isWindowsCoreCLREnvironment() const
Definition: Triple.h:523
~X86TargetMachine() override
Windows x64, Windows Itanium (IA-64)
bool isOSSolaris() const
Definition: Triple.h:488
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:466
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
unsigned StackAlignmentOverride
StackAlignmentOverride - Override default stack alignment for target.
This pass is responsible for selecting generic machine instructions to target-specific instructions...
FunctionPass * createX86FloatingPointStackifierPass()
This function returns a pass which converts floating-point register references and pseudo instruction...
Target - Wrapper for Target specific information.
This file describes how to lower LLVM calls to machine code calls.
std::string TargetCPU
Definition: TargetMachine.h:76
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
static cl::opt< bool > UseVZeroUpper("x86-use-vzeroupper", cl::Hidden, cl::desc("Minimize AVX to SSE transition penalty"), cl::init(true))
llvm_unreachable("Unknown RegBank!")
FunctionPass * createX86WinAllocaExpander()
Return a pass that expands WinAlloca pseudo-instructions.
A ScheduleDAG for scheduling lists of MachineInstr.
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:577
INITIALIZE_PASS(X86ExecutionDepsFix,"x86-execution-deps-fix","X86 Execution Dependency Fix", false, false) TargetPassConfig *X86TargetMachine
#define C
Definition: LargeTest.cpp:25
FunctionPass * createX86ISelDag(X86TargetMachine &TM, CodeGenOpt::Level OptLevel)
This pass converts a legalized DAG into a X86-specific DAG, ready for instruction scheduling...
TargetOptions Options
Definition: TargetMachine.h:95
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
#define I(x, y, z)
Definition: MD5.cpp:58
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
Target & getTheX86_32Target()
bool isOSFreeBSD() const
Definition: Triple.h:478
std::string TargetFS
Definition: TargetMachine.h:77
void initializeWinEHStatePassPass(PassRegistry &)
EnvironmentType getEnvironment() const
getEnvironment - Get the parsed environment type of this triple.
Definition: Triple.h:299
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:195
This file declares the IRTranslator pass.
RegisterTargetMachine - Helper template for registering a target machine implementation, for use in the target machine initialization function.
bool isKnownWindowsMSVCEnvironment() const
Checks if the environment is MSVC.
Definition: Triple.h:519
This file describes how to lower LLVM calls to machine code calls.
This file declares the targeting of the Machinelegalizer class for X86.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:40
unsigned TrapUnreachable
Emit target-specific trap instruction for 'unreachable' IR instructions.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
This pass exposes codegen information to IR-level passes.
FunctionPass * createX86WinEHStatePass()
Return an IR pass that inserts EH registration stack objects and explicit EH state updates...
bool isPS4() const
Tests whether the target is the PS4 platform.
Definition: Triple.h:604
FunctionPass * createAtomicExpandPass()
Target & getTheX86_64Target()
FunctionPass * createCleanupLocalDynamicTLSPass()
This pass combines multiple accesses to local-dynamic TLS variables so that the TLS base address for ...
void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
Definition: GlobalISel.cpp:21
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.