1 //===-- RISCVTargetMachine.cpp - Define TargetMachine for RISCV -----------===//
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 // Implements the info about RISCV target spec.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RISCVTargetMachine.h"
14 #include "MCTargetDesc/RISCVBaseInfo.h"
15 #include "RISCV.h"
16 #include "RISCVMachineFunctionInfo.h"
17 #include "RISCVTargetObjectFile.h"
18 #include "RISCVTargetTransformInfo.h"
19 #include "TargetInfo/RISCVTargetInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
23 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
24 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
25 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
26 #include "llvm/CodeGen/MIRParser/MIParser.h"
27 #include "llvm/CodeGen/MIRYamlMapping.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/TargetPassConfig.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/MC/TargetRegistry.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37 
38 static cl::opt<bool> EnableRedundantCopyElimination(
39     "riscv-enable-copyelim",
40     cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
41     cl::Hidden);
42 
43 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVTarget() {
44   RegisterTargetMachine<RISCVTargetMachine> X(getTheRISCV32Target());
45   RegisterTargetMachine<RISCVTargetMachine> Y(getTheRISCV64Target());
46   auto *PR = PassRegistry::getPassRegistry();
47   initializeGlobalISel(*PR);
48   initializeRISCVGatherScatterLoweringPass(*PR);
49   initializeRISCVMergeBaseOffsetOptPass(*PR);
50   initializeRISCVSExtWRemovalPass(*PR);
51   initializeRISCVExpandPseudoPass(*PR);
52   initializeRISCVInsertVSETVLIPass(*PR);
53 }
54 
55 static StringRef computeDataLayout(const Triple &TT) {
56   if (TT.isArch64Bit())
57     return "e-m:e-p:64:64-i64:64-i128:128-n64-S128";
58   assert(TT.isArch32Bit() && "only RV32 and RV64 are currently supported");
59   return "e-m:e-p:32:32-i64:64-n32-S128";
60 }
61 
62 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
63                                            Optional<Reloc::Model> RM) {
64   if (!RM.hasValue())
65     return Reloc::Static;
66   return *RM;
67 }
68 
69 RISCVTargetMachine::RISCVTargetMachine(const Target &T, const Triple &TT,
70                                        StringRef CPU, StringRef FS,
71                                        const TargetOptions &Options,
72                                        Optional<Reloc::Model> RM,
73                                        Optional<CodeModel::Model> CM,
74                                        CodeGenOpt::Level OL, bool JIT)
75     : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
76                         getEffectiveRelocModel(TT, RM),
77                         getEffectiveCodeModel(CM, CodeModel::Small), OL),
78       TLOF(std::make_unique<RISCVELFTargetObjectFile>()) {
79   initAsmInfo();
80 
81   // RISC-V supports the MachineOutliner.
82   setMachineOutliner(true);
83 }
84 
85 const RISCVSubtarget *
86 RISCVTargetMachine::getSubtargetImpl(const Function &F) const {
87   Attribute CPUAttr = F.getFnAttribute("target-cpu");
88   Attribute TuneAttr = F.getFnAttribute("tune-cpu");
89   Attribute FSAttr = F.getFnAttribute("target-features");
90 
91   std::string CPU =
92       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
93   std::string TuneCPU =
94       TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
95   std::string FS =
96       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
97   std::string Key = CPU + TuneCPU + FS;
98   auto &I = SubtargetMap[Key];
99   if (!I) {
100     // This needs to be done before we create a new subtarget since any
101     // creation will depend on the TM and the code generation flags on the
102     // function that reside in TargetOptions.
103     resetTargetOptions(F);
104     auto ABIName = Options.MCOptions.getABIName();
105     if (const MDString *ModuleTargetABI = dyn_cast_or_null<MDString>(
106             F.getParent()->getModuleFlag("target-abi"))) {
107       auto TargetABI = RISCVABI::getTargetABI(ABIName);
108       if (TargetABI != RISCVABI::ABI_Unknown &&
109           ModuleTargetABI->getString() != ABIName) {
110         report_fatal_error("-target-abi option != target-abi module flag");
111       }
112       ABIName = ModuleTargetABI->getString();
113     }
114     I = std::make_unique<RISCVSubtarget>(TargetTriple, CPU, TuneCPU, FS, ABIName, *this);
115   }
116   return I.get();
117 }
118 
119 TargetTransformInfo
120 RISCVTargetMachine::getTargetTransformInfo(const Function &F) const {
121   return TargetTransformInfo(RISCVTTIImpl(this, F));
122 }
123 
124 // A RISC-V hart has a single byte-addressable address space of 2^XLEN bytes
125 // for all memory accesses, so it is reasonable to assume that an
126 // implementation has no-op address space casts. If an implementation makes a
127 // change to this, they can override it here.
128 bool RISCVTargetMachine::isNoopAddrSpaceCast(unsigned SrcAS,
129                                              unsigned DstAS) const {
130   return true;
131 }
132 
133 namespace {
134 class RISCVPassConfig : public TargetPassConfig {
135 public:
136   RISCVPassConfig(RISCVTargetMachine &TM, PassManagerBase &PM)
137       : TargetPassConfig(TM, PM) {}
138 
139   RISCVTargetMachine &getRISCVTargetMachine() const {
140     return getTM<RISCVTargetMachine>();
141   }
142 
143   void addIRPasses() override;
144   bool addInstSelector() override;
145   bool addIRTranslator() override;
146   bool addLegalizeMachineIR() override;
147   bool addRegBankSelect() override;
148   bool addGlobalInstructionSelect() override;
149   void addPreEmitPass() override;
150   void addPreEmitPass2() override;
151   void addPreSched2() override;
152   void addMachineSSAOptimization() override;
153   void addPreRegAlloc() override;
154   void addPostRegAlloc() override;
155 };
156 } // namespace
157 
158 TargetPassConfig *RISCVTargetMachine::createPassConfig(PassManagerBase &PM) {
159   return new RISCVPassConfig(*this, PM);
160 }
161 
162 void RISCVPassConfig::addIRPasses() {
163   addPass(createAtomicExpandPass());
164 
165   addPass(createRISCVGatherScatterLoweringPass());
166 
167   TargetPassConfig::addIRPasses();
168 }
169 
170 bool RISCVPassConfig::addInstSelector() {
171   addPass(createRISCVISelDag(getRISCVTargetMachine()));
172 
173   return false;
174 }
175 
176 bool RISCVPassConfig::addIRTranslator() {
177   addPass(new IRTranslator(getOptLevel()));
178   return false;
179 }
180 
181 bool RISCVPassConfig::addLegalizeMachineIR() {
182   addPass(new Legalizer());
183   return false;
184 }
185 
186 bool RISCVPassConfig::addRegBankSelect() {
187   addPass(new RegBankSelect());
188   return false;
189 }
190 
191 bool RISCVPassConfig::addGlobalInstructionSelect() {
192   addPass(new InstructionSelect(getOptLevel()));
193   return false;
194 }
195 
196 void RISCVPassConfig::addPreSched2() {}
197 
198 void RISCVPassConfig::addPreEmitPass() { addPass(&BranchRelaxationPassID); }
199 
200 void RISCVPassConfig::addPreEmitPass2() {
201   addPass(createRISCVExpandPseudoPass());
202   // Schedule the expansion of AMOs at the last possible moment, avoiding the
203   // possibility for other passes to break the requirements for forward
204   // progress in the LR/SC block.
205   addPass(createRISCVExpandAtomicPseudoPass());
206 }
207 
208 void RISCVPassConfig::addMachineSSAOptimization() {
209   TargetPassConfig::addMachineSSAOptimization();
210 
211   if (TM->getTargetTriple().getArch() == Triple::riscv64)
212     addPass(createRISCVSExtWRemovalPass());
213 }
214 
215 void RISCVPassConfig::addPreRegAlloc() {
216   if (TM->getOptLevel() != CodeGenOpt::None)
217     addPass(createRISCVMergeBaseOffsetOptPass());
218   addPass(createRISCVInsertVSETVLIPass());
219 }
220 
221 void RISCVPassConfig::addPostRegAlloc() {
222   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
223     addPass(createRISCVRedundantCopyEliminationPass());
224 }
225 
226 yaml::MachineFunctionInfo *
227 RISCVTargetMachine::createDefaultFuncInfoYAML() const {
228   return new yaml::RISCVMachineFunctionInfo();
229 }
230 
231 yaml::MachineFunctionInfo *
232 RISCVTargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
233   const auto *MFI = MF.getInfo<RISCVMachineFunctionInfo>();
234   return new yaml::RISCVMachineFunctionInfo(*MFI);
235 }
236 
237 bool RISCVTargetMachine::parseMachineFunctionInfo(
238     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
239     SMDiagnostic &Error, SMRange &SourceRange) const {
240   const auto &YamlMFI =
241       static_cast<const yaml::RISCVMachineFunctionInfo &>(MFI);
242   PFS.MF.getInfo<RISCVMachineFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
243   return false;
244 }
245