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 "AArch64CallLowering.h"
15 #include "AArch64RegisterBankInfo.h"
16 #include "AArch64TargetMachine.h"
17 #include "AArch64TargetObjectFile.h"
18 #include "AArch64TargetTransformInfo.h"
19 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
20 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/LegacyPassManager.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Transforms/Scalar.h"
31 using namespace llvm;
32 
33 static cl::opt<bool>
34 EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"),
35            cl::init(true), cl::Hidden);
36 
37 static cl::opt<bool> EnableMCR("aarch64-mcr",
38                                cl::desc("Enable the machine combiner pass"),
39                                cl::init(true), cl::Hidden);
40 
41 static cl::opt<bool>
42 EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"),
43                      cl::init(true), cl::Hidden);
44 
45 static cl::opt<bool>
46 EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar"
47                     " integer instructions"), cl::init(false), cl::Hidden);
48 
49 static cl::opt<bool>
50 EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote "
51                       "constant pass"), cl::init(true), cl::Hidden);
52 
53 static cl::opt<bool>
54 EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the"
55                  " linker optimization hints (LOH)"), cl::init(true),
56                  cl::Hidden);
57 
58 static cl::opt<bool>
59 EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden,
60                               cl::desc("Enable the pass that removes dead"
61                                        " definitons and replaces stores to"
62                                        " them with stores to the zero"
63                                        " register"),
64                               cl::init(true));
65 
66 static cl::opt<bool>
67 EnableRedundantCopyElimination("aarch64-redundant-copy-elim",
68               cl::desc("Enable the redundant copy elimination pass"),
69               cl::init(true), cl::Hidden);
70 
71 static cl::opt<bool>
72 EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair"
73                    " optimization pass"), cl::init(true), cl::Hidden);
74 
75 static cl::opt<bool>
76 EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden,
77                  cl::desc("Run SimplifyCFG after expanding atomic operations"
78                           " to make use of cmpxchg flow-based information"),
79                  cl::init(true));
80 
81 static cl::opt<bool>
82 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
83                         cl::desc("Run early if-conversion"),
84                         cl::init(true));
85 
86 static cl::opt<bool>
87 EnableCondOpt("aarch64-condopt",
88               cl::desc("Enable the condition optimizer pass"),
89               cl::init(true), cl::Hidden);
90 
91 static cl::opt<bool>
92 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
93                 cl::desc("Work around Cortex-A53 erratum 835769"),
94                 cl::init(false));
95 
96 static cl::opt<bool>
97 EnableGEPOpt("aarch64-gep-opt", cl::Hidden,
98              cl::desc("Enable optimizations on complex GEPs"),
99              cl::init(false));
100 
101 // FIXME: Unify control over GlobalMerge.
102 static cl::opt<cl::boolOrDefault>
103 EnableGlobalMerge("aarch64-global-merge", cl::Hidden,
104                   cl::desc("Enable the global merge pass"));
105 
106 static cl::opt<bool>
107     EnableLoopDataPrefetch("aarch64-loop-data-prefetch", cl::Hidden,
108                            cl::desc("Enable the loop data prefetch pass"),
109                            cl::init(true));
110 
111 extern "C" void LLVMInitializeAArch64Target() {
112   // Register the target.
113   RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget);
114   RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget);
115   RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64Target);
116   auto PR = PassRegistry::getPassRegistry();
117   initializeGlobalISel(*PR);
118   initializeAArch64ExpandPseudoPass(*PR);
119 }
120 
121 //===----------------------------------------------------------------------===//
122 // AArch64 Lowering public interface.
123 //===----------------------------------------------------------------------===//
124 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
125   if (TT.isOSBinFormatMachO())
126     return make_unique<AArch64_MachoTargetObjectFile>();
127 
128   return make_unique<AArch64_ELFTargetObjectFile>();
129 }
130 
131 // Helper function to build a DataLayout string
132 static std::string computeDataLayout(const Triple &TT, bool LittleEndian) {
133   if (TT.isOSBinFormatMachO())
134     return "e-m:o-i64:64-i128:128-n32:64-S128";
135   if (LittleEndian)
136     return "e-m:e-i64:64-i128:128-n32:64-S128";
137   return "E-m:e-i64:64-i128:128-n32:64-S128";
138 }
139 
140 // Helper function to set up the defaults for reciprocals.
141 static void initReciprocals(AArch64TargetMachine& TM, AArch64Subtarget& ST)
142 {
143   // For the estimates, convergence is quadratic, so essentially the number of
144   // digits is doubled after each iteration. ARMv8, the minimum architected
145   // accuracy of the initial estimate is 2^-8.  Therefore, the number of extra
146   // steps to refine the result for float (23 mantissa bits) and for double
147   // (52 mantissa bits) are 2 and 3, respectively.
148   unsigned ExtraStepsF = 2,
149            ExtraStepsD = ExtraStepsF + 1;
150   // FIXME: Enable x^-1/2 only for Exynos M1 at the moment.
151   bool UseRsqrt = ST.isExynosM1();
152 
153   TM.Options.Reciprocals.setDefaults("sqrtf", UseRsqrt, ExtraStepsF);
154   TM.Options.Reciprocals.setDefaults("sqrtd", UseRsqrt, ExtraStepsD);
155   TM.Options.Reciprocals.setDefaults("vec-sqrtf", UseRsqrt, ExtraStepsF);
156   TM.Options.Reciprocals.setDefaults("vec-sqrtd", UseRsqrt, ExtraStepsD);
157 
158   TM.Options.Reciprocals.setDefaults("divf", false, ExtraStepsF);
159   TM.Options.Reciprocals.setDefaults("divd", false, ExtraStepsD);
160   TM.Options.Reciprocals.setDefaults("vec-divf", false, ExtraStepsF);
161   TM.Options.Reciprocals.setDefaults("vec-divd", false, ExtraStepsD);
162 }
163 
164 /// TargetMachine ctor - Create an AArch64 architecture model.
165 ///
166 AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
167                                            StringRef CPU, StringRef FS,
168                                            const TargetOptions &Options,
169                                            Reloc::Model RM, CodeModel::Model CM,
170                                            CodeGenOpt::Level OL,
171                                            bool LittleEndian)
172     // This nested ternary is horrible, but DL needs to be properly
173     // initialized before TLInfo is constructed.
174     : LLVMTargetMachine(T, computeDataLayout(TT, LittleEndian), TT, CPU, FS,
175                         Options, RM, CM, OL),
176       TLOF(createTLOF(getTargetTriple())),
177       Subtarget(TT, CPU, FS, *this, LittleEndian) {
178   initReciprocals(*this, Subtarget);
179   initAsmInfo();
180 }
181 
182 AArch64TargetMachine::~AArch64TargetMachine() {}
183 
184 #ifdef LLVM_BUILD_GLOBAL_ISEL
185 namespace {
186 struct AArch64GISelActualAccessor : public GISelAccessor {
187   std::unique_ptr<CallLowering> CallLoweringInfo;
188   std::unique_ptr<RegisterBankInfo> RegBankInfo;
189   const CallLowering *getCallLowering() const override {
190     return CallLoweringInfo.get();
191   }
192   const RegisterBankInfo *getRegBankInfo() const override {
193     return RegBankInfo.get();
194   }
195 };
196 } // End anonymous namespace.
197 #endif
198 
199 const AArch64Subtarget *
200 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
201   Attribute CPUAttr = F.getFnAttribute("target-cpu");
202   Attribute FSAttr = F.getFnAttribute("target-features");
203 
204   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
205                         ? CPUAttr.getValueAsString().str()
206                         : TargetCPU;
207   std::string FS = !FSAttr.hasAttribute(Attribute::None)
208                        ? FSAttr.getValueAsString().str()
209                        : TargetFS;
210 
211   auto &I = SubtargetMap[CPU + FS];
212   if (!I) {
213     // This needs to be done before we create a new subtarget since any
214     // creation will depend on the TM and the code generation flags on the
215     // function that reside in TargetOptions.
216     resetTargetOptions(F);
217     I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
218                                             Subtarget.isLittleEndian());
219 #ifndef LLVM_BUILD_GLOBAL_ISEL
220    GISelAccessor *GISel = new GISelAccessor();
221 #else
222     AArch64GISelActualAccessor *GISel =
223         new AArch64GISelActualAccessor();
224     GISel->CallLoweringInfo.reset(
225         new AArch64CallLowering(*I->getTargetLowering()));
226     GISel->RegBankInfo.reset(
227         new AArch64RegisterBankInfo(*I->getRegisterInfo()));
228 #endif
229     I->setGISelAccessor(*GISel);
230   }
231   return I.get();
232 }
233 
234 void AArch64leTargetMachine::anchor() { }
235 
236 AArch64leTargetMachine::AArch64leTargetMachine(
237     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
238     const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
239     CodeGenOpt::Level OL)
240     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
241 
242 void AArch64beTargetMachine::anchor() { }
243 
244 AArch64beTargetMachine::AArch64beTargetMachine(
245     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
246     const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
247     CodeGenOpt::Level OL)
248     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
249 
250 namespace {
251 /// AArch64 Code Generator Pass Configuration Options.
252 class AArch64PassConfig : public TargetPassConfig {
253 public:
254   AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
255       : TargetPassConfig(TM, PM) {
256     if (TM->getOptLevel() != CodeGenOpt::None)
257       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
258   }
259 
260   AArch64TargetMachine &getAArch64TargetMachine() const {
261     return getTM<AArch64TargetMachine>();
262   }
263 
264   void addIRPasses()  override;
265   bool addPreISel() override;
266   bool addInstSelector() override;
267 #ifdef LLVM_BUILD_GLOBAL_ISEL
268   bool addIRTranslator() override;
269   bool addRegBankSelect() override;
270 #endif
271   bool addILPOpts() override;
272   void addPreRegAlloc() override;
273   void addPostRegAlloc() override;
274   void addPreSched2() override;
275   void addPreEmitPass() override;
276 };
277 } // namespace
278 
279 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
280   return TargetIRAnalysis([this](const Function &F) {
281     return TargetTransformInfo(AArch64TTIImpl(this, F));
282   });
283 }
284 
285 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
286   return new AArch64PassConfig(this, PM);
287 }
288 
289 void AArch64PassConfig::addIRPasses() {
290   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
291   // ourselves.
292   addPass(createAtomicExpandPass(TM));
293 
294   // Cmpxchg instructions are often used with a subsequent comparison to
295   // determine whether it succeeded. We can exploit existing control-flow in
296   // ldrex/strex loops to simplify this, but it needs tidying up.
297   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
298     addPass(createCFGSimplificationPass());
299 
300   // Run LoopDataPrefetch for Cyclone (the only subtarget that defines a
301   // non-zero getPrefetchDistance).
302   //
303   // Run this before LSR to remove the multiplies involved in computing the
304   // pointer values N iterations ahead.
305   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoopDataPrefetch)
306     addPass(createLoopDataPrefetchPass());
307 
308   TargetPassConfig::addIRPasses();
309 
310   // Match interleaved memory accesses to ldN/stN intrinsics.
311   if (TM->getOptLevel() != CodeGenOpt::None)
312     addPass(createInterleavedAccessPass(TM));
313 
314   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
315     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
316     // and lower a GEP with multiple indices to either arithmetic operations or
317     // multiple GEPs with single index.
318     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
319     // Call EarlyCSE pass to find and remove subexpressions in the lowered
320     // result.
321     addPass(createEarlyCSEPass());
322     // Do loop invariant code motion in case part of the lowered result is
323     // invariant.
324     addPass(createLICMPass());
325   }
326 }
327 
328 // Pass Pipeline Configuration
329 bool AArch64PassConfig::addPreISel() {
330   // Run promote constant before global merge, so that the promoted constants
331   // get a chance to be merged
332   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
333     addPass(createAArch64PromoteConstantPass());
334   // FIXME: On AArch64, this depends on the type.
335   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
336   // and the offset has to be a multiple of the related size in bytes.
337   if ((TM->getOptLevel() != CodeGenOpt::None &&
338        EnableGlobalMerge == cl::BOU_UNSET) ||
339       EnableGlobalMerge == cl::BOU_TRUE) {
340     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
341                                (EnableGlobalMerge == cl::BOU_UNSET);
342     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
343   }
344 
345   if (TM->getOptLevel() != CodeGenOpt::None)
346     addPass(createAArch64AddressTypePromotionPass());
347 
348   return false;
349 }
350 
351 bool AArch64PassConfig::addInstSelector() {
352   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
353 
354   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
355   // references to _TLS_MODULE_BASE_ as possible.
356   if (TM->getTargetTriple().isOSBinFormatELF() &&
357       getOptLevel() != CodeGenOpt::None)
358     addPass(createAArch64CleanupLocalDynamicTLSPass());
359 
360   return false;
361 }
362 
363 #ifdef LLVM_BUILD_GLOBAL_ISEL
364 bool AArch64PassConfig::addIRTranslator() {
365   addPass(new IRTranslator());
366   return false;
367 }
368 bool AArch64PassConfig::addRegBankSelect() {
369   addPass(new RegBankSelect());
370   return false;
371 }
372 #endif
373 
374 bool AArch64PassConfig::addILPOpts() {
375   if (EnableCondOpt)
376     addPass(createAArch64ConditionOptimizerPass());
377   if (EnableCCMP)
378     addPass(createAArch64ConditionalCompares());
379   if (EnableMCR)
380     addPass(&MachineCombinerID);
381   if (EnableEarlyIfConversion)
382     addPass(&EarlyIfConverterID);
383   if (EnableStPairSuppress)
384     addPass(createAArch64StorePairSuppressPass());
385   return true;
386 }
387 
388 void AArch64PassConfig::addPreRegAlloc() {
389   // Use AdvSIMD scalar instructions whenever profitable.
390   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
391     addPass(createAArch64AdvSIMDScalar());
392     // The AdvSIMD pass may produce copies that can be rewritten to
393     // be register coaleascer friendly.
394     addPass(&PeepholeOptimizerID);
395   }
396 }
397 
398 void AArch64PassConfig::addPostRegAlloc() {
399   // Remove redundant copy instructions.
400   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
401     addPass(createAArch64RedundantCopyEliminationPass());
402 
403   // Change dead register definitions to refer to the zero register.
404   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
405     addPass(createAArch64DeadRegisterDefinitions());
406   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
407     // Improve performance for some FP/SIMD code for A57.
408     addPass(createAArch64A57FPLoadBalancing());
409 }
410 
411 void AArch64PassConfig::addPreSched2() {
412   // Expand some pseudo instructions to allow proper scheduling.
413   addPass(createAArch64ExpandPseudoPass());
414   // Use load/store pair instructions when possible.
415   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
416     addPass(createAArch64LoadStoreOptimizationPass());
417 }
418 
419 void AArch64PassConfig::addPreEmitPass() {
420   if (EnableA53Fix835769)
421     addPass(createAArch64A53Fix835769());
422   // Relax conditional branch instructions if they're otherwise out of
423   // range of their destination.
424   addPass(createAArch64BranchRelaxation());
425   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
426       TM->getTargetTriple().isOSBinFormatMachO())
427     addPass(createAArch64CollectLOHPass());
428 }
429