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