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   StringRef ABIName = Options.MCOptions.getABIName();
114 
115   if (ABIName.empty())
116     ABIName = ARM::computeDefaultTargetABI(TT, CPU);
117 
118   if (ABIName == "aapcs16")
119     return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
120   else if (ABIName.startswith("aapcs"))
121     return ARMBaseTargetMachine::ARM_ABI_AAPCS;
122   else if (ABIName.startswith("apcs"))
123     return ARMBaseTargetMachine::ARM_ABI_APCS;
124 
125   llvm_unreachable("Unhandled/unknown ABI Name!");
126   return ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
127 }
128 
129 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
130                                      const TargetOptions &Options,
131                                      bool isLittle) {
132   auto ABI = computeTargetABI(TT, CPU, Options);
133   std::string Ret;
134 
135   if (isLittle)
136     // Little endian.
137     Ret += "e";
138   else
139     // Big endian.
140     Ret += "E";
141 
142   Ret += DataLayout::getManglingComponent(TT);
143 
144   // Pointers are 32 bits and aligned to 32 bits.
145   Ret += "-p:32:32";
146 
147   // ABIs other than APCS have 64 bit integers with natural alignment.
148   if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
149     Ret += "-i64:64";
150 
151   // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
152   // bits, others to 64 bits. We always try to align to 64 bits.
153   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
154     Ret += "-f64:32:64";
155 
156   // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
157   // to 64. We always ty to give them natural alignment.
158   if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
159     Ret += "-v64:32:64-v128:32:128";
160   else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
161     Ret += "-v128:64:128";
162 
163   // Try to align aggregates to 32 bits (the default is 64 bits, which has no
164   // particular hardware support on 32-bit ARM).
165   Ret += "-a:0:32";
166 
167   // Integer registers are 32 bits.
168   Ret += "-n32";
169 
170   // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
171   // aligned everywhere else.
172   if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
173     Ret += "-S128";
174   else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
175     Ret += "-S64";
176   else
177     Ret += "-S32";
178 
179   return Ret;
180 }
181 
182 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
183                                            Optional<Reloc::Model> RM) {
184   if (!RM.hasValue())
185     // Default relocation model on Darwin is PIC.
186     return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
187 
188   if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
189     assert(TT.isOSBinFormatELF() &&
190            "ROPI/RWPI currently only supported for ELF");
191 
192   // DynamicNoPIC is only used on darwin.
193   if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
194     return Reloc::Static;
195 
196   return *RM;
197 }
198 
199 /// Create an ARM architecture model.
200 ///
201 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
202                                            StringRef CPU, StringRef FS,
203                                            const TargetOptions &Options,
204                                            Optional<Reloc::Model> RM,
205                                            CodeModel::Model CM,
206                                            CodeGenOpt::Level OL, bool isLittle)
207     : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
208                         CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM,
209                         OL),
210       TargetABI(computeTargetABI(TT, CPU, Options)),
211       TLOF(createTLOF(getTargetTriple())),
212       Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
213 
214   // Default to triple-appropriate float ABI
215   if (Options.FloatABIType == FloatABI::Default)
216     this->Options.FloatABIType =
217         Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
218 
219   // Default to triple-appropriate EABI
220   if (Options.EABIVersion == EABI::Default ||
221       Options.EABIVersion == EABI::Unknown) {
222     // musl is compatible with glibc with regard to EABI version
223     if (Subtarget.isTargetGNUAEABI() || Subtarget.isTargetMuslAEABI())
224       this->Options.EABIVersion = EABI::GNU;
225     else
226       this->Options.EABIVersion = EABI::EABI5;
227   }
228 
229   initAsmInfo();
230   if (!Subtarget.isThumb() && !Subtarget.hasARMOps())
231     report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
232                        "support ARM mode execution!");
233 }
234 
235 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
236 
237 #ifdef LLVM_BUILD_GLOBAL_ISEL
238 namespace {
239 
240 struct ARMGISelActualAccessor : public GISelAccessor {
241   std::unique_ptr<CallLowering> CallLoweringInfo;
242   std::unique_ptr<InstructionSelector> InstSelector;
243   std::unique_ptr<LegalizerInfo> Legalizer;
244   std::unique_ptr<RegisterBankInfo> RegBankInfo;
245 
246   const CallLowering *getCallLowering() const override {
247     return CallLoweringInfo.get();
248   }
249 
250   const InstructionSelector *getInstructionSelector() const override {
251     return InstSelector.get();
252   }
253 
254   const LegalizerInfo *getLegalizerInfo() const override {
255     return Legalizer.get();
256   }
257 
258   const RegisterBankInfo *getRegBankInfo() const override {
259     return RegBankInfo.get();
260   }
261 };
262 
263 } // end anonymous namespace
264 #endif
265 
266 const ARMSubtarget *
267 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
268   Attribute CPUAttr = F.getFnAttribute("target-cpu");
269   Attribute FSAttr = F.getFnAttribute("target-features");
270 
271   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
272                         ? CPUAttr.getValueAsString().str()
273                         : TargetCPU;
274   std::string FS = !FSAttr.hasAttribute(Attribute::None)
275                        ? FSAttr.getValueAsString().str()
276                        : TargetFS;
277 
278   // FIXME: This is related to the code below to reset the target options,
279   // we need to know whether or not the soft float flag is set on the
280   // function before we can generate a subtarget. We also need to use
281   // it as a key for the subtarget since that can be the only difference
282   // between two functions.
283   bool SoftFloat =
284       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
285   // If the soft float attribute is set on the function turn on the soft float
286   // subtarget feature.
287   if (SoftFloat)
288     FS += FS.empty() ? "+soft-float" : ",+soft-float";
289 
290   auto &I = SubtargetMap[CPU + FS];
291   if (!I) {
292     // This needs to be done before we create a new subtarget since any
293     // creation will depend on the TM and the code generation flags on the
294     // function that reside in TargetOptions.
295     resetTargetOptions(F);
296     I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
297 
298 #ifndef LLVM_BUILD_GLOBAL_ISEL
299     GISelAccessor *GISel = new GISelAccessor();
300 #else
301     ARMGISelActualAccessor *GISel = new ARMGISelActualAccessor();
302     GISel->CallLoweringInfo.reset(new ARMCallLowering(*I->getTargetLowering()));
303     GISel->Legalizer.reset(new ARMLegalizerInfo(*I));
304 
305     auto *RBI = new ARMRegisterBankInfo(*I->getRegisterInfo());
306 
307     // FIXME: At this point, we can't rely on Subtarget having RBI.
308     // It's awkward to mix passing RBI and the Subtarget; should we pass
309     // TII/TRI as well?
310     GISel->InstSelector.reset(createARMInstructionSelector(*this, *I, *RBI));
311 
312     GISel->RegBankInfo.reset(RBI);
313 #endif
314     I->setGISelAccessor(*GISel);
315   }
316   return I.get();
317 }
318 
319 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
320   return TargetIRAnalysis([this](const Function &F) {
321     return TargetTransformInfo(ARMTTIImpl(this, F));
322   });
323 }
324 
325 
326 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
327                                        StringRef CPU, StringRef FS,
328                                        const TargetOptions &Options,
329                                        Optional<Reloc::Model> RM,
330                                        CodeModel::Model CM,
331                                        CodeGenOpt::Level OL)
332     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
333 
334 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
335                                        StringRef CPU, StringRef FS,
336                                        const TargetOptions &Options,
337                                        Optional<Reloc::Model> RM,
338                                        CodeModel::Model CM,
339                                        CodeGenOpt::Level OL)
340     : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
341 
342 namespace {
343 
344 /// ARM Code Generator Pass Configuration Options.
345 class ARMPassConfig : public TargetPassConfig {
346 public:
347   ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM)
348     : TargetPassConfig(TM, PM) {}
349 
350   ARMBaseTargetMachine &getARMTargetMachine() const {
351     return getTM<ARMBaseTargetMachine>();
352   }
353 
354   ScheduleDAGInstrs *
355   createMachineScheduler(MachineSchedContext *C) const override {
356     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
357     // add DAG Mutations here.
358     const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
359     if (ST.hasFusion())
360       DAG->addMutation(createARMMacroFusionDAGMutation());
361     return DAG;
362   }
363 
364   ScheduleDAGInstrs *
365   createPostMachineScheduler(MachineSchedContext *C) const override {
366     ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
367     // add DAG Mutations here.
368     const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
369     if (ST.hasFusion())
370       DAG->addMutation(createARMMacroFusionDAGMutation());
371     return DAG;
372   }
373 
374   void addIRPasses() override;
375   bool addPreISel() override;
376   bool addInstSelector() override;
377 #ifdef LLVM_BUILD_GLOBAL_ISEL
378   bool addIRTranslator() override;
379   bool addLegalizeMachineIR() override;
380   bool addRegBankSelect() override;
381   bool addGlobalInstructionSelect() override;
382 #endif
383   void addPreRegAlloc() override;
384   void addPreSched2() override;
385   void addPreEmitPass() override;
386 };
387 
388 class ARMExecutionDepsFix : public ExecutionDepsFix {
389 public:
390   static char ID;
391   ARMExecutionDepsFix() : ExecutionDepsFix(ID, ARM::DPRRegClass) {}
392   StringRef getPassName() const override {
393     return "ARM Execution Dependency Fix";
394   }
395 };
396 char ARMExecutionDepsFix::ID;
397 
398 } // end anonymous namespace
399 
400 INITIALIZE_PASS(ARMExecutionDepsFix, "arm-execution-deps-fix",
401                 "ARM Execution Dependency Fix", false, false)
402 
403 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
404   return new ARMPassConfig(*this, PM);
405 }
406 
407 void ARMPassConfig::addIRPasses() {
408   if (TM->Options.ThreadModel == ThreadModel::Single)
409     addPass(createLowerAtomicPass());
410   else
411     addPass(createAtomicExpandPass());
412 
413   // Cmpxchg instructions are often used with a subsequent comparison to
414   // determine whether it succeeded. We can exploit existing control-flow in
415   // ldrex/strex loops to simplify this, but it needs tidying up.
416   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
417     addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
418       const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
419       return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
420     }));
421 
422   TargetPassConfig::addIRPasses();
423 
424   // Match interleaved memory accesses to ldN/stN intrinsics.
425   if (TM->getOptLevel() != CodeGenOpt::None)
426     addPass(createInterleavedAccessPass());
427 }
428 
429 bool ARMPassConfig::addPreISel() {
430   if ((TM->getOptLevel() != CodeGenOpt::None &&
431        EnableGlobalMerge == cl::BOU_UNSET) ||
432       EnableGlobalMerge == cl::BOU_TRUE) {
433     // FIXME: This is using the thumb1 only constant value for
434     // maximal global offset for merging globals. We may want
435     // to look into using the old value for non-thumb1 code of
436     // 4095 based on the TargetMachine, but this starts to become
437     // tricky when doing code gen per function.
438     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
439                                (EnableGlobalMerge == cl::BOU_UNSET);
440     // Merging of extern globals is enabled by default on non-Mach-O as we
441     // expect it to be generally either beneficial or harmless. On Mach-O it
442     // is disabled as we emit the .subsections_via_symbols directive which
443     // means that merging extern globals is not safe.
444     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
445     addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
446                                   MergeExternalByDefault));
447   }
448 
449   return false;
450 }
451 
452 bool ARMPassConfig::addInstSelector() {
453   addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
454   return false;
455 }
456 
457 #ifdef LLVM_BUILD_GLOBAL_ISEL
458 bool ARMPassConfig::addIRTranslator() {
459   addPass(new IRTranslator());
460   return false;
461 }
462 
463 bool ARMPassConfig::addLegalizeMachineIR() {
464   addPass(new Legalizer());
465   return false;
466 }
467 
468 bool ARMPassConfig::addRegBankSelect() {
469   addPass(new RegBankSelect());
470   return false;
471 }
472 
473 bool ARMPassConfig::addGlobalInstructionSelect() {
474   addPass(new InstructionSelect());
475   return false;
476 }
477 #endif
478 
479 void ARMPassConfig::addPreRegAlloc() {
480   if (getOptLevel() != CodeGenOpt::None) {
481     addPass(createMLxExpansionPass());
482 
483     if (EnableARMLoadStoreOpt)
484       addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
485 
486     if (!DisableA15SDOptimization)
487       addPass(createA15SDOptimizerPass());
488   }
489 }
490 
491 void ARMPassConfig::addPreSched2() {
492   if (getOptLevel() != CodeGenOpt::None) {
493     if (EnableARMLoadStoreOpt)
494       addPass(createARMLoadStoreOptimizationPass());
495 
496     addPass(new ARMExecutionDepsFix());
497   }
498 
499   // Expand some pseudo instructions into multiple instructions to allow
500   // proper scheduling.
501   addPass(createARMExpandPseudoPass());
502 
503   if (getOptLevel() != CodeGenOpt::None) {
504     // in v8, IfConversion depends on Thumb instruction widths
505     addPass(createThumb2SizeReductionPass([this](const Function &F) {
506       return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
507     }));
508 
509     addPass(createIfConverter([](const MachineFunction &MF) {
510       return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
511     }));
512   }
513   addPass(createThumb2ITBlockPass());
514 }
515 
516 void ARMPassConfig::addPreEmitPass() {
517   addPass(createThumb2SizeReductionPass());
518 
519   // Constant island pass work on unbundled instructions.
520   addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
521     return MF.getSubtarget<ARMSubtarget>().isThumb2();
522   }));
523 
524   // Don't optimize barriers at -O0.
525   if (getOptLevel() != CodeGenOpt::None)
526     addPass(createARMOptimizeBarriersPass());
527 
528   addPass(createARMConstantIslandPass());
529 }
530