f0ee66496763cc1de1deca132ac7046df86d2a00
[oota-llvm.git] / lib / Target / AArch64 / AArch64TargetMachine.cpp
1 //===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
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 //
11 //===----------------------------------------------------------------------===//
12
13 #include "AArch64.h"
14 #include "AArch64TargetMachine.h"
15 #include "AArch64TargetObjectFile.h"
16 #include "AArch64TargetTransformInfo.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/RegAllocRegistry.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/TargetRegistry.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/Transforms/Scalar.h"
25 using namespace llvm;
26
27 static cl::opt<bool>
28 EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"),
29            cl::init(true), cl::Hidden);
30
31 static cl::opt<bool> EnableMCR("aarch64-mcr",
32                                cl::desc("Enable the machine combiner pass"),
33                                cl::init(true), cl::Hidden);
34
35 static cl::opt<bool>
36 EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"),
37                      cl::init(true), cl::Hidden);
38
39 static cl::opt<bool>
40 EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar"
41                     " integer instructions"), cl::init(false), cl::Hidden);
42
43 static cl::opt<bool>
44 EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote "
45                       "constant pass"), cl::init(true), cl::Hidden);
46
47 static cl::opt<bool>
48 EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the"
49                  " linker optimization hints (LOH)"), cl::init(true),
50                  cl::Hidden);
51
52 static cl::opt<bool>
53 EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden,
54                               cl::desc("Enable the pass that removes dead"
55                                        " definitons and replaces stores to"
56                                        " them with stores to the zero"
57                                        " register"),
58                               cl::init(true));
59
60 static cl::opt<bool>
61 EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair"
62                    " optimization pass"), cl::init(true), cl::Hidden);
63
64 static cl::opt<bool>
65 EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden,
66                  cl::desc("Run SimplifyCFG after expanding atomic operations"
67                           " to make use of cmpxchg flow-based information"),
68                  cl::init(true));
69
70 static cl::opt<bool> AArch64InterleavedAccessOpt(
71     "aarch64-interleaved-access-opt",
72     cl::desc("Optimize interleaved memory accesses in the AArch64 backend"),
73     cl::init(false), cl::Hidden);
74
75 static cl::opt<bool>
76 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
77                         cl::desc("Run early if-conversion"),
78                         cl::init(true));
79
80 static cl::opt<bool>
81 EnableCondOpt("aarch64-condopt",
82               cl::desc("Enable the condition optimizer pass"),
83               cl::init(true), cl::Hidden);
84
85 static cl::opt<bool>
86 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
87                 cl::desc("Work around Cortex-A53 erratum 835769"),
88                 cl::init(false));
89
90 static cl::opt<bool>
91 EnableGEPOpt("aarch64-gep-opt", cl::Hidden,
92              cl::desc("Enable optimizations on complex GEPs"),
93              cl::init(false));
94
95 // FIXME: Unify control over GlobalMerge.
96 static cl::opt<cl::boolOrDefault>
97 EnableGlobalMerge("aarch64-global-merge", cl::Hidden,
98                   cl::desc("Enable the global merge pass"));
99
100 extern "C" void LLVMInitializeAArch64Target() {
101   // Register the target.
102   RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget);
103   RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget);
104   RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64Target);
105 }
106
107 //===----------------------------------------------------------------------===//
108 // AArch64 Lowering public interface.
109 //===----------------------------------------------------------------------===//
110 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
111   if (TT.isOSBinFormatMachO())
112     return make_unique<AArch64_MachoTargetObjectFile>();
113
114   return make_unique<AArch64_ELFTargetObjectFile>();
115 }
116
117 // Helper function to build a DataLayout string
118 static std::string computeDataLayout(const Triple &TT, bool LittleEndian) {
119   if (TT.isOSBinFormatMachO())
120     return "e-m:o-i64:64-i128:128-n32:64-S128";
121   if (LittleEndian)
122     return "e-m:e-i64:64-i128:128-n32:64-S128";
123   return "E-m:e-i64:64-i128:128-n32:64-S128";
124 }
125
126 /// TargetMachine ctor - Create an AArch64 architecture model.
127 ///
128 AArch64TargetMachine::AArch64TargetMachine(const Target &T, StringRef TT,
129                                            StringRef CPU, StringRef FS,
130                                            const TargetOptions &Options,
131                                            Reloc::Model RM, CodeModel::Model CM,
132                                            CodeGenOpt::Level OL,
133                                            bool LittleEndian)
134     // This nested ternary is horrible, but DL needs to be properly
135     // initialized before TLInfo is constructed.
136     : LLVMTargetMachine(T, computeDataLayout(Triple(TT), LittleEndian), TT, CPU,
137                         FS, Options, RM, CM, OL),
138       TLOF(createTLOF(Triple(getTargetTriple()))),
139       isLittle(LittleEndian) {
140   initAsmInfo();
141 }
142
143 AArch64TargetMachine::~AArch64TargetMachine() {}
144
145 const AArch64Subtarget *
146 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
147   Attribute CPUAttr = F.getFnAttribute("target-cpu");
148   Attribute FSAttr = F.getFnAttribute("target-features");
149
150   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
151                         ? CPUAttr.getValueAsString().str()
152                         : TargetCPU;
153   std::string FS = !FSAttr.hasAttribute(Attribute::None)
154                        ? FSAttr.getValueAsString().str()
155                        : TargetFS;
156
157   auto &I = SubtargetMap[CPU + FS];
158   if (!I) {
159     // This needs to be done before we create a new subtarget since any
160     // creation will depend on the TM and the code generation flags on the
161     // function that reside in TargetOptions.
162     resetTargetOptions(F);
163     I = llvm::make_unique<AArch64Subtarget>(Triple(TargetTriple), CPU, FS,
164                                             *this, isLittle);
165   }
166   return I.get();
167 }
168
169 void AArch64leTargetMachine::anchor() { }
170
171 AArch64leTargetMachine::
172 AArch64leTargetMachine(const Target &T, StringRef TT,
173                        StringRef CPU, StringRef FS, const TargetOptions &Options,
174                        Reloc::Model RM, CodeModel::Model CM,
175                        CodeGenOpt::Level OL)
176   : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
177
178 void AArch64beTargetMachine::anchor() { }
179
180 AArch64beTargetMachine::
181 AArch64beTargetMachine(const Target &T, StringRef TT,
182                        StringRef CPU, StringRef FS, const TargetOptions &Options,
183                        Reloc::Model RM, CodeModel::Model CM,
184                        CodeGenOpt::Level OL)
185   : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
186
187 namespace {
188 /// AArch64 Code Generator Pass Configuration Options.
189 class AArch64PassConfig : public TargetPassConfig {
190 public:
191   AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
192       : TargetPassConfig(TM, PM) {
193     if (TM->getOptLevel() != CodeGenOpt::None)
194       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
195   }
196
197   AArch64TargetMachine &getAArch64TargetMachine() const {
198     return getTM<AArch64TargetMachine>();
199   }
200
201   void addIRPasses()  override;
202   bool addPreISel() override;
203   bool addInstSelector() override;
204   bool addILPOpts() override;
205   void addPreRegAlloc() override;
206   void addPostRegAlloc() override;
207   void addPreSched2() override;
208   void addPreEmitPass() override;
209 };
210 } // namespace
211
212 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
213   return TargetIRAnalysis([this](Function &F) {
214     return TargetTransformInfo(AArch64TTIImpl(this, F));
215   });
216 }
217
218 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
219   return new AArch64PassConfig(this, PM);
220 }
221
222 void AArch64PassConfig::addIRPasses() {
223   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
224   // ourselves.
225   addPass(createAtomicExpandPass(TM));
226
227   // Cmpxchg instructions are often used with a subsequent comparison to
228   // determine whether it succeeded. We can exploit existing control-flow in
229   // ldrex/strex loops to simplify this, but it needs tidying up.
230   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
231     addPass(createCFGSimplificationPass());
232
233   if (TM->getOptLevel() != CodeGenOpt::None && AArch64InterleavedAccessOpt)
234     addPass(createAArch64InterleavedAccessPass());
235
236   TargetPassConfig::addIRPasses();
237
238   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
239     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
240     // and lower a GEP with multiple indices to either arithmetic operations or
241     // multiple GEPs with single index.
242     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
243     // Call EarlyCSE pass to find and remove subexpressions in the lowered
244     // result.
245     addPass(createEarlyCSEPass());
246     // Do loop invariant code motion in case part of the lowered result is
247     // invariant.
248     addPass(createLICMPass());
249   }
250 }
251
252 // Pass Pipeline Configuration
253 bool AArch64PassConfig::addPreISel() {
254   // Run promote constant before global merge, so that the promoted constants
255   // get a chance to be merged
256   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
257     addPass(createAArch64PromoteConstantPass());
258   // FIXME: On AArch64, this depends on the type.
259   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
260   // and the offset has to be a multiple of the related size in bytes.
261   if ((TM->getOptLevel() != CodeGenOpt::None &&
262        EnableGlobalMerge == cl::BOU_UNSET) ||
263       EnableGlobalMerge == cl::BOU_TRUE) {
264     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
265                                (EnableGlobalMerge == cl::BOU_UNSET);
266     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
267   }
268
269   if (TM->getOptLevel() != CodeGenOpt::None)
270     addPass(createAArch64AddressTypePromotionPass());
271
272   return false;
273 }
274
275 bool AArch64PassConfig::addInstSelector() {
276   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
277
278   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
279   // references to _TLS_MODULE_BASE_ as possible.
280   if (Triple(TM->getTargetTriple()).isOSBinFormatELF() &&
281       getOptLevel() != CodeGenOpt::None)
282     addPass(createAArch64CleanupLocalDynamicTLSPass());
283
284   return false;
285 }
286
287 bool AArch64PassConfig::addILPOpts() {
288   if (EnableCondOpt)
289     addPass(createAArch64ConditionOptimizerPass());
290   if (EnableCCMP)
291     addPass(createAArch64ConditionalCompares());
292   if (EnableMCR)
293     addPass(&MachineCombinerID);
294   if (EnableEarlyIfConversion)
295     addPass(&EarlyIfConverterID);
296   if (EnableStPairSuppress)
297     addPass(createAArch64StorePairSuppressPass());
298   return true;
299 }
300
301 void AArch64PassConfig::addPreRegAlloc() {
302   // Use AdvSIMD scalar instructions whenever profitable.
303   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
304     addPass(createAArch64AdvSIMDScalar());
305     // The AdvSIMD pass may produce copies that can be rewritten to
306     // be register coaleascer friendly.
307     addPass(&PeepholeOptimizerID);
308   }
309 }
310
311 void AArch64PassConfig::addPostRegAlloc() {
312   // Change dead register definitions to refer to the zero register.
313   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
314     addPass(createAArch64DeadRegisterDefinitions());
315   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
316     // Improve performance for some FP/SIMD code for A57.
317     addPass(createAArch64A57FPLoadBalancing());
318 }
319
320 void AArch64PassConfig::addPreSched2() {
321   // Expand some pseudo instructions to allow proper scheduling.
322   addPass(createAArch64ExpandPseudoPass());
323   // Use load/store pair instructions when possible.
324   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
325     addPass(createAArch64LoadStoreOptimizationPass());
326 }
327
328 void AArch64PassConfig::addPreEmitPass() {
329   if (EnableA53Fix835769)
330     addPass(createAArch64A53Fix835769());
331   // Relax conditional branch instructions if they're otherwise out of
332   // range of their destination.
333   addPass(createAArch64BranchRelaxation());
334   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
335       Triple(TM->getTargetTriple()).isOSBinFormatMachO())
336     addPass(createAArch64CollectLOHPass());
337 }