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