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