]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
Import zstandard 1.1.4 in base
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 "AArch64CallLowering.h"
15 #include "AArch64InstructionSelector.h"
16 #include "AArch64LegalizerInfo.h"
17 #include "AArch64RegisterBankInfo.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "AArch64TargetTransformInfo.h"
22 #include "MCTargetDesc/AArch64MCTargetDesc.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/CodeGen/GlobalISel/GISelAccessor.h"
27 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
28 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
29 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
30 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
31 #include "llvm/CodeGen/MachineScheduler.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/IR/Attributes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/MC/MCTargetOptions.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CodeGen.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include <memory>
45 #include <string>
46
47 using namespace llvm;
48
49 static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
50                                 cl::desc("Enable the CCMP formation pass"),
51                                 cl::init(true), cl::Hidden);
52
53 static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
54                                cl::desc("Enable the machine combiner pass"),
55                                cl::init(true), cl::Hidden);
56
57 static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
58                                           cl::desc("Suppress STP for AArch64"),
59                                           cl::init(true), cl::Hidden);
60
61 static cl::opt<bool> EnableAdvSIMDScalar(
62     "aarch64-enable-simd-scalar",
63     cl::desc("Enable use of AdvSIMD scalar integer instructions"),
64     cl::init(false), cl::Hidden);
65
66 static cl::opt<bool>
67     EnablePromoteConstant("aarch64-enable-promote-const",
68                           cl::desc("Enable the promote constant pass"),
69                           cl::init(true), cl::Hidden);
70
71 static cl::opt<bool> EnableCollectLOH(
72     "aarch64-enable-collect-loh",
73     cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
74     cl::init(true), cl::Hidden);
75
76 static cl::opt<bool>
77     EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
78                                   cl::desc("Enable the pass that removes dead"
79                                            " definitons and replaces stores to"
80                                            " them with stores to the zero"
81                                            " register"),
82                                   cl::init(true));
83
84 static cl::opt<bool> EnableRedundantCopyElimination(
85     "aarch64-enable-copyelim",
86     cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
87     cl::Hidden);
88
89 static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
90                                         cl::desc("Enable the load/store pair"
91                                                  " optimization pass"),
92                                         cl::init(true), cl::Hidden);
93
94 static cl::opt<bool> EnableAtomicTidy(
95     "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
96     cl::desc("Run SimplifyCFG after expanding atomic operations"
97              " to make use of cmpxchg flow-based information"),
98     cl::init(true));
99
100 static cl::opt<bool>
101 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
102                         cl::desc("Run early if-conversion"),
103                         cl::init(true));
104
105 static cl::opt<bool>
106     EnableCondOpt("aarch64-enable-condopt",
107                   cl::desc("Enable the condition optimizer pass"),
108                   cl::init(true), cl::Hidden);
109
110 static cl::opt<bool>
111 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
112                 cl::desc("Work around Cortex-A53 erratum 835769"),
113                 cl::init(false));
114
115 static cl::opt<bool>
116     EnableAddressTypePromotion("aarch64-enable-type-promotion", cl::Hidden,
117                                cl::desc("Enable the type promotion pass"),
118                                cl::init(true));
119
120 static cl::opt<bool>
121     EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
122                  cl::desc("Enable optimizations on complex GEPs"),
123                  cl::init(false));
124
125 static cl::opt<bool>
126     BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true),
127                      cl::desc("Relax out of range conditional branches"));
128
129 // FIXME: Unify control over GlobalMerge.
130 static cl::opt<cl::boolOrDefault>
131     EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
132                       cl::desc("Enable the global merge pass"));
133
134 static cl::opt<bool>
135     EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
136                            cl::desc("Enable the loop data prefetch pass"),
137                            cl::init(true));
138
139 extern "C" void LLVMInitializeAArch64Target() {
140   // Register the target.
141   RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
142   RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
143   RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
144   auto PR = PassRegistry::getPassRegistry();
145   initializeGlobalISel(*PR);
146   initializeAArch64A53Fix835769Pass(*PR);
147   initializeAArch64A57FPLoadBalancingPass(*PR);
148   initializeAArch64AddressTypePromotionPass(*PR);
149   initializeAArch64AdvSIMDScalarPass(*PR);
150   initializeAArch64CollectLOHPass(*PR);
151   initializeAArch64ConditionalComparesPass(*PR);
152   initializeAArch64ConditionOptimizerPass(*PR);
153   initializeAArch64DeadRegisterDefinitionsPass(*PR);
154   initializeAArch64ExpandPseudoPass(*PR);
155   initializeAArch64LoadStoreOptPass(*PR);
156   initializeAArch64VectorByElementOptPass(*PR);
157   initializeAArch64PromoteConstantPass(*PR);
158   initializeAArch64RedundantCopyEliminationPass(*PR);
159   initializeAArch64StorePairSuppressPass(*PR);
160   initializeLDTLSCleanupPass(*PR);
161 }
162
163 //===----------------------------------------------------------------------===//
164 // AArch64 Lowering public interface.
165 //===----------------------------------------------------------------------===//
166 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
167   if (TT.isOSBinFormatMachO())
168     return llvm::make_unique<AArch64_MachoTargetObjectFile>();
169
170   return llvm::make_unique<AArch64_ELFTargetObjectFile>();
171 }
172
173 // Helper function to build a DataLayout string
174 static std::string computeDataLayout(const Triple &TT,
175                                      const MCTargetOptions &Options,
176                                      bool LittleEndian) {
177   if (Options.getABIName() == "ilp32")
178     return "e-m:e-p:32:32-i8:8-i16:16-i64:64-S128";
179   if (TT.isOSBinFormatMachO())
180     return "e-m:o-i64:64-i128:128-n32:64-S128";
181   if (LittleEndian)
182     return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
183   return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
184 }
185
186 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
187                                            Optional<Reloc::Model> RM) {
188   // AArch64 Darwin is always PIC.
189   if (TT.isOSDarwin())
190     return Reloc::PIC_;
191   // On ELF platforms the default static relocation model has a smart enough
192   // linker to cope with referencing external symbols defined in a shared
193   // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
194   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
195     return Reloc::Static;
196   return *RM;
197 }
198
199 /// Create an AArch64 architecture model.
200 ///
201 AArch64TargetMachine::AArch64TargetMachine(
202     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
203     const TargetOptions &Options, Optional<Reloc::Model> RM,
204     CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian)
205     // This nested ternary is horrible, but DL needs to be properly
206     // initialized before TLInfo is constructed.
207     : LLVMTargetMachine(T, computeDataLayout(TT, Options.MCOptions,
208                                              LittleEndian),
209                         TT, CPU, FS, Options,
210                         getEffectiveRelocModel(TT, RM), CM, OL),
211       TLOF(createTLOF(getTargetTriple())),
212       isLittle(LittleEndian) {
213   initAsmInfo();
214 }
215
216 AArch64TargetMachine::~AArch64TargetMachine() = default;
217
218 #ifdef LLVM_BUILD_GLOBAL_ISEL
219 namespace {
220
221 struct AArch64GISelActualAccessor : public GISelAccessor {
222   std::unique_ptr<CallLowering> CallLoweringInfo;
223   std::unique_ptr<InstructionSelector> InstSelector;
224   std::unique_ptr<LegalizerInfo> Legalizer;
225   std::unique_ptr<RegisterBankInfo> RegBankInfo;
226
227   const CallLowering *getCallLowering() const override {
228     return CallLoweringInfo.get();
229   }
230
231   const InstructionSelector *getInstructionSelector() const override {
232     return InstSelector.get();
233   }
234
235   const LegalizerInfo *getLegalizerInfo() const override {
236     return Legalizer.get();
237   }
238
239   const RegisterBankInfo *getRegBankInfo() const override {
240     return RegBankInfo.get();
241   }
242 };
243
244 } // end anonymous namespace
245 #endif
246
247 const AArch64Subtarget *
248 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
249   Attribute CPUAttr = F.getFnAttribute("target-cpu");
250   Attribute FSAttr = F.getFnAttribute("target-features");
251
252   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
253                         ? CPUAttr.getValueAsString().str()
254                         : TargetCPU;
255   std::string FS = !FSAttr.hasAttribute(Attribute::None)
256                        ? FSAttr.getValueAsString().str()
257                        : TargetFS;
258
259   auto &I = SubtargetMap[CPU + FS];
260   if (!I) {
261     // This needs to be done before we create a new subtarget since any
262     // creation will depend on the TM and the code generation flags on the
263     // function that reside in TargetOptions.
264     resetTargetOptions(F);
265     I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
266                                             isLittle);
267 #ifndef LLVM_BUILD_GLOBAL_ISEL
268     GISelAccessor *GISel = new GISelAccessor();
269 #else
270     AArch64GISelActualAccessor *GISel =
271         new AArch64GISelActualAccessor();
272     GISel->CallLoweringInfo.reset(
273         new AArch64CallLowering(*I->getTargetLowering()));
274     GISel->Legalizer.reset(new AArch64LegalizerInfo());
275
276     auto *RBI = new AArch64RegisterBankInfo(*I->getRegisterInfo());
277
278     // FIXME: At this point, we can't rely on Subtarget having RBI.
279     // It's awkward to mix passing RBI and the Subtarget; should we pass
280     // TII/TRI as well?
281     GISel->InstSelector.reset(new AArch64InstructionSelector(*this, *I, *RBI));
282
283     GISel->RegBankInfo.reset(RBI);
284 #endif
285     I->setGISelAccessor(*GISel);
286   }
287   return I.get();
288 }
289
290 void AArch64leTargetMachine::anchor() { }
291
292 AArch64leTargetMachine::AArch64leTargetMachine(
293     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
294     const TargetOptions &Options, Optional<Reloc::Model> RM,
295     CodeModel::Model CM, CodeGenOpt::Level OL)
296     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
297
298 void AArch64beTargetMachine::anchor() { }
299
300 AArch64beTargetMachine::AArch64beTargetMachine(
301     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
302     const TargetOptions &Options, Optional<Reloc::Model> RM,
303     CodeModel::Model CM, CodeGenOpt::Level OL)
304     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
305
306 namespace {
307
308 /// AArch64 Code Generator Pass Configuration Options.
309 class AArch64PassConfig : public TargetPassConfig {
310 public:
311   AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
312       : TargetPassConfig(TM, PM) {
313     if (TM->getOptLevel() != CodeGenOpt::None)
314       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
315   }
316
317   AArch64TargetMachine &getAArch64TargetMachine() const {
318     return getTM<AArch64TargetMachine>();
319   }
320
321   ScheduleDAGInstrs *
322   createMachineScheduler(MachineSchedContext *C) const override {
323     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
324     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
325     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
326     DAG->addMutation(createMacroFusionDAGMutation(DAG->TII));
327     return DAG;
328   }
329
330   void addIRPasses()  override;
331   bool addPreISel() override;
332   bool addInstSelector() override;
333 #ifdef LLVM_BUILD_GLOBAL_ISEL
334   bool addIRTranslator() override;
335   bool addLegalizeMachineIR() override;
336   bool addRegBankSelect() override;
337   bool addGlobalInstructionSelect() override;
338 #endif
339   bool addILPOpts() override;
340   void addPreRegAlloc() override;
341   void addPostRegAlloc() override;
342   void addPreSched2() override;
343   void addPreEmitPass() override;
344 };
345
346 } // end anonymous namespace
347
348 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
349   return TargetIRAnalysis([this](const Function &F) {
350     return TargetTransformInfo(AArch64TTIImpl(this, F));
351   });
352 }
353
354 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
355   return new AArch64PassConfig(this, PM);
356 }
357
358 void AArch64PassConfig::addIRPasses() {
359   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
360   // ourselves.
361   addPass(createAtomicExpandPass(TM));
362
363   // Cmpxchg instructions are often used with a subsequent comparison to
364   // determine whether it succeeded. We can exploit existing control-flow in
365   // ldrex/strex loops to simplify this, but it needs tidying up.
366   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
367     addPass(createCFGSimplificationPass());
368
369   // Run LoopDataPrefetch
370   //
371   // Run this before LSR to remove the multiplies involved in computing the
372   // pointer values N iterations ahead.
373   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoopDataPrefetch)
374     addPass(createLoopDataPrefetchPass());
375
376   TargetPassConfig::addIRPasses();
377
378   // Match interleaved memory accesses to ldN/stN intrinsics.
379   if (TM->getOptLevel() != CodeGenOpt::None)
380     addPass(createInterleavedAccessPass(TM));
381
382   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
383     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
384     // and lower a GEP with multiple indices to either arithmetic operations or
385     // multiple GEPs with single index.
386     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
387     // Call EarlyCSE pass to find and remove subexpressions in the lowered
388     // result.
389     addPass(createEarlyCSEPass());
390     // Do loop invariant code motion in case part of the lowered result is
391     // invariant.
392     addPass(createLICMPass());
393   }
394 }
395
396 // Pass Pipeline Configuration
397 bool AArch64PassConfig::addPreISel() {
398   // Run promote constant before global merge, so that the promoted constants
399   // get a chance to be merged
400   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
401     addPass(createAArch64PromoteConstantPass());
402   // FIXME: On AArch64, this depends on the type.
403   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
404   // and the offset has to be a multiple of the related size in bytes.
405   if ((TM->getOptLevel() != CodeGenOpt::None &&
406        EnableGlobalMerge == cl::BOU_UNSET) ||
407       EnableGlobalMerge == cl::BOU_TRUE) {
408     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
409                                (EnableGlobalMerge == cl::BOU_UNSET);
410     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
411   }
412
413   if (TM->getOptLevel() != CodeGenOpt::None && EnableAddressTypePromotion)
414     addPass(createAArch64AddressTypePromotionPass());
415
416   return false;
417 }
418
419 bool AArch64PassConfig::addInstSelector() {
420   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
421
422   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
423   // references to _TLS_MODULE_BASE_ as possible.
424   if (TM->getTargetTriple().isOSBinFormatELF() &&
425       getOptLevel() != CodeGenOpt::None)
426     addPass(createAArch64CleanupLocalDynamicTLSPass());
427
428   return false;
429 }
430
431 #ifdef LLVM_BUILD_GLOBAL_ISEL
432 bool AArch64PassConfig::addIRTranslator() {
433   addPass(new IRTranslator());
434   return false;
435 }
436
437 bool AArch64PassConfig::addLegalizeMachineIR() {
438   addPass(new Legalizer());
439   return false;
440 }
441
442 bool AArch64PassConfig::addRegBankSelect() {
443   addPass(new RegBankSelect());
444   return false;
445 }
446
447 bool AArch64PassConfig::addGlobalInstructionSelect() {
448   addPass(new InstructionSelect());
449   return false;
450 }
451 #endif
452
453 bool AArch64PassConfig::addILPOpts() {
454   if (EnableCondOpt)
455     addPass(createAArch64ConditionOptimizerPass());
456   if (EnableCCMP)
457     addPass(createAArch64ConditionalCompares());
458   if (EnableMCR)
459     addPass(&MachineCombinerID);
460   if (EnableEarlyIfConversion)
461     addPass(&EarlyIfConverterID);
462   if (EnableStPairSuppress)
463     addPass(createAArch64StorePairSuppressPass());
464   addPass(createAArch64VectorByElementOptPass());
465   return true;
466 }
467
468 void AArch64PassConfig::addPreRegAlloc() {
469   // Change dead register definitions to refer to the zero register.
470   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
471     addPass(createAArch64DeadRegisterDefinitions());
472
473   // Use AdvSIMD scalar instructions whenever profitable.
474   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
475     addPass(createAArch64AdvSIMDScalar());
476     // The AdvSIMD pass may produce copies that can be rewritten to
477     // be register coaleascer friendly.
478     addPass(&PeepholeOptimizerID);
479   }
480 }
481
482 void AArch64PassConfig::addPostRegAlloc() {
483   // Remove redundant copy instructions.
484   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
485     addPass(createAArch64RedundantCopyEliminationPass());
486
487   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
488     // Improve performance for some FP/SIMD code for A57.
489     addPass(createAArch64A57FPLoadBalancing());
490 }
491
492 void AArch64PassConfig::addPreSched2() {
493   // Expand some pseudo instructions to allow proper scheduling.
494   addPass(createAArch64ExpandPseudoPass());
495   // Use load/store pair instructions when possible.
496   if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
497     addPass(createAArch64LoadStoreOptimizationPass());
498 }
499
500 void AArch64PassConfig::addPreEmitPass() {
501   if (EnableA53Fix835769)
502     addPass(createAArch64A53Fix835769());
503   // Relax conditional branch instructions if they're otherwise out of
504   // range of their destination.
505   if (BranchRelaxation)
506     addPass(&BranchRelaxationPassID);
507
508   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
509       TM->getTargetTriple().isOSBinFormatMachO())
510     addPass(createAArch64CollectLOHPass());
511 }