]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r305145, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / ARM / ARMTargetMachine.cpp
1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
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 "ARM.h"
14 #include "ARMCallLowering.h"
15 #include "ARMLegalizerInfo.h"
16 #ifdef LLVM_BUILD_GLOBAL_ISEL
17 #include "ARMRegisterBankInfo.h"
18 #endif
19 #include "ARMSubtarget.h"
20 #include "ARMTargetMachine.h"
21 #include "ARMTargetObjectFile.h"
22 #include "ARMTargetTransformInfo.h"
23 #include "MCTargetDesc/ARMMCTargetDesc.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/CodeGen/ExecutionDepsFix.h"
30 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
31 #include "llvm/CodeGen/GlobalISel/GISelAccessor.h"
32 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
33 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
34 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
35 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
36 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
37 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
38 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineScheduler.h"
41 #include "llvm/CodeGen/Passes.h"
42 #include "llvm/CodeGen/TargetPassConfig.h"
43 #include "llvm/IR/Attributes.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/CodeGen.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/TargetParser.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Target/TargetLoweringObjectFile.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Transforms/Scalar.h"
55 #include <cassert>
56 #include <memory>
57 #include <string>
58
59 using namespace llvm;
60
61 static cl::opt<bool>
62 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
63                    cl::desc("Inhibit optimization of S->D register accesses on A15"),
64                    cl::init(false));
65
66 static cl::opt<bool>
67 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
68                  cl::desc("Run SimplifyCFG after expanding atomic operations"
69                           " to make use of cmpxchg flow-based information"),
70                  cl::init(true));
71
72 static cl::opt<bool>
73 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
74                       cl::desc("Enable ARM load/store optimization pass"),
75                       cl::init(true));
76
77 // FIXME: Unify control over GlobalMerge.
78 static cl::opt<cl::boolOrDefault>
79 EnableGlobalMerge("arm-global-merge", cl::Hidden,
80                   cl::desc("Enable the global merge pass"));
81
82 namespace llvm {
83   void initializeARMExecutionDepsFixPass(PassRegistry&);
84 }
85
86 extern "C" void LLVMInitializeARMTarget() {
87   // Register the target.
88   RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget());
89   RegisterTargetMachine<ARMLETargetMachine> A(getTheThumbLETarget());
90   RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget());
91   RegisterTargetMachine<ARMBETargetMachine> B(getTheThumbBETarget());
92
93   PassRegistry &Registry = *PassRegistry::getPassRegistry();
94   initializeGlobalISel(Registry);
95   initializeARMLoadStoreOptPass(Registry);
96   initializeARMPreAllocLoadStoreOptPass(Registry);
97   initializeARMConstantIslandsPass(Registry);
98   initializeARMExecutionDepsFixPass(Registry);
99 }
100
101 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
102   if (TT.isOSBinFormatMachO())
103     return llvm::make_unique<TargetLoweringObjectFileMachO>();
104   if (TT.isOSWindows())
105     return llvm::make_unique<TargetLoweringObjectFileCOFF>();
106   return llvm::make_unique<ARMElfTargetObjectFile>();
107 }
108
109 static ARMBaseTargetMachine::ARMABI
110 computeTargetABI(const Triple &TT, StringRef CPU,
111                  const TargetOptions &Options) {
112   if (Options.MCOptions.getABIName() == "aapcs16")
113     return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
114   else if (Options.MCOptions.getABIName().startswith("aapcs"))
115     return ARMBaseTargetMachine::ARM_ABI_AAPCS;
116   else if (Options.MCOptions.getABIName().startswith("apcs"))
117     return ARMBaseTargetMachine::ARM_ABI_APCS;
118
119   assert(Options.MCOptions.getABIName().empty() &&
120          "Unknown target-abi option!");
121
122   ARMBaseTargetMachine::ARMABI TargetABI =
123       ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
124
125   unsigned ArchKind = ARM::parseCPUArch(CPU);
126   StringRef ArchName = ARM::getArchName(ArchKind);
127   // FIXME: This is duplicated code from the front end and should be unified.
128   if (TT.isOSBinFormatMachO()) {
129     if (TT.getEnvironment() == Triple::EABI ||
130         (TT.getOS() == Triple::UnknownOS && TT.isOSBinFormatMachO()) ||
131         ARM::parseArchProfile(ArchName) == ARM::PK_M) {
132       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
133     } else if (TT.isWatchABI()) {
134       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS16;
135     } else {
136       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
137     }
138   } else if (TT.isOSWindows()) {
139     // FIXME: this is invalid for WindowsCE
140     TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
141   } else {
142     // Select the default based on the platform.
143     switch (TT.getEnvironment()) {
144     case Triple::Android:
145     case Triple::GNUEABI:
146     case Triple::GNUEABIHF:
147     case Triple::MuslEABI:
148     case Triple::MuslEABIHF:
149     case Triple::EABIHF:
150     case Triple::EABI:
151       TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
152       break;
153     case Triple::GNU:
154       TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
155       break;
156     default:
157       if (TT.isOSNetBSD())
158         TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
159       else
160         TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
161       break;
162     }
163   }
164
165   return TargetABI;
166 }
167
168 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
169                                      const TargetOptions &Options,
170                                      bool isLittle) {
171   auto ABI = computeTargetABI(TT, CPU, Options);
172   std::string Ret;
173
174   if (isLittle)
175     // Little endian.
176     Ret += "e";
177   else
178     // Big endian.
179     Ret += "E";
180
181   Ret += DataLayout::getManglingComponent(TT);
182
183   // Pointers are 32 bits and aligned to 32 bits.
184   Ret += "-p:32:32";
185
186   // ABIs other than APCS have 64 bit integers with natural alignment.
187   if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
188     Ret += "-i64:64";
189
190   // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
191   // bits, others to 64 bits. We always try to align to 64 bits.
192   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
193     Ret += "-f64:32:64";
194
195   // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
196   // to 64. We always ty to give them natural alignment.
197   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
198     Ret += "-v64:32:64-v128:32:128";
199   else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
200     Ret += "-v128:64:128";
201
202   // Try to align aggregates to 32 bits (the default is 64 bits, which has no
203   // particular hardware support on 32-bit ARM).
204   Ret += "-a:0:32";
205
206   // Integer registers are 32 bits.
207   Ret += "-n32";
208
209   // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
210   // aligned everywhere else.
211   if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
212     Ret += "-S128";
213   else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
214     Ret += "-S64";
215   else
216     Ret += "-S32";
217
218   return Ret;
219 }
220
221 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
222                                            Optional<Reloc::Model> RM) {
223   if (!RM.hasValue())
224     // Default relocation model on Darwin is PIC.
225     return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
226
227   if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
228     assert(TT.isOSBinFormatELF() &&
229            "ROPI/RWPI currently only supported for ELF");
230
231   // DynamicNoPIC is only used on darwin.
232   if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
233     return Reloc::Static;
234
235   return *RM;
236 }
237
238 /// Create an ARM architecture model.
239 ///
240 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
241                                            StringRef CPU, StringRef FS,
242                                            const TargetOptions &Options,
243                                            Optional<Reloc::Model> RM,
244                                            CodeModel::Model CM,
245                                            CodeGenOpt::Level OL, bool isLittle)
246     : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
247                         CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM,
248                         OL),
249       TargetABI(computeTargetABI(TT, CPU, Options)),
250       TLOF(createTLOF(getTargetTriple())),
251       Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
252
253   // Default to triple-appropriate float ABI
254   if (Options.FloatABIType == FloatABI::Default)
255     this->Options.FloatABIType =
256         Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
257
258   // Default to triple-appropriate EABI
259   if (Options.EABIVersion == EABI::Default ||
260       Options.EABIVersion == EABI::Unknown) {
261     // musl is compatible with glibc with regard to EABI version
262     if (Subtarget.isTargetGNUAEABI() || Subtarget.isTargetMuslAEABI())
263       this->Options.EABIVersion = EABI::GNU;
264     else
265       this->Options.EABIVersion = EABI::EABI5;
266   }
267
268   initAsmInfo();
269   if (!Subtarget.isThumb() && !Subtarget.hasARMOps())
270     report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
271                        "support ARM mode execution!");
272 }
273
274 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
275
276 #ifdef LLVM_BUILD_GLOBAL_ISEL
277 namespace {
278
279 struct ARMGISelActualAccessor : public GISelAccessor {
280   std::unique_ptr<CallLowering> CallLoweringInfo;
281   std::unique_ptr<InstructionSelector> InstSelector;
282   std::unique_ptr<LegalizerInfo> Legalizer;
283   std::unique_ptr<RegisterBankInfo> RegBankInfo;
284
285   const CallLowering *getCallLowering() const override {
286     return CallLoweringInfo.get();
287   }
288
289   const InstructionSelector *getInstructionSelector() const override {
290     return InstSelector.get();
291   }
292
293   const LegalizerInfo *getLegalizerInfo() const override {
294     return Legalizer.get();
295   }
296
297   const RegisterBankInfo *getRegBankInfo() const override {
298     return RegBankInfo.get();
299   }
300 };
301
302 } // end anonymous namespace
303 #endif
304
305 const ARMSubtarget *
306 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
307   Attribute CPUAttr = F.getFnAttribute("target-cpu");
308   Attribute FSAttr = F.getFnAttribute("target-features");
309
310   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
311                         ? CPUAttr.getValueAsString().str()
312                         : TargetCPU;
313   std::string FS = !FSAttr.hasAttribute(Attribute::None)
314                        ? FSAttr.getValueAsString().str()
315                        : TargetFS;
316
317   // FIXME: This is related to the code below to reset the target options,
318   // we need to know whether or not the soft float flag is set on the
319   // function before we can generate a subtarget. We also need to use
320   // it as a key for the subtarget since that can be the only difference
321   // between two functions.
322   bool SoftFloat =
323       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
324   // If the soft float attribute is set on the function turn on the soft float
325   // subtarget feature.
326   if (SoftFloat)
327     FS += FS.empty() ? "+soft-float" : ",+soft-float";
328
329   auto &I = SubtargetMap[CPU + FS];
330   if (!I) {
331     // This needs to be done before we create a new subtarget since any
332     // creation will depend on the TM and the code generation flags on the
333     // function that reside in TargetOptions.
334     resetTargetOptions(F);
335     I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
336
337 #ifndef LLVM_BUILD_GLOBAL_ISEL
338     GISelAccessor *GISel = new GISelAccessor();
339 #else
340     ARMGISelActualAccessor *GISel = new ARMGISelActualAccessor();
341     GISel->CallLoweringInfo.reset(new ARMCallLowering(*I->getTargetLowering()));
342     GISel->Legalizer.reset(new ARMLegalizerInfo(*I));
343
344     auto *RBI = new ARMRegisterBankInfo(*I->getRegisterInfo());
345
346     // FIXME: At this point, we can't rely on Subtarget having RBI.
347     // It's awkward to mix passing RBI and the Subtarget; should we pass
348     // TII/TRI as well?
349     GISel->InstSelector.reset(createARMInstructionSelector(*this, *I, *RBI));
350
351     GISel->RegBankInfo.reset(RBI);
352 #endif
353     I->setGISelAccessor(*GISel);
354   }
355   return I.get();
356 }
357
358 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
359   return TargetIRAnalysis([this](const Function &F) {
360     return TargetTransformInfo(ARMTTIImpl(this, F));
361   });
362 }
363
364
365 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
366                                        StringRef CPU, StringRef FS,
367                                        const TargetOptions &Options,
368                                        Optional<Reloc::Model> RM,
369                                        CodeModel::Model CM,
370                                        CodeGenOpt::Level OL)
371     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
372
373 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
374                                        StringRef CPU, StringRef FS,
375                                        const TargetOptions &Options,
376                                        Optional<Reloc::Model> RM,
377                                        CodeModel::Model CM,
378                                        CodeGenOpt::Level OL)
379     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
380
381 namespace {
382
383 /// ARM Code Generator Pass Configuration Options.
384 class ARMPassConfig : public TargetPassConfig {
385 public:
386   ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM)
387     : TargetPassConfig(TM, PM) {}
388
389   ARMBaseTargetMachine &getARMTargetMachine() const {
390     return getTM<ARMBaseTargetMachine>();
391   }
392
393   ScheduleDAGInstrs *
394   createMachineScheduler(MachineSchedContext *C) const override {
395     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
396     // add DAG Mutations here.
397     return DAG;
398   }
399
400   ScheduleDAGInstrs *
401   createPostMachineScheduler(MachineSchedContext *C) const override {
402     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
403     // add DAG Mutations here.
404     return DAG;
405   }
406
407   void addIRPasses() override;
408   bool addPreISel() override;
409   bool addInstSelector() override;
410 #ifdef LLVM_BUILD_GLOBAL_ISEL
411   bool addIRTranslator() override;
412   bool addLegalizeMachineIR() override;
413   bool addRegBankSelect() override;
414   bool addGlobalInstructionSelect() override;
415 #endif
416   void addPreRegAlloc() override;
417   void addPreSched2() override;
418   void addPreEmitPass() override;
419 };
420
421 class ARMExecutionDepsFix : public ExecutionDepsFix {
422 public:
423   static char ID;
424   ARMExecutionDepsFix() : ExecutionDepsFix(ID, ARM::DPRRegClass) {}
425   StringRef getPassName() const override {
426     return "ARM Execution Dependency Fix";
427   }
428 };
429 char ARMExecutionDepsFix::ID;
430
431 } // end anonymous namespace
432
433 INITIALIZE_PASS(ARMExecutionDepsFix, "arm-execution-deps-fix",
434                 "ARM Execution Dependency Fix", false, false)
435
436 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
437   return new ARMPassConfig(*this, PM);
438 }
439
440 void ARMPassConfig::addIRPasses() {
441   if (TM->Options.ThreadModel == ThreadModel::Single)
442     addPass(createLowerAtomicPass());
443   else
444     addPass(createAtomicExpandPass());
445
446   // Cmpxchg instructions are often used with a subsequent comparison to
447   // determine whether it succeeded. We can exploit existing control-flow in
448   // ldrex/strex loops to simplify this, but it needs tidying up.
449   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
450     addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
451       const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
452       return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
453     }));
454
455   TargetPassConfig::addIRPasses();
456
457   // Match interleaved memory accesses to ldN/stN intrinsics.
458   if (TM->getOptLevel() != CodeGenOpt::None)
459     addPass(createInterleavedAccessPass());
460 }
461
462 bool ARMPassConfig::addPreISel() {
463   if ((TM->getOptLevel() != CodeGenOpt::None &&
464        EnableGlobalMerge == cl::BOU_UNSET) ||
465       EnableGlobalMerge == cl::BOU_TRUE) {
466     // FIXME: This is using the thumb1 only constant value for
467     // maximal global offset for merging globals. We may want
468     // to look into using the old value for non-thumb1 code of
469     // 4095 based on the TargetMachine, but this starts to become
470     // tricky when doing code gen per function.
471     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
472                                (EnableGlobalMerge == cl::BOU_UNSET);
473     // Merging of extern globals is enabled by default on non-Mach-O as we
474     // expect it to be generally either beneficial or harmless. On Mach-O it
475     // is disabled as we emit the .subsections_via_symbols directive which
476     // means that merging extern globals is not safe.
477     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
478     addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
479                                   MergeExternalByDefault));
480   }
481
482   return false;
483 }
484
485 bool ARMPassConfig::addInstSelector() {
486   addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
487   return false;
488 }
489
490 #ifdef LLVM_BUILD_GLOBAL_ISEL
491 bool ARMPassConfig::addIRTranslator() {
492   addPass(new IRTranslator());
493   return false;
494 }
495
496 bool ARMPassConfig::addLegalizeMachineIR() {
497   addPass(new Legalizer());
498   return false;
499 }
500
501 bool ARMPassConfig::addRegBankSelect() {
502   addPass(new RegBankSelect());
503   return false;
504 }
505
506 bool ARMPassConfig::addGlobalInstructionSelect() {
507   addPass(new InstructionSelect());
508   return false;
509 }
510 #endif
511
512 void ARMPassConfig::addPreRegAlloc() {
513   if (getOptLevel() != CodeGenOpt::None) {
514     addPass(createMLxExpansionPass());
515
516     if (EnableARMLoadStoreOpt)
517       addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
518
519     if (!DisableA15SDOptimization)
520       addPass(createA15SDOptimizerPass());
521   }
522 }
523
524 void ARMPassConfig::addPreSched2() {
525   if (getOptLevel() != CodeGenOpt::None) {
526     if (EnableARMLoadStoreOpt)
527       addPass(createARMLoadStoreOptimizationPass());
528
529     addPass(new ARMExecutionDepsFix());
530   }
531
532   // Expand some pseudo instructions into multiple instructions to allow
533   // proper scheduling.
534   addPass(createARMExpandPseudoPass());
535
536   if (getOptLevel() != CodeGenOpt::None) {
537     // in v8, IfConversion depends on Thumb instruction widths
538     addPass(createThumb2SizeReductionPass([this](const Function &F) {
539       return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
540     }));
541
542     addPass(createIfConverter([](const MachineFunction &MF) {
543       return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
544     }));
545   }
546   addPass(createThumb2ITBlockPass());
547 }
548
549 void ARMPassConfig::addPreEmitPass() {
550   addPass(createThumb2SizeReductionPass());
551
552   // Constant island pass work on unbundled instructions.
553   addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
554     return MF.getSubtarget<ARMSubtarget>().isThumb2();
555   }));
556
557   // Don't optimize barriers at -O0.
558   if (getOptLevel() != CodeGenOpt::None)
559     addPass(createARMOptimizeBarriersPass());
560
561   addPass(createARMConstantIslandPass());
562 }