1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 //===----------------------------------------------------------------------===//
14 #include "ARMFrameLowering.h"
15 #include "ARMTargetMachine.h"
16 #include "ARMTargetObjectFile.h"
17 #include "ARMTargetTransformInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/TargetPassConfig.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/LegacyPassManager.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FormattedStream.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Transforms/Scalar.h"
31 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
32 cl::desc("Inhibit optimization of S->D register accesses on A15"),
36 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
37 cl::desc("Run SimplifyCFG after expanding atomic operations"
38 " to make use of cmpxchg flow-based information"),
42 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
43 cl::desc("Enable ARM load/store optimization pass"),
46 // FIXME: Unify control over GlobalMerge.
47 static cl::opt<cl::boolOrDefault>
48 EnableGlobalMerge("arm-global-merge", cl::Hidden,
49 cl::desc("Enable the global merge pass"));
51 extern "C" void LLVMInitializeARMTarget() {
52 // Register the target.
53 RegisterTargetMachine<ARMLETargetMachine> X(TheARMLETarget);
54 RegisterTargetMachine<ARMBETargetMachine> Y(TheARMBETarget);
55 RegisterTargetMachine<ThumbLETargetMachine> A(TheThumbLETarget);
56 RegisterTargetMachine<ThumbBETargetMachine> B(TheThumbBETarget);
58 PassRegistry &Registry = *PassRegistry::getPassRegistry();
59 initializeARMLoadStoreOptPass(Registry);
60 initializeARMPreAllocLoadStoreOptPass(Registry);
63 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
64 if (TT.isOSBinFormatMachO())
65 return make_unique<TargetLoweringObjectFileMachO>();
67 return make_unique<TargetLoweringObjectFileCOFF>();
68 return make_unique<ARMElfTargetObjectFile>();
71 static ARMBaseTargetMachine::ARMABI
72 computeTargetABI(const Triple &TT, StringRef CPU,
73 const TargetOptions &Options) {
74 if (Options.MCOptions.getABIName() == "aapcs16")
75 return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
76 else if (Options.MCOptions.getABIName().startswith("aapcs"))
77 return ARMBaseTargetMachine::ARM_ABI_AAPCS;
78 else if (Options.MCOptions.getABIName().startswith("apcs"))
79 return ARMBaseTargetMachine::ARM_ABI_APCS;
81 assert(Options.MCOptions.getABIName().empty() &&
82 "Unknown target-abi option!");
84 ARMBaseTargetMachine::ARMABI TargetABI =
85 ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
87 // FIXME: This is duplicated code from the front end and should be unified.
88 if (TT.isOSBinFormatMachO()) {
89 if (TT.getEnvironment() == llvm::Triple::EABI ||
90 (TT.getOS() == llvm::Triple::UnknownOS && TT.isOSBinFormatMachO()) ||
91 CPU.startswith("cortex-m")) {
92 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
93 } else if (TT.isWatchABI()) {
94 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS16;
96 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
98 } else if (TT.isOSWindows()) {
99 // FIXME: this is invalid for WindowsCE
100 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
102 // Select the default based on the platform.
103 switch (TT.getEnvironment()) {
104 case llvm::Triple::Android:
105 case llvm::Triple::GNUEABI:
106 case llvm::Triple::GNUEABIHF:
107 case llvm::Triple::MuslEABI:
108 case llvm::Triple::MuslEABIHF:
109 case llvm::Triple::EABIHF:
110 case llvm::Triple::EABI:
111 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
113 case llvm::Triple::GNU:
114 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
118 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
120 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
128 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
129 const TargetOptions &Options,
131 auto ABI = computeTargetABI(TT, CPU, Options);
132 std::string Ret = "";
141 Ret += DataLayout::getManglingComponent(TT);
143 // Pointers are 32 bits and aligned to 32 bits.
146 // ABIs other than APCS have 64 bit integers with natural alignment.
147 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
150 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
151 // bits, others to 64 bits. We always try to align to 64 bits.
152 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
155 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
156 // to 64. We always ty to give them natural alignment.
157 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
158 Ret += "-v64:32:64-v128:32:128";
159 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
160 Ret += "-v128:64:128";
162 // Try to align aggregates to 32 bits (the default is 64 bits, which has no
163 // particular hardware support on 32-bit ARM).
166 // Integer registers are 32 bits.
169 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
170 // aligned everywhere else.
171 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
173 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
181 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
182 Optional<Reloc::Model> RM) {
184 // Default relocation model on Darwin is PIC.
185 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
187 // DynamicNoPIC is only used on darwin.
188 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
189 return Reloc::Static;
194 /// Create an ARM architecture model.
196 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
197 StringRef CPU, StringRef FS,
198 const TargetOptions &Options,
199 Optional<Reloc::Model> RM,
201 CodeGenOpt::Level OL, bool isLittle)
202 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
203 CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM,
205 TargetABI(computeTargetABI(TT, CPU, Options)),
206 TLOF(createTLOF(getTargetTriple())),
207 Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
209 // Default to triple-appropriate float ABI
210 if (Options.FloatABIType == FloatABI::Default)
211 this->Options.FloatABIType =
212 Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
214 // Default to triple-appropriate EABI
215 if (Options.EABIVersion == EABI::Default ||
216 Options.EABIVersion == EABI::Unknown) {
217 // musl is compatible with glibc with regard to EABI version
218 if (Subtarget.isTargetGNUAEABI() || Subtarget.isTargetMuslAEABI())
219 this->Options.EABIVersion = EABI::GNU;
221 this->Options.EABIVersion = EABI::EABI5;
225 ARMBaseTargetMachine::~ARMBaseTargetMachine() {}
228 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
229 Attribute CPUAttr = F.getFnAttribute("target-cpu");
230 Attribute FSAttr = F.getFnAttribute("target-features");
232 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
233 ? CPUAttr.getValueAsString().str()
235 std::string FS = !FSAttr.hasAttribute(Attribute::None)
236 ? FSAttr.getValueAsString().str()
239 // FIXME: This is related to the code below to reset the target options,
240 // we need to know whether or not the soft float flag is set on the
241 // function before we can generate a subtarget. We also need to use
242 // it as a key for the subtarget since that can be the only difference
243 // between two functions.
245 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
246 // If the soft float attribute is set on the function turn on the soft float
247 // subtarget feature.
249 FS += FS.empty() ? "+soft-float" : ",+soft-float";
251 auto &I = SubtargetMap[CPU + FS];
253 // This needs to be done before we create a new subtarget since any
254 // creation will depend on the TM and the code generation flags on the
255 // function that reside in TargetOptions.
256 resetTargetOptions(F);
257 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
262 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
263 return TargetIRAnalysis([this](const Function &F) {
264 return TargetTransformInfo(ARMTTIImpl(this, F));
268 void ARMTargetMachine::anchor() {}
270 ARMTargetMachine::ARMTargetMachine(const Target &T, const Triple &TT,
271 StringRef CPU, StringRef FS,
272 const TargetOptions &Options,
273 Optional<Reloc::Model> RM,
274 CodeModel::Model CM, CodeGenOpt::Level OL,
276 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
278 if (!Subtarget.hasARMOps())
279 report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
280 "support ARM mode execution!");
283 void ARMLETargetMachine::anchor() {}
285 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
286 StringRef CPU, StringRef FS,
287 const TargetOptions &Options,
288 Optional<Reloc::Model> RM,
290 CodeGenOpt::Level OL)
291 : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
293 void ARMBETargetMachine::anchor() {}
295 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
296 StringRef CPU, StringRef FS,
297 const TargetOptions &Options,
298 Optional<Reloc::Model> RM,
300 CodeGenOpt::Level OL)
301 : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
303 void ThumbTargetMachine::anchor() {}
305 ThumbTargetMachine::ThumbTargetMachine(const Target &T, const Triple &TT,
306 StringRef CPU, StringRef FS,
307 const TargetOptions &Options,
308 Optional<Reloc::Model> RM,
310 CodeGenOpt::Level OL, bool isLittle)
311 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
315 void ThumbLETargetMachine::anchor() {}
317 ThumbLETargetMachine::ThumbLETargetMachine(const Target &T, const Triple &TT,
318 StringRef CPU, StringRef FS,
319 const TargetOptions &Options,
320 Optional<Reloc::Model> RM,
322 CodeGenOpt::Level OL)
323 : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
325 void ThumbBETargetMachine::anchor() {}
327 ThumbBETargetMachine::ThumbBETargetMachine(const Target &T, const Triple &TT,
328 StringRef CPU, StringRef FS,
329 const TargetOptions &Options,
330 Optional<Reloc::Model> RM,
332 CodeGenOpt::Level OL)
333 : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
336 /// ARM Code Generator Pass Configuration Options.
337 class ARMPassConfig : public TargetPassConfig {
339 ARMPassConfig(ARMBaseTargetMachine *TM, PassManagerBase &PM)
340 : TargetPassConfig(TM, PM) {}
342 ARMBaseTargetMachine &getARMTargetMachine() const {
343 return getTM<ARMBaseTargetMachine>();
346 void addIRPasses() override;
347 bool addPreISel() override;
348 bool addInstSelector() override;
349 void addPreRegAlloc() override;
350 void addPreSched2() override;
351 void addPreEmitPass() override;
355 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
356 return new ARMPassConfig(this, PM);
359 void ARMPassConfig::addIRPasses() {
360 if (TM->Options.ThreadModel == ThreadModel::Single)
361 addPass(createLowerAtomicPass());
363 addPass(createAtomicExpandPass(TM));
365 // Cmpxchg instructions are often used with a subsequent comparison to
366 // determine whether it succeeded. We can exploit existing control-flow in
367 // ldrex/strex loops to simplify this, but it needs tidying up.
368 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
369 addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
370 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
371 return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
374 TargetPassConfig::addIRPasses();
376 // Match interleaved memory accesses to ldN/stN intrinsics.
377 if (TM->getOptLevel() != CodeGenOpt::None)
378 addPass(createInterleavedAccessPass(TM));
381 bool ARMPassConfig::addPreISel() {
382 if ((TM->getOptLevel() != CodeGenOpt::None &&
383 EnableGlobalMerge == cl::BOU_UNSET) ||
384 EnableGlobalMerge == cl::BOU_TRUE) {
385 // FIXME: This is using the thumb1 only constant value for
386 // maximal global offset for merging globals. We may want
387 // to look into using the old value for non-thumb1 code of
388 // 4095 based on the TargetMachine, but this starts to become
389 // tricky when doing code gen per function.
390 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
391 (EnableGlobalMerge == cl::BOU_UNSET);
392 // Merging of extern globals is enabled by default on non-Mach-O as we
393 // expect it to be generally either beneficial or harmless. On Mach-O it
394 // is disabled as we emit the .subsections_via_symbols directive which
395 // means that merging extern globals is not safe.
396 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
397 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
398 MergeExternalByDefault));
404 bool ARMPassConfig::addInstSelector() {
405 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
409 void ARMPassConfig::addPreRegAlloc() {
410 if (getOptLevel() != CodeGenOpt::None) {
411 addPass(createMLxExpansionPass());
413 if (EnableARMLoadStoreOpt)
414 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
416 if (!DisableA15SDOptimization)
417 addPass(createA15SDOptimizerPass());
421 void ARMPassConfig::addPreSched2() {
422 if (getOptLevel() != CodeGenOpt::None) {
423 if (EnableARMLoadStoreOpt)
424 addPass(createARMLoadStoreOptimizationPass());
426 addPass(createExecutionDependencyFixPass(&ARM::DPRRegClass));
429 // Expand some pseudo instructions into multiple instructions to allow
430 // proper scheduling.
431 addPass(createARMExpandPseudoPass());
433 if (getOptLevel() != CodeGenOpt::None) {
434 // in v8, IfConversion depends on Thumb instruction widths
435 addPass(createThumb2SizeReductionPass([this](const Function &F) {
436 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
439 addPass(createIfConverter([this](const Function &F) {
440 return !this->TM->getSubtarget<ARMSubtarget>(F).isThumb1Only();
443 addPass(createThumb2ITBlockPass());
446 void ARMPassConfig::addPreEmitPass() {
447 addPass(createThumb2SizeReductionPass());
449 // Constant island pass work on unbundled instructions.
450 addPass(createUnpackMachineBundles([this](const Function &F) {
451 return this->TM->getSubtarget<ARMSubtarget>(F).isThumb2();
454 // Don't optimize barriers at -O0.
455 if (getOptLevel() != CodeGenOpt::None)
456 addPass(createARMOptimizeBarriersPass());
458 addPass(createARMConstantIslandPass());