1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
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
7 //===----------------------------------------------------------------------===//
10 //===----------------------------------------------------------------------===//
12 #include "ARMTargetMachine.h"
14 #include "ARMMacroFusion.h"
15 #include "ARMSubtarget.h"
16 #include "ARMTargetObjectFile.h"
17 #include "ARMTargetTransformInfo.h"
18 #include "MCTargetDesc/ARMMCTargetDesc.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/CodeGen/ExecutionDomainFix.h"
25 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
26 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
27 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
28 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
29 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
30 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
31 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
32 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineScheduler.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/TargetPassConfig.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/TargetParser.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Transforms/Scalar.h"
56 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden
,
57 cl::desc("Inhibit optimization of S->D register accesses on A15"),
61 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden
,
62 cl::desc("Run SimplifyCFG after expanding atomic operations"
63 " to make use of cmpxchg flow-based information"),
67 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden
,
68 cl::desc("Enable ARM load/store optimization pass"),
71 // FIXME: Unify control over GlobalMerge.
72 static cl::opt
<cl::boolOrDefault
>
73 EnableGlobalMerge("arm-global-merge", cl::Hidden
,
74 cl::desc("Enable the global merge pass"));
77 void initializeARMExecutionDomainFixPass(PassRegistry
&);
80 extern "C" void LLVMInitializeARMTarget() {
81 // Register the target.
82 RegisterTargetMachine
<ARMLETargetMachine
> X(getTheARMLETarget());
83 RegisterTargetMachine
<ARMLETargetMachine
> A(getTheThumbLETarget());
84 RegisterTargetMachine
<ARMBETargetMachine
> Y(getTheARMBETarget());
85 RegisterTargetMachine
<ARMBETargetMachine
> B(getTheThumbBETarget());
87 PassRegistry
&Registry
= *PassRegistry::getPassRegistry();
88 initializeGlobalISel(Registry
);
89 initializeARMLoadStoreOptPass(Registry
);
90 initializeARMPreAllocLoadStoreOptPass(Registry
);
91 initializeARMParallelDSPPass(Registry
);
92 initializeARMCodeGenPreparePass(Registry
);
93 initializeARMConstantIslandsPass(Registry
);
94 initializeARMExecutionDomainFixPass(Registry
);
95 initializeARMExpandPseudoPass(Registry
);
96 initializeThumb2SizeReducePass(Registry
);
99 static std::unique_ptr
<TargetLoweringObjectFile
> createTLOF(const Triple
&TT
) {
100 if (TT
.isOSBinFormatMachO())
101 return llvm::make_unique
<TargetLoweringObjectFileMachO
>();
102 if (TT
.isOSWindows())
103 return llvm::make_unique
<TargetLoweringObjectFileCOFF
>();
104 return llvm::make_unique
<ARMElfTargetObjectFile
>();
107 static ARMBaseTargetMachine::ARMABI
108 computeTargetABI(const Triple
&TT
, StringRef CPU
,
109 const TargetOptions
&Options
) {
110 StringRef ABIName
= Options
.MCOptions
.getABIName();
113 ABIName
= ARM::computeDefaultTargetABI(TT
, CPU
);
115 if (ABIName
== "aapcs16")
116 return ARMBaseTargetMachine::ARM_ABI_AAPCS16
;
117 else if (ABIName
.startswith("aapcs"))
118 return ARMBaseTargetMachine::ARM_ABI_AAPCS
;
119 else if (ABIName
.startswith("apcs"))
120 return ARMBaseTargetMachine::ARM_ABI_APCS
;
122 llvm_unreachable("Unhandled/unknown ABI Name!");
123 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN
;
126 static std::string
computeDataLayout(const Triple
&TT
, StringRef CPU
,
127 const TargetOptions
&Options
,
129 auto ABI
= computeTargetABI(TT
, CPU
, Options
);
139 Ret
+= DataLayout::getManglingComponent(TT
);
141 // Pointers are 32 bits and aligned to 32 bits.
144 // ABIs other than APCS have 64 bit integers with natural alignment.
145 if (ABI
!= ARMBaseTargetMachine::ARM_ABI_APCS
)
148 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
149 // bits, others to 64 bits. We always try to align to 64 bits.
150 if (ABI
== ARMBaseTargetMachine::ARM_ABI_APCS
)
153 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
154 // to 64. We always ty to give them natural alignment.
155 if (ABI
== ARMBaseTargetMachine::ARM_ABI_APCS
)
156 Ret
+= "-v64:32:64-v128:32:128";
157 else if (ABI
!= ARMBaseTargetMachine::ARM_ABI_AAPCS16
)
158 Ret
+= "-v128:64:128";
160 // Try to align aggregates to 32 bits (the default is 64 bits, which has no
161 // particular hardware support on 32-bit ARM).
164 // Integer registers are 32 bits.
167 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
168 // aligned everywhere else.
169 if (TT
.isOSNaCl() || ABI
== ARMBaseTargetMachine::ARM_ABI_AAPCS16
)
171 else if (ABI
== ARMBaseTargetMachine::ARM_ABI_AAPCS
)
179 static Reloc::Model
getEffectiveRelocModel(const Triple
&TT
,
180 Optional
<Reloc::Model
> RM
) {
182 // Default relocation model on Darwin is PIC.
183 return TT
.isOSBinFormatMachO() ? Reloc::PIC_
: Reloc::Static
;
185 if (*RM
== Reloc::ROPI
|| *RM
== Reloc::RWPI
|| *RM
== Reloc::ROPI_RWPI
)
186 assert(TT
.isOSBinFormatELF() &&
187 "ROPI/RWPI currently only supported for ELF");
189 // DynamicNoPIC is only used on darwin.
190 if (*RM
== Reloc::DynamicNoPIC
&& !TT
.isOSDarwin())
191 return Reloc::Static
;
196 /// Create an ARM architecture model.
198 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target
&T
, const Triple
&TT
,
199 StringRef CPU
, StringRef FS
,
200 const TargetOptions
&Options
,
201 Optional
<Reloc::Model
> RM
,
202 Optional
<CodeModel::Model
> CM
,
203 CodeGenOpt::Level OL
, bool isLittle
)
204 : LLVMTargetMachine(T
, computeDataLayout(TT
, CPU
, Options
, isLittle
), TT
,
205 CPU
, FS
, Options
, getEffectiveRelocModel(TT
, RM
),
206 getEffectiveCodeModel(CM
, CodeModel::Small
), OL
),
207 TargetABI(computeTargetABI(TT
, CPU
, Options
)),
208 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle
) {
210 // Default to triple-appropriate float ABI
211 if (Options
.FloatABIType
== FloatABI::Default
) {
212 if (isTargetHardFloat())
213 this->Options
.FloatABIType
= FloatABI::Hard
;
215 this->Options
.FloatABIType
= FloatABI::Soft
;
218 // Default to triple-appropriate EABI
219 if (Options
.EABIVersion
== EABI::Default
||
220 Options
.EABIVersion
== EABI::Unknown
) {
221 // musl is compatible with glibc with regard to EABI version
222 if ((TargetTriple
.getEnvironment() == Triple::GNUEABI
||
223 TargetTriple
.getEnvironment() == Triple::GNUEABIHF
||
224 TargetTriple
.getEnvironment() == Triple::MuslEABI
||
225 TargetTriple
.getEnvironment() == Triple::MuslEABIHF
) &&
226 !(TargetTriple
.isOSWindows() || TargetTriple
.isOSDarwin()))
227 this->Options
.EABIVersion
= EABI::GNU
;
229 this->Options
.EABIVersion
= EABI::EABI5
;
232 if (TT
.isOSBinFormatMachO()) {
233 this->Options
.TrapUnreachable
= true;
234 this->Options
.NoTrapAfterNoreturn
= true;
240 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
243 ARMBaseTargetMachine::getSubtargetImpl(const Function
&F
) const {
244 Attribute CPUAttr
= F
.getFnAttribute("target-cpu");
245 Attribute FSAttr
= F
.getFnAttribute("target-features");
247 std::string CPU
= !CPUAttr
.hasAttribute(Attribute::None
)
248 ? CPUAttr
.getValueAsString().str()
250 std::string FS
= !FSAttr
.hasAttribute(Attribute::None
)
251 ? FSAttr
.getValueAsString().str()
254 // FIXME: This is related to the code below to reset the target options,
255 // we need to know whether or not the soft float flag is set on the
256 // function before we can generate a subtarget. We also need to use
257 // it as a key for the subtarget since that can be the only difference
258 // between two functions.
260 F
.getFnAttribute("use-soft-float").getValueAsString() == "true";
261 // If the soft float attribute is set on the function turn on the soft float
262 // subtarget feature.
264 FS
+= FS
.empty() ? "+soft-float" : ",+soft-float";
266 // Use the optminsize to identify the subtarget, but don't use it in the
268 std::string Key
= CPU
+ FS
;
269 if (F
.optForMinSize())
272 auto &I
= SubtargetMap
[Key
];
274 // This needs to be done before we create a new subtarget since any
275 // creation will depend on the TM and the code generation flags on the
276 // function that reside in TargetOptions.
277 resetTargetOptions(F
);
278 I
= llvm::make_unique
<ARMSubtarget
>(TargetTriple
, CPU
, FS
, *this, isLittle
,
281 if (!I
->isThumb() && !I
->hasARMOps())
282 F
.getContext().emitError("Function '" + F
.getName() + "' uses ARM "
283 "instructions, but the target does not support ARM mode execution.");
290 ARMBaseTargetMachine::getTargetTransformInfo(const Function
&F
) {
291 return TargetTransformInfo(ARMTTIImpl(this, F
));
294 ARMLETargetMachine::ARMLETargetMachine(const Target
&T
, const Triple
&TT
,
295 StringRef CPU
, StringRef FS
,
296 const TargetOptions
&Options
,
297 Optional
<Reloc::Model
> RM
,
298 Optional
<CodeModel::Model
> CM
,
299 CodeGenOpt::Level OL
, bool JIT
)
300 : ARMBaseTargetMachine(T
, TT
, CPU
, FS
, Options
, RM
, CM
, OL
, true) {}
302 ARMBETargetMachine::ARMBETargetMachine(const Target
&T
, const Triple
&TT
,
303 StringRef CPU
, StringRef FS
,
304 const TargetOptions
&Options
,
305 Optional
<Reloc::Model
> RM
,
306 Optional
<CodeModel::Model
> CM
,
307 CodeGenOpt::Level OL
, bool JIT
)
308 : ARMBaseTargetMachine(T
, TT
, CPU
, FS
, Options
, RM
, CM
, OL
, false) {}
312 /// ARM Code Generator Pass Configuration Options.
313 class ARMPassConfig
: public TargetPassConfig
{
315 ARMPassConfig(ARMBaseTargetMachine
&TM
, PassManagerBase
&PM
)
316 : TargetPassConfig(TM
, PM
) {
317 if (TM
.getOptLevel() != CodeGenOpt::None
) {
318 ARMGenSubtargetInfo
STI(TM
.getTargetTriple(), TM
.getTargetCPU(),
319 TM
.getTargetFeatureString());
320 if (STI
.hasFeature(ARM::FeatureUseMISched
))
321 substitutePass(&PostRASchedulerID
, &PostMachineSchedulerID
);
325 ARMBaseTargetMachine
&getARMTargetMachine() const {
326 return getTM
<ARMBaseTargetMachine
>();
330 createMachineScheduler(MachineSchedContext
*C
) const override
{
331 ScheduleDAGMILive
*DAG
= createGenericSchedLive(C
);
332 // add DAG Mutations here.
333 const ARMSubtarget
&ST
= C
->MF
->getSubtarget
<ARMSubtarget
>();
335 DAG
->addMutation(createARMMacroFusionDAGMutation());
340 createPostMachineScheduler(MachineSchedContext
*C
) const override
{
341 ScheduleDAGMI
*DAG
= createGenericSchedPostRA(C
);
342 // add DAG Mutations here.
343 const ARMSubtarget
&ST
= C
->MF
->getSubtarget
<ARMSubtarget
>();
345 DAG
->addMutation(createARMMacroFusionDAGMutation());
349 void addIRPasses() override
;
350 void addCodeGenPrepare() override
;
351 bool addPreISel() override
;
352 bool addInstSelector() override
;
353 bool addIRTranslator() override
;
354 bool addLegalizeMachineIR() override
;
355 bool addRegBankSelect() override
;
356 bool addGlobalInstructionSelect() override
;
357 void addPreRegAlloc() override
;
358 void addPreSched2() override
;
359 void addPreEmitPass() override
;
362 class ARMExecutionDomainFix
: public ExecutionDomainFix
{
365 ARMExecutionDomainFix() : ExecutionDomainFix(ID
, ARM::DPRRegClass
) {}
366 StringRef
getPassName() const override
{
367 return "ARM Execution Domain Fix";
370 char ARMExecutionDomainFix::ID
;
372 } // end anonymous namespace
374 INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix
, "arm-execution-domain-fix",
375 "ARM Execution Domain Fix", false, false)
376 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis
)
377 INITIALIZE_PASS_END(ARMExecutionDomainFix
, "arm-execution-domain-fix",
378 "ARM Execution Domain Fix", false, false)
380 TargetPassConfig
*ARMBaseTargetMachine::createPassConfig(PassManagerBase
&PM
) {
381 return new ARMPassConfig(*this, PM
);
384 void ARMPassConfig::addIRPasses() {
385 if (TM
->Options
.ThreadModel
== ThreadModel::Single
)
386 addPass(createLowerAtomicPass());
388 addPass(createAtomicExpandPass());
390 // Cmpxchg instructions are often used with a subsequent comparison to
391 // determine whether it succeeded. We can exploit existing control-flow in
392 // ldrex/strex loops to simplify this, but it needs tidying up.
393 if (TM
->getOptLevel() != CodeGenOpt::None
&& EnableAtomicTidy
)
394 addPass(createCFGSimplificationPass(
395 1, false, false, true, true, [this](const Function
&F
) {
396 const auto &ST
= this->TM
->getSubtarget
<ARMSubtarget
>(F
);
397 return ST
.hasAnyDataBarrier() && !ST
.isThumb1Only();
400 TargetPassConfig::addIRPasses();
402 // Match interleaved memory accesses to ldN/stN intrinsics.
403 if (TM
->getOptLevel() != CodeGenOpt::None
)
404 addPass(createInterleavedAccessPass());
407 void ARMPassConfig::addCodeGenPrepare() {
408 if (getOptLevel() != CodeGenOpt::None
)
409 addPass(createARMCodeGenPreparePass());
410 TargetPassConfig::addCodeGenPrepare();
413 bool ARMPassConfig::addPreISel() {
414 if (getOptLevel() != CodeGenOpt::None
)
415 addPass(createARMParallelDSPPass());
417 if ((TM
->getOptLevel() != CodeGenOpt::None
&&
418 EnableGlobalMerge
== cl::BOU_UNSET
) ||
419 EnableGlobalMerge
== cl::BOU_TRUE
) {
420 // FIXME: This is using the thumb1 only constant value for
421 // maximal global offset for merging globals. We may want
422 // to look into using the old value for non-thumb1 code of
423 // 4095 based on the TargetMachine, but this starts to become
424 // tricky when doing code gen per function.
425 bool OnlyOptimizeForSize
= (TM
->getOptLevel() < CodeGenOpt::Aggressive
) &&
426 (EnableGlobalMerge
== cl::BOU_UNSET
);
427 // Merging of extern globals is enabled by default on non-Mach-O as we
428 // expect it to be generally either beneficial or harmless. On Mach-O it
429 // is disabled as we emit the .subsections_via_symbols directive which
430 // means that merging extern globals is not safe.
431 bool MergeExternalByDefault
= !TM
->getTargetTriple().isOSBinFormatMachO();
432 addPass(createGlobalMergePass(TM
, 127, OnlyOptimizeForSize
,
433 MergeExternalByDefault
));
439 bool ARMPassConfig::addInstSelector() {
440 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
444 bool ARMPassConfig::addIRTranslator() {
445 addPass(new IRTranslator());
449 bool ARMPassConfig::addLegalizeMachineIR() {
450 addPass(new Legalizer());
454 bool ARMPassConfig::addRegBankSelect() {
455 addPass(new RegBankSelect());
459 bool ARMPassConfig::addGlobalInstructionSelect() {
460 addPass(new InstructionSelect());
464 void ARMPassConfig::addPreRegAlloc() {
465 if (getOptLevel() != CodeGenOpt::None
) {
466 addPass(createMLxExpansionPass());
468 if (EnableARMLoadStoreOpt
)
469 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
471 if (!DisableA15SDOptimization
)
472 addPass(createA15SDOptimizerPass());
476 void ARMPassConfig::addPreSched2() {
477 if (getOptLevel() != CodeGenOpt::None
) {
478 if (EnableARMLoadStoreOpt
)
479 addPass(createARMLoadStoreOptimizationPass());
481 addPass(new ARMExecutionDomainFix());
482 addPass(createBreakFalseDeps());
485 // Expand some pseudo instructions into multiple instructions to allow
486 // proper scheduling.
487 addPass(createARMExpandPseudoPass());
489 if (getOptLevel() != CodeGenOpt::None
) {
490 // in v8, IfConversion depends on Thumb instruction widths
491 addPass(createThumb2SizeReductionPass([this](const Function
&F
) {
492 return this->TM
->getSubtarget
<ARMSubtarget
>(F
).restrictIT();
495 addPass(createIfConverter([](const MachineFunction
&MF
) {
496 return !MF
.getSubtarget
<ARMSubtarget
>().isThumb1Only();
499 addPass(createThumb2ITBlockPass());
502 void ARMPassConfig::addPreEmitPass() {
503 addPass(createThumb2SizeReductionPass());
505 // Constant island pass work on unbundled instructions.
506 addPass(createUnpackMachineBundles([](const MachineFunction
&MF
) {
507 return MF
.getSubtarget
<ARMSubtarget
>().isThumb2();
510 // Don't optimize barriers at -O0.
511 if (getOptLevel() != CodeGenOpt::None
)
512 addPass(createARMOptimizeBarriersPass());
514 addPass(createARMConstantIslandPass());