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   initializeAArch64LoadStoreOptPass(*PR);
120 }
121 
122 //===----------------------------------------------------------------------===//
123 // AArch64 Lowering public interface.
124 //===----------------------------------------------------------------------===//
125 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
126   if (TT.isOSBinFormatMachO())
127     return make_unique<AArch64_MachoTargetObjectFile>();
128 
129   return make_unique<AArch64_ELFTargetObjectFile>();
130 }
131 
132 // Helper function to build a DataLayout string
133 static std::string computeDataLayout(const Triple &TT, bool LittleEndian) {
134   if (TT.isOSBinFormatMachO())
135     return "e-m:o-i64:64-i128:128-n32:64-S128";
136   if (LittleEndian)
137     return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
138   return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
139 }
140 
141 // Helper function to set up the defaults for reciprocals.
142 static void initReciprocals(AArch64TargetMachine& TM, AArch64Subtarget& ST)
143 {
144   // For the estimates, convergence is quadratic, so essentially the number of
145   // digits is doubled after each iteration. ARMv8, the minimum architected
146   // accuracy of the initial estimate is 2^-8.  Therefore, the number of extra
147   // steps to refine the result for float (23 mantissa bits) and for double
148   // (52 mantissa bits) are 2 and 3, respectively.
149   unsigned ExtraStepsF = 2,
150            ExtraStepsD = ExtraStepsF + 1;
151   bool UseRsqrt = ST.useRSqrt();
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 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
165                                            Optional<Reloc::Model> RM) {
166   // AArch64 Darwin is always PIC.
167   if (TT.isOSDarwin())
168     return Reloc::PIC_;
169   // On ELF platforms the default static relocation model has a smart enough
170   // linker to cope with referencing external symbols defined in a shared
171   // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
172   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
173     return Reloc::Static;
174   return *RM;
175 }
176 
177 /// Create an AArch64 architecture model.
178 ///
179 AArch64TargetMachine::AArch64TargetMachine(
180     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
181     const TargetOptions &Options, Optional<Reloc::Model> RM,
182     CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian)
183     // This nested ternary is horrible, but DL needs to be properly
184     // initialized before TLInfo is constructed.
185     : LLVMTargetMachine(T, computeDataLayout(TT, LittleEndian), TT, CPU, FS,
186                         Options, getEffectiveRelocModel(TT, RM), CM, OL),
187       TLOF(createTLOF(getTargetTriple())),
188       Subtarget(TT, CPU, FS, *this, LittleEndian) {
189   initReciprocals(*this, Subtarget);
190   initAsmInfo();
191 }
192 
193 AArch64TargetMachine::~AArch64TargetMachine() {}
194 
195 #ifdef LLVM_BUILD_GLOBAL_ISEL
196 namespace {
197 struct AArch64GISelActualAccessor : public GISelAccessor {
198   std::unique_ptr<CallLowering> CallLoweringInfo;
199   std::unique_ptr<RegisterBankInfo> RegBankInfo;
200   const CallLowering *getCallLowering() const override {
201     return CallLoweringInfo.get();
202   }
203   const RegisterBankInfo *getRegBankInfo() const override {
204     return RegBankInfo.get();
205   }
206 };
207 } // End anonymous namespace.
208 #endif
209 
210 const AArch64Subtarget *
211 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
212   Attribute CPUAttr = F.getFnAttribute("target-cpu");
213   Attribute FSAttr = F.getFnAttribute("target-features");
214 
215   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
216                         ? CPUAttr.getValueAsString().str()
217                         : TargetCPU;
218   std::string FS = !FSAttr.hasAttribute(Attribute::None)
219                        ? FSAttr.getValueAsString().str()
220                        : TargetFS;
221 
222   auto &I = SubtargetMap[CPU + FS];
223   if (!I) {
224     // This needs to be done before we create a new subtarget since any
225     // creation will depend on the TM and the code generation flags on the
226     // function that reside in TargetOptions.
227     resetTargetOptions(F);
228     I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
229                                             Subtarget.isLittleEndian());
230 #ifndef LLVM_BUILD_GLOBAL_ISEL
231    GISelAccessor *GISel = new GISelAccessor();
232 #else
233     AArch64GISelActualAccessor *GISel =
234         new AArch64GISelActualAccessor();
235     GISel->CallLoweringInfo.reset(
236         new AArch64CallLowering(*I->getTargetLowering()));
237     GISel->RegBankInfo.reset(
238         new AArch64RegisterBankInfo(*I->getRegisterInfo()));
239 #endif
240     I->setGISelAccessor(*GISel);
241   }
242   return I.get();
243 }
244 
245 void AArch64leTargetMachine::anchor() { }
246 
247 AArch64leTargetMachine::AArch64leTargetMachine(
248     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
249     const TargetOptions &Options, Optional<Reloc::Model> RM,
250     CodeModel::Model CM, CodeGenOpt::Level OL)
251     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
252 
253 void AArch64beTargetMachine::anchor() { }
254 
255 AArch64beTargetMachine::AArch64beTargetMachine(
256     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
257     const TargetOptions &Options, Optional<Reloc::Model> RM,
258     CodeModel::Model CM, CodeGenOpt::Level OL)
259     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
260 
261 namespace {
262 /// AArch64 Code Generator Pass Configuration Options.
263 class AArch64PassConfig : public TargetPassConfig {
264 public:
265   AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
266       : TargetPassConfig(TM, PM) {
267     if (TM->getOptLevel() != CodeGenOpt::None)
268       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
269   }
270 
271   AArch64TargetMachine &getAArch64TargetMachine() const {
272     return getTM<AArch64TargetMachine>();
273   }
274 
275   void addIRPasses()  override;
276   bool addPreISel() override;
277   bool addInstSelector() override;
278 #ifdef LLVM_BUILD_GLOBAL_ISEL
279   bool addIRTranslator() override;
280   bool addRegBankSelect() override;
281 #endif
282   bool addILPOpts() override;
283   void addPreRegAlloc() override;
284   void addPostRegAlloc() override;
285   void addPreSched2() override;
286   void addPreEmitPass() override;
287 };
288 } // namespace
289 
290 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
291   return TargetIRAnalysis([this](const Function &F) {
292     return TargetTransformInfo(AArch64TTIImpl(this, F));
293   });
294 }
295 
296 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
297   return new AArch64PassConfig(this, PM);
298 }
299 
300 void AArch64PassConfig::addIRPasses() {
301   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
302   // ourselves.
303   addPass(createAtomicExpandPass(TM));
304 
305   // Cmpxchg instructions are often used with a subsequent comparison to
306   // determine whether it succeeded. We can exploit existing control-flow in
307   // ldrex/strex loops to simplify this, but it needs tidying up.
308   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
309     addPass(createCFGSimplificationPass());
310 
311   // Run LoopDataPrefetch
312   //
313   // Run this before LSR to remove the multiplies involved in computing the
314   // pointer values N iterations ahead.
315   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoopDataPrefetch)
316     addPass(createLoopDataPrefetchPass());
317 
318   TargetPassConfig::addIRPasses();
319 
320   // Match interleaved memory accesses to ldN/stN intrinsics.
321   if (TM->getOptLevel() != CodeGenOpt::None)
322     addPass(createInterleavedAccessPass(TM));
323 
324   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
325     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
326     // and lower a GEP with multiple indices to either arithmetic operations or
327     // multiple GEPs with single index.
328     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
329     // Call EarlyCSE pass to find and remove subexpressions in the lowered
330     // result.
331     addPass(createEarlyCSEPass());
332     // Do loop invariant code motion in case part of the lowered result is
333     // invariant.
334     addPass(createLICMPass());
335   }
336 }
337 
338 // Pass Pipeline Configuration
339 bool AArch64PassConfig::addPreISel() {
340   // Run promote constant before global merge, so that the promoted constants
341   // get a chance to be merged
342   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
343     addPass(createAArch64PromoteConstantPass());
344   // FIXME: On AArch64, this depends on the type.
345   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
346   // and the offset has to be a multiple of the related size in bytes.
347   if ((TM->getOptLevel() != CodeGenOpt::None &&
348        EnableGlobalMerge == cl::BOU_UNSET) ||
349       EnableGlobalMerge == cl::BOU_TRUE) {
350     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
351                                (EnableGlobalMerge == cl::BOU_UNSET);
352     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
353   }
354 
355   if (TM->getOptLevel() != CodeGenOpt::None)
356     addPass(createAArch64AddressTypePromotionPass());
357 
358   return false;
359 }
360 
361 bool AArch64PassConfig::addInstSelector() {
362   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
363 
364   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
365   // references to _TLS_MODULE_BASE_ as possible.
366   if (TM->getTargetTriple().isOSBinFormatELF() &&
367       getOptLevel() != CodeGenOpt::None)
368     addPass(createAArch64CleanupLocalDynamicTLSPass());
369 
370   return false;
371 }
372 
373 #ifdef LLVM_BUILD_GLOBAL_ISEL
374 bool AArch64PassConfig::addIRTranslator() {
375   addPass(new IRTranslator());
376   return false;
377 }
378 bool AArch64PassConfig::addRegBankSelect() {
379   addPass(new RegBankSelect());
380   return false;
381 }
382 #endif
383 
384 bool AArch64PassConfig::addILPOpts() {
385   if (EnableCondOpt)
386     addPass(createAArch64ConditionOptimizerPass());
387   if (EnableCCMP)
388     addPass(createAArch64ConditionalCompares());
389   if (EnableMCR)
390     addPass(&MachineCombinerID);
391   if (EnableEarlyIfConversion)
392     addPass(&EarlyIfConverterID);
393   if (EnableStPairSuppress)
394     addPass(createAArch64StorePairSuppressPass());
395   return true;
396 }
397 
398 void AArch64PassConfig::addPreRegAlloc() {
399   // Use AdvSIMD scalar instructions whenever profitable.
400   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
401     addPass(createAArch64AdvSIMDScalar());
402     // The AdvSIMD pass may produce copies that can be rewritten to
403     // be register coaleascer friendly.
404     addPass(&PeepholeOptimizerID);
405   }
406 }
407 
408 void AArch64PassConfig::addPostRegAlloc() {
409   // Remove redundant copy instructions.
410   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
411     addPass(createAArch64RedundantCopyEliminationPass());
412 
413   // Change dead register definitions to refer to the zero register.
414   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
415     addPass(createAArch64DeadRegisterDefinitions());
416   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
417     // Improve performance for some FP/SIMD code for A57.
418     addPass(createAArch64A57FPLoadBalancing());
419 }
420 
421 void AArch64PassConfig::addPreSched2() {
422   // Expand some pseudo instructions to allow proper scheduling.
423   addPass(createAArch64ExpandPseudoPass());
424   // Use load/store pair instructions when possible.
425   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
426     addPass(createAArch64LoadStoreOptimizationPass());
427 }
428 
429 void AArch64PassConfig::addPreEmitPass() {
430   if (EnableA53Fix835769)
431     addPass(createAArch64A53Fix835769());
432   // Relax conditional branch instructions if they're otherwise out of
433   // range of their destination.
434   addPass(createAArch64BranchRelaxation());
435   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
436       TM->getTargetTriple().isOSBinFormatMachO())
437     addPass(createAArch64CollectLOHPass());
438 }
439