[x86] Add a reassociation optimization to increase ILP via the MachineCombiner pass
[oota-llvm.git] / 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 "X86TargetMachine.h"
15 #include "X86.h"
16 #include "X86TargetObjectFile.h"
17 #include "X86TargetTransformInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/FormattedStream.h"
23 #include "llvm/Support/TargetRegistry.h"
24 #include "llvm/Target/TargetOptions.h"
25 using namespace llvm;
26
27 static cl::opt<bool> EnableMachineCombinerPass("x86-machine-combiner",
28                                cl::desc("Enable the machine combiner pass"),
29                                cl::init(true), cl::Hidden);
30
31 extern "C" void LLVMInitializeX86Target() {
32   // Register the target.
33   RegisterTargetMachine<X86TargetMachine> X(TheX86_32Target);
34   RegisterTargetMachine<X86TargetMachine> Y(TheX86_64Target);
35 }
36
37 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
38   if (TT.isOSBinFormatMachO()) {
39     if (TT.getArch() == Triple::x86_64)
40       return make_unique<X86_64MachoTargetObjectFile>();
41     return make_unique<TargetLoweringObjectFileMachO>();
42   }
43
44   if (TT.isOSLinux() || TT.isOSNaCl())
45     return make_unique<X86LinuxNaClTargetObjectFile>();
46   if (TT.isOSBinFormatELF())
47     return make_unique<X86ELFTargetObjectFile>();
48   if (TT.isKnownWindowsMSVCEnvironment())
49     return make_unique<X86WindowsTargetObjectFile>();
50   if (TT.isOSBinFormatCOFF())
51     return make_unique<TargetLoweringObjectFileCOFF>();
52   llvm_unreachable("unknown subtarget type");
53 }
54
55 static std::string computeDataLayout(const Triple &TT) {
56   // X86 is little endian
57   std::string Ret = "e";
58
59   Ret += DataLayout::getManglingComponent(TT);
60   // X86 and x32 have 32 bit pointers.
61   if ((TT.isArch64Bit() &&
62        (TT.getEnvironment() == Triple::GNUX32 || TT.isOSNaCl())) ||
63       !TT.isArch64Bit())
64     Ret += "-p:32:32";
65
66   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
67   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
68     Ret += "-i64:64";
69   else
70     Ret += "-f64:32:64";
71
72   // Some ABIs align long double to 128 bits, others to 32.
73   if (TT.isOSNaCl())
74     ; // No f80
75   else if (TT.isArch64Bit() || TT.isOSDarwin())
76     Ret += "-f80:128";
77   else
78     Ret += "-f80:32";
79
80   // The registers can hold 8, 16, 32 or, in x86-64, 64 bits.
81   if (TT.isArch64Bit())
82     Ret += "-n8:16:32:64";
83   else
84     Ret += "-n8:16:32";
85
86   // The stack is aligned to 32 bits on some ABIs and 128 bits on others.
87   if (!TT.isArch64Bit() && TT.isOSWindows())
88     Ret += "-a:0:32-S32";
89   else
90     Ret += "-S128";
91
92   return Ret;
93 }
94
95 /// X86TargetMachine ctor - Create an X86 target.
96 ///
97 X86TargetMachine::X86TargetMachine(const Target &T, StringRef TT, StringRef CPU,
98                                    StringRef FS, const TargetOptions &Options,
99                                    Reloc::Model RM, CodeModel::Model CM,
100                                    CodeGenOpt::Level OL)
101     : LLVMTargetMachine(T, computeDataLayout(Triple(TT)), TT, CPU, FS, Options,
102                         RM, CM, OL),
103       TLOF(createTLOF(Triple(getTargetTriple()))),
104       Subtarget(Triple(TT), CPU, FS, *this, Options.StackAlignmentOverride) {
105   // Windows stack unwinder gets confused when execution flow "falls through"
106   // after a call to 'noreturn' function.
107   // To prevent that, we emit a trap for 'unreachable' IR instructions.
108   // (which on X86, happens to be the 'ud2' instruction)
109   if (Subtarget.isTargetWin64())
110     this->Options.TrapUnreachable = true;
111
112   // TODO: By default, all reciprocal estimate operations are off because
113   // that matches the behavior before TargetRecip was added (except for btver2
114   // which used subtarget features to enable this type of codegen).
115   // We should change this to match GCC behavior where everything but
116   // scalar division estimates are turned on by default with -ffast-math.
117   this->Options.Reciprocals.setDefaults("all", false, 1);
118
119   initAsmInfo();
120 }
121
122 X86TargetMachine::~X86TargetMachine() {}
123
124 const X86Subtarget *
125 X86TargetMachine::getSubtargetImpl(const Function &F) const {
126   Attribute CPUAttr = F.getFnAttribute("target-cpu");
127   Attribute FSAttr = F.getFnAttribute("target-features");
128
129   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
130                         ? CPUAttr.getValueAsString().str()
131                         : TargetCPU;
132   std::string FS = !FSAttr.hasAttribute(Attribute::None)
133                        ? FSAttr.getValueAsString().str()
134                        : TargetFS;
135
136   // FIXME: This is related to the code below to reset the target options,
137   // we need to know whether or not the soft float flag is set on the
138   // function before we can generate a subtarget. We also need to use
139   // it as a key for the subtarget since that can be the only difference
140   // between two functions.
141   bool SoftFloat =
142       F.hasFnAttribute("use-soft-float") &&
143       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
144   // If the soft float attribute is set on the function turn on the soft float
145   // subtarget feature.
146   if (SoftFloat)
147     FS += FS.empty() ? "+soft-float" : ",+soft-float";
148
149   auto &I = SubtargetMap[CPU + FS];
150   if (!I) {
151     // This needs to be done before we create a new subtarget since any
152     // creation will depend on the TM and the code generation flags on the
153     // function that reside in TargetOptions.
154     resetTargetOptions(F);
155     I = llvm::make_unique<X86Subtarget>(Triple(TargetTriple), CPU, FS, *this,
156                                         Options.StackAlignmentOverride);
157   }
158   return I.get();
159 }
160
161 //===----------------------------------------------------------------------===//
162 // Command line options for x86
163 //===----------------------------------------------------------------------===//
164 static cl::opt<bool>
165 UseVZeroUpper("x86-use-vzeroupper", cl::Hidden,
166   cl::desc("Minimize AVX to SSE transition penalty"),
167   cl::init(true));
168
169 //===----------------------------------------------------------------------===//
170 // X86 TTI query.
171 //===----------------------------------------------------------------------===//
172
173 TargetIRAnalysis X86TargetMachine::getTargetIRAnalysis() {
174   return TargetIRAnalysis(
175       [this](Function &F) { return TargetTransformInfo(X86TTIImpl(this, F)); });
176 }
177
178
179 //===----------------------------------------------------------------------===//
180 // Pass Pipeline Configuration
181 //===----------------------------------------------------------------------===//
182
183 namespace {
184 /// X86 Code Generator Pass Configuration Options.
185 class X86PassConfig : public TargetPassConfig {
186 public:
187   X86PassConfig(X86TargetMachine *TM, PassManagerBase &PM)
188     : TargetPassConfig(TM, PM) {}
189
190   X86TargetMachine &getX86TargetMachine() const {
191     return getTM<X86TargetMachine>();
192   }
193
194   void addIRPasses() override;
195   bool addInstSelector() override;
196   bool addILPOpts() override;
197   bool addPreISel() override;
198   void addPreRegAlloc() override;
199   void addPostRegAlloc() override;
200   void addPreEmitPass() override;
201   void addPreSched2() override;
202 };
203 } // namespace
204
205 TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
206   return new X86PassConfig(this, PM);
207 }
208
209 void X86PassConfig::addIRPasses() {
210   addPass(createAtomicExpandPass(&getX86TargetMachine()));
211
212   TargetPassConfig::addIRPasses();
213 }
214
215 bool X86PassConfig::addInstSelector() {
216   // Install an instruction selector.
217   addPass(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
218
219   // For ELF, cleanup any local-dynamic TLS accesses.
220   if (Triple(TM->getTargetTriple()).isOSBinFormatELF() &&
221       getOptLevel() != CodeGenOpt::None)
222     addPass(createCleanupLocalDynamicTLSPass());
223
224   addPass(createX86GlobalBaseRegPass());
225
226   return false;
227 }
228
229 bool X86PassConfig::addILPOpts() {
230   addPass(&EarlyIfConverterID);
231   if (EnableMachineCombinerPass)
232     addPass(&MachineCombinerID);
233   return true;
234 }
235
236 bool X86PassConfig::addPreISel() {
237   // Only add this pass for 32-bit x86 Windows.
238   Triple TT(TM->getTargetTriple());
239   if (TT.isOSWindows() && TT.getArch() == Triple::x86)
240     addPass(createX86WinEHStatePass());
241   return true;
242 }
243
244 void X86PassConfig::addPreRegAlloc() {
245   addPass(createX86CallFrameOptimization());
246 }
247
248 void X86PassConfig::addPostRegAlloc() {
249   addPass(createX86FloatingPointStackifierPass());
250 }
251
252 void X86PassConfig::addPreSched2() { addPass(createX86ExpandPseudoPass()); }
253
254 void X86PassConfig::addPreEmitPass() {
255   if (getOptLevel() != CodeGenOpt::None)
256     addPass(createExecutionDependencyFixPass(&X86::VR128RegClass));
257
258   if (UseVZeroUpper)
259     addPass(createX86IssueVZeroUpperPass());
260
261   if (getOptLevel() != CodeGenOpt::None) {
262     addPass(createX86PadShortFunctions());
263     addPass(createX86FixupLEAs());
264   }
265 }