[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / Target / PowerPC / PPCTargetMachine.cpp
blob82717300a48013a8b2f863dd8f3123fba0dad505
1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
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 // Top-level implementation for the PowerPC target.
11 //===----------------------------------------------------------------------===//
13 #include "PPCTargetMachine.h"
14 #include "MCTargetDesc/PPCMCTargetDesc.h"
15 #include "PPC.h"
16 #include "PPCMachineScheduler.h"
17 #include "PPCMacroFusion.h"
18 #include "PPCSubtarget.h"
19 #include "PPCTargetObjectFile.h"
20 #include "PPCTargetTransformInfo.h"
21 #include "TargetInfo/PowerPCTargetInfo.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
28 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
29 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
30 #include "llvm/CodeGen/GlobalISel/Localizer.h"
31 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
32 #include "llvm/CodeGen/MachineScheduler.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CodeGen.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Transforms/Scalar.h"
46 #include <cassert>
47 #include <memory>
48 #include <string>
50 using namespace llvm;
53 static cl::opt<bool>
54 EnableBranchCoalescing("enable-ppc-branch-coalesce", cl::Hidden,
55 cl::desc("enable coalescing of duplicate branches for PPC"));
56 static cl::
57 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
58 cl::desc("Disable CTR loops for PPC"));
60 static cl::
61 opt<bool> DisableInstrFormPrep("disable-ppc-instr-form-prep", cl::Hidden,
62 cl::desc("Disable PPC loop instr form prep"));
64 static cl::opt<bool>
65 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
66 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
68 static cl::
69 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
70 cl::desc("Disable VSX Swap Removal for PPC"));
72 static cl::
73 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
74 cl::desc("Disable machine peepholes for PPC"));
76 static cl::opt<bool>
77 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
78 cl::desc("Enable optimizations on complex GEPs"),
79 cl::init(true));
81 static cl::opt<bool>
82 EnablePrefetch("enable-ppc-prefetching",
83 cl::desc("enable software prefetching on PPC"),
84 cl::init(false), cl::Hidden);
86 static cl::opt<bool>
87 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
88 cl::desc("Add extra TOC register dependencies"),
89 cl::init(true), cl::Hidden);
91 static cl::opt<bool>
92 EnableMachineCombinerPass("ppc-machine-combiner",
93 cl::desc("Enable the machine combiner pass"),
94 cl::init(true), cl::Hidden);
96 static cl::opt<bool>
97 ReduceCRLogical("ppc-reduce-cr-logicals",
98 cl::desc("Expand eligible cr-logical binary ops to branches"),
99 cl::init(true), cl::Hidden);
100 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCTarget() {
101 // Register the targets
102 RegisterTargetMachine<PPCTargetMachine> A(getThePPC32Target());
103 RegisterTargetMachine<PPCTargetMachine> B(getThePPC32LETarget());
104 RegisterTargetMachine<PPCTargetMachine> C(getThePPC64Target());
105 RegisterTargetMachine<PPCTargetMachine> D(getThePPC64LETarget());
107 PassRegistry &PR = *PassRegistry::getPassRegistry();
108 #ifndef NDEBUG
109 initializePPCCTRLoopsVerifyPass(PR);
110 #endif
111 initializePPCLoopInstrFormPrepPass(PR);
112 initializePPCTOCRegDepsPass(PR);
113 initializePPCEarlyReturnPass(PR);
114 initializePPCVSXCopyPass(PR);
115 initializePPCVSXFMAMutatePass(PR);
116 initializePPCVSXSwapRemovalPass(PR);
117 initializePPCReduceCRLogicalsPass(PR);
118 initializePPCBSelPass(PR);
119 initializePPCBranchCoalescingPass(PR);
120 initializePPCBoolRetToIntPass(PR);
121 initializePPCExpandISELPass(PR);
122 initializePPCPreEmitPeepholePass(PR);
123 initializePPCTLSDynamicCallPass(PR);
124 initializePPCMIPeepholePass(PR);
125 initializePPCLowerMASSVEntriesPass(PR);
126 initializePPCExpandAtomicPseudoPass(PR);
127 initializeGlobalISel(PR);
130 static bool isLittleEndianTriple(const Triple &T) {
131 return T.getArch() == Triple::ppc64le || T.getArch() == Triple::ppcle;
134 /// Return the datalayout string of a subtarget.
135 static std::string getDataLayoutString(const Triple &T) {
136 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
137 std::string Ret;
139 // Most PPC* platforms are big endian, PPC(64)LE is little endian.
140 if (isLittleEndianTriple(T))
141 Ret = "e";
142 else
143 Ret = "E";
145 Ret += DataLayout::getManglingComponent(T);
147 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
148 // pointers.
149 if (!is64Bit || T.getOS() == Triple::Lv2)
150 Ret += "-p:32:32";
152 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
153 // documentation are wrong; these are correct (i.e. "what gcc does").
154 Ret += "-i64:64";
156 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
157 if (is64Bit)
158 Ret += "-n32:64";
159 else
160 Ret += "-n32";
162 // Specify the vector alignment explicitly. For v256i1 and v512i1, the
163 // calculated alignment would be 256*alignment(i1) and 512*alignment(i1),
164 // which is 256 and 512 bytes - way over aligned.
165 if (is64Bit && (T.isOSAIX() || T.isOSLinux()))
166 Ret += "-S128-v256:256:256-v512:512:512";
168 return Ret;
171 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
172 const Triple &TT) {
173 std::string FullFS = std::string(FS);
175 // Make sure 64-bit features are available when CPUname is generic
176 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
177 if (!FullFS.empty())
178 FullFS = "+64bit," + FullFS;
179 else
180 FullFS = "+64bit";
183 if (OL >= CodeGenOpt::Default) {
184 if (!FullFS.empty())
185 FullFS = "+crbits," + FullFS;
186 else
187 FullFS = "+crbits";
190 if (OL != CodeGenOpt::None) {
191 if (!FullFS.empty())
192 FullFS = "+invariant-function-descriptors," + FullFS;
193 else
194 FullFS = "+invariant-function-descriptors";
197 if (TT.isOSAIX()) {
198 if (!FullFS.empty())
199 FullFS = "+aix," + FullFS;
200 else
201 FullFS = "+aix";
204 return FullFS;
207 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
208 if (TT.isOSAIX())
209 return std::make_unique<TargetLoweringObjectFileXCOFF>();
211 return std::make_unique<PPC64LinuxTargetObjectFile>();
214 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
215 const TargetOptions &Options) {
216 if (Options.MCOptions.getABIName().startswith("elfv1"))
217 return PPCTargetMachine::PPC_ABI_ELFv1;
218 else if (Options.MCOptions.getABIName().startswith("elfv2"))
219 return PPCTargetMachine::PPC_ABI_ELFv2;
221 assert(Options.MCOptions.getABIName().empty() &&
222 "Unknown target-abi option!");
224 if (TT.isMacOSX())
225 return PPCTargetMachine::PPC_ABI_UNKNOWN;
227 switch (TT.getArch()) {
228 case Triple::ppc64le:
229 return PPCTargetMachine::PPC_ABI_ELFv2;
230 case Triple::ppc64:
231 return PPCTargetMachine::PPC_ABI_ELFv1;
232 default:
233 return PPCTargetMachine::PPC_ABI_UNKNOWN;
237 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
238 Optional<Reloc::Model> RM) {
239 assert((!TT.isOSAIX() || !RM.hasValue() || *RM == Reloc::PIC_) &&
240 "Invalid relocation model for AIX.");
242 if (RM.hasValue())
243 return *RM;
245 // Big Endian PPC and AIX default to PIC.
246 if (TT.getArch() == Triple::ppc64 || TT.isOSAIX())
247 return Reloc::PIC_;
249 // Rest are static by default.
250 return Reloc::Static;
253 static CodeModel::Model getEffectivePPCCodeModel(const Triple &TT,
254 Optional<CodeModel::Model> CM,
255 bool JIT) {
256 if (CM) {
257 if (*CM == CodeModel::Tiny)
258 report_fatal_error("Target does not support the tiny CodeModel", false);
259 if (*CM == CodeModel::Kernel)
260 report_fatal_error("Target does not support the kernel CodeModel", false);
261 return *CM;
264 if (JIT)
265 return CodeModel::Small;
266 if (TT.isOSAIX())
267 return CodeModel::Small;
269 assert(TT.isOSBinFormatELF() && "All remaining PPC OSes are ELF based.");
271 if (TT.isArch32Bit())
272 return CodeModel::Small;
274 assert(TT.isArch64Bit() && "Unsupported PPC architecture.");
275 return CodeModel::Medium;
279 static ScheduleDAGInstrs *createPPCMachineScheduler(MachineSchedContext *C) {
280 const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>();
281 ScheduleDAGMILive *DAG =
282 new ScheduleDAGMILive(C, ST.usePPCPreRASchedStrategy() ?
283 std::make_unique<PPCPreRASchedStrategy>(C) :
284 std::make_unique<GenericScheduler>(C));
285 // add DAG Mutations here.
286 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
287 if (ST.hasStoreFusion())
288 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
289 if (ST.hasFusion())
290 DAG->addMutation(createPowerPCMacroFusionDAGMutation());
292 return DAG;
295 static ScheduleDAGInstrs *createPPCPostMachineScheduler(
296 MachineSchedContext *C) {
297 const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>();
298 ScheduleDAGMI *DAG =
299 new ScheduleDAGMI(C, ST.usePPCPostRASchedStrategy() ?
300 std::make_unique<PPCPostRASchedStrategy>(C) :
301 std::make_unique<PostGenericScheduler>(C), true);
302 // add DAG Mutations here.
303 if (ST.hasStoreFusion())
304 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
305 if (ST.hasFusion())
306 DAG->addMutation(createPowerPCMacroFusionDAGMutation());
307 return DAG;
310 // The FeatureString here is a little subtle. We are modifying the feature
311 // string with what are (currently) non-function specific overrides as it goes
312 // into the LLVMTargetMachine constructor and then using the stored value in the
313 // Subtarget constructor below it.
314 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
315 StringRef CPU, StringRef FS,
316 const TargetOptions &Options,
317 Optional<Reloc::Model> RM,
318 Optional<CodeModel::Model> CM,
319 CodeGenOpt::Level OL, bool JIT)
320 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
321 computeFSAdditions(FS, OL, TT), Options,
322 getEffectiveRelocModel(TT, RM),
323 getEffectivePPCCodeModel(TT, CM, JIT), OL),
324 TLOF(createTLOF(getTargetTriple())),
325 TargetABI(computeTargetABI(TT, Options)),
326 Endianness(isLittleEndianTriple(TT) ? Endian::LITTLE : Endian::BIG) {
327 initAsmInfo();
330 PPCTargetMachine::~PPCTargetMachine() = default;
332 const PPCSubtarget *
333 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
334 Attribute CPUAttr = F.getFnAttribute("target-cpu");
335 Attribute FSAttr = F.getFnAttribute("target-features");
337 std::string CPU =
338 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
339 std::string FS =
340 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
342 // FIXME: This is related to the code below to reset the target options,
343 // we need to know whether or not the soft float flag is set on the
344 // function before we can generate a subtarget. We also need to use
345 // it as a key for the subtarget since that can be the only difference
346 // between two functions.
347 bool SoftFloat = F.getFnAttribute("use-soft-float").getValueAsBool();
348 // If the soft float attribute is set on the function turn on the soft float
349 // subtarget feature.
350 if (SoftFloat)
351 FS += FS.empty() ? "-hard-float" : ",-hard-float";
353 auto &I = SubtargetMap[CPU + FS];
354 if (!I) {
355 // This needs to be done before we create a new subtarget since any
356 // creation will depend on the TM and the code generation flags on the
357 // function that reside in TargetOptions.
358 resetTargetOptions(F);
359 I = std::make_unique<PPCSubtarget>(
360 TargetTriple, CPU,
361 // FIXME: It would be good to have the subtarget additions here
362 // not necessary. Anything that turns them on/off (overrides) ends
363 // up being put at the end of the feature string, but the defaults
364 // shouldn't require adding them. Fixing this means pulling Feature64Bit
365 // out of most of the target cpus in the .td file and making it set only
366 // as part of initialization via the TargetTriple.
367 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
369 return I.get();
372 //===----------------------------------------------------------------------===//
373 // Pass Pipeline Configuration
374 //===----------------------------------------------------------------------===//
376 namespace {
378 /// PPC Code Generator Pass Configuration Options.
379 class PPCPassConfig : public TargetPassConfig {
380 public:
381 PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM)
382 : TargetPassConfig(TM, PM) {
383 // At any optimization level above -O0 we use the Machine Scheduler and not
384 // the default Post RA List Scheduler.
385 if (TM.getOptLevel() != CodeGenOpt::None)
386 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
389 PPCTargetMachine &getPPCTargetMachine() const {
390 return getTM<PPCTargetMachine>();
393 void addIRPasses() override;
394 bool addPreISel() override;
395 bool addILPOpts() override;
396 bool addInstSelector() override;
397 void addMachineSSAOptimization() override;
398 void addPreRegAlloc() override;
399 void addPreSched2() override;
400 void addPreEmitPass() override;
401 void addPreEmitPass2() override;
402 // GlobalISEL
403 bool addIRTranslator() override;
404 bool addLegalizeMachineIR() override;
405 bool addRegBankSelect() override;
406 bool addGlobalInstructionSelect() override;
408 ScheduleDAGInstrs *
409 createMachineScheduler(MachineSchedContext *C) const override {
410 return createPPCMachineScheduler(C);
412 ScheduleDAGInstrs *
413 createPostMachineScheduler(MachineSchedContext *C) const override {
414 return createPPCPostMachineScheduler(C);
418 } // end anonymous namespace
420 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
421 return new PPCPassConfig(*this, PM);
424 void PPCPassConfig::addIRPasses() {
425 if (TM->getOptLevel() != CodeGenOpt::None)
426 addPass(createPPCBoolRetToIntPass());
427 addPass(createAtomicExpandPass());
429 // Lower generic MASSV routines to PowerPC subtarget-specific entries.
430 addPass(createPPCLowerMASSVEntriesPass());
432 // If explicitly requested, add explicit data prefetch intrinsics.
433 if (EnablePrefetch.getNumOccurrences() > 0)
434 addPass(createLoopDataPrefetchPass());
436 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
437 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
438 // and lower a GEP with multiple indices to either arithmetic operations or
439 // multiple GEPs with single index.
440 addPass(createSeparateConstOffsetFromGEPPass(true));
441 // Call EarlyCSE pass to find and remove subexpressions in the lowered
442 // result.
443 addPass(createEarlyCSEPass());
444 // Do loop invariant code motion in case part of the lowered result is
445 // invariant.
446 addPass(createLICMPass());
449 TargetPassConfig::addIRPasses();
452 bool PPCPassConfig::addPreISel() {
453 if (!DisableInstrFormPrep && getOptLevel() != CodeGenOpt::None)
454 addPass(createPPCLoopInstrFormPrepPass(getPPCTargetMachine()));
456 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
457 addPass(createHardwareLoopsPass());
459 return false;
462 bool PPCPassConfig::addILPOpts() {
463 addPass(&EarlyIfConverterID);
465 if (EnableMachineCombinerPass)
466 addPass(&MachineCombinerID);
468 return true;
471 bool PPCPassConfig::addInstSelector() {
472 // Install an instruction selector.
473 addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel()));
475 #ifndef NDEBUG
476 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
477 addPass(createPPCCTRLoopsVerify());
478 #endif
480 addPass(createPPCVSXCopyPass());
481 return false;
484 void PPCPassConfig::addMachineSSAOptimization() {
485 // PPCBranchCoalescingPass need to be done before machine sinking
486 // since it merges empty blocks.
487 if (EnableBranchCoalescing && getOptLevel() != CodeGenOpt::None)
488 addPass(createPPCBranchCoalescingPass());
489 TargetPassConfig::addMachineSSAOptimization();
490 // For little endian, remove where possible the vector swap instructions
491 // introduced at code generation to normalize vector element order.
492 if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
493 !DisableVSXSwapRemoval)
494 addPass(createPPCVSXSwapRemovalPass());
495 // Reduce the number of cr-logical ops.
496 if (ReduceCRLogical && getOptLevel() != CodeGenOpt::None)
497 addPass(createPPCReduceCRLogicalsPass());
498 // Target-specific peephole cleanups performed after instruction
499 // selection.
500 if (!DisableMIPeephole) {
501 addPass(createPPCMIPeepholePass());
502 addPass(&DeadMachineInstructionElimID);
506 void PPCPassConfig::addPreRegAlloc() {
507 if (getOptLevel() != CodeGenOpt::None) {
508 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
509 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
510 &PPCVSXFMAMutateID);
513 // FIXME: We probably don't need to run these for -fPIE.
514 if (getPPCTargetMachine().isPositionIndependent()) {
515 // FIXME: LiveVariables should not be necessary here!
516 // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on
517 // LiveVariables. This (unnecessary) dependency has been removed now,
518 // however a stage-2 clang build fails without LiveVariables computed here.
519 addPass(&LiveVariablesID);
520 addPass(createPPCTLSDynamicCallPass());
522 if (EnableExtraTOCRegDeps)
523 addPass(createPPCTOCRegDepsPass());
525 if (getOptLevel() != CodeGenOpt::None)
526 addPass(&MachinePipelinerID);
529 void PPCPassConfig::addPreSched2() {
530 if (getOptLevel() != CodeGenOpt::None)
531 addPass(&IfConverterID);
534 void PPCPassConfig::addPreEmitPass() {
535 addPass(createPPCPreEmitPeepholePass());
536 addPass(createPPCExpandISELPass());
538 if (getOptLevel() != CodeGenOpt::None)
539 addPass(createPPCEarlyReturnPass());
542 void PPCPassConfig::addPreEmitPass2() {
543 // Schedule the expansion of AMOs at the last possible moment, avoiding the
544 // possibility for other passes to break the requirements for forward
545 // progress in the LL/SC block.
546 addPass(createPPCExpandAtomicPseudoPass());
547 // Must run branch selection immediately preceding the asm printer.
548 addPass(createPPCBranchSelectionPass());
551 TargetTransformInfo
552 PPCTargetMachine::getTargetTransformInfo(const Function &F) {
553 return TargetTransformInfo(PPCTTIImpl(this, F));
556 bool PPCTargetMachine::isLittleEndian() const {
557 assert(Endianness != Endian::NOT_DETECTED &&
558 "Unable to determine endianness");
559 return Endianness == Endian::LITTLE;
562 static MachineSchedRegistry
563 PPCPreRASchedRegistry("ppc-prera",
564 "Run PowerPC PreRA specific scheduler",
565 createPPCMachineScheduler);
567 static MachineSchedRegistry
568 PPCPostRASchedRegistry("ppc-postra",
569 "Run PowerPC PostRA specific scheduler",
570 createPPCPostMachineScheduler);
572 // Global ISEL
573 bool PPCPassConfig::addIRTranslator() {
574 addPass(new IRTranslator());
575 return false;
578 bool PPCPassConfig::addLegalizeMachineIR() {
579 addPass(new Legalizer());
580 return false;
583 bool PPCPassConfig::addRegBankSelect() {
584 addPass(new RegBankSelect());
585 return false;
588 bool PPCPassConfig::addGlobalInstructionSelect() {
589 addPass(new InstructionSelect(getOptLevel()));
590 return false;