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