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 "RISCV.h"
15 #include "RISCVTargetObjectFile.h"
16 #include "RISCVTargetTransformInfo.h"
17 #include "TargetInfo/RISCVTargetInfo.h"
18 #include "Utils/RISCVBaseInfo.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
22 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
23 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
24 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/IR/LegacyPassManager.h"
29 #include "llvm/InitializePasses.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Target/TargetOptions.h"
33 using namespace llvm;
34 
35 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVTarget() {
36   RegisterTargetMachine<RISCVTargetMachine> X(getTheRISCV32Target());
37   RegisterTargetMachine<RISCVTargetMachine> Y(getTheRISCV64Target());
38   auto PR = PassRegistry::getPassRegistry();
39   initializeGlobalISel(*PR);
40   initializeRISCVMergeBaseOffsetOptPass(*PR);
41   initializeRISCVExpandPseudoPass(*PR);
42 }
43 
44 static StringRef computeDataLayout(const Triple &TT) {
45   if (TT.isArch64Bit()) {
46     return "e-m:e-p:64:64-i64:64-i128:128-n64-S128";
47   } else {
48     assert(TT.isArch32Bit() && "only RV32 and RV64 are currently supported");
49     return "e-m:e-p:32:32-i64:64-n32-S128";
50   }
51 }
52 
53 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
54                                            Optional<Reloc::Model> RM) {
55   if (!RM.hasValue())
56     return Reloc::Static;
57   return *RM;
58 }
59 
60 RISCVTargetMachine::RISCVTargetMachine(const Target &T, const Triple &TT,
61                                        StringRef CPU, StringRef FS,
62                                        const TargetOptions &Options,
63                                        Optional<Reloc::Model> RM,
64                                        Optional<CodeModel::Model> CM,
65                                        CodeGenOpt::Level OL, bool JIT)
66     : LLVMTargetMachine(T, computeDataLayout(TT), TT, CPU, FS, Options,
67                         getEffectiveRelocModel(TT, RM),
68                         getEffectiveCodeModel(CM, CodeModel::Small), OL),
69       TLOF(std::make_unique<RISCVELFTargetObjectFile>()) {
70   initAsmInfo();
71 
72   // RISC-V supports the MachineOutliner.
73   setMachineOutliner(true);
74 }
75 
76 const RISCVSubtarget *
77 RISCVTargetMachine::getSubtargetImpl(const Function &F) const {
78   Attribute CPUAttr = F.getFnAttribute("target-cpu");
79   Attribute TuneAttr = F.getFnAttribute("tune-cpu");
80   Attribute FSAttr = F.getFnAttribute("target-features");
81 
82   std::string CPU =
83       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
84   std::string TuneCPU =
85       TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
86   std::string FS =
87       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
88   std::string Key = CPU + TuneCPU + FS;
89   auto &I = SubtargetMap[Key];
90   if (!I) {
91     // This needs to be done before we create a new subtarget since any
92     // creation will depend on the TM and the code generation flags on the
93     // function that reside in TargetOptions.
94     resetTargetOptions(F);
95     auto ABIName = Options.MCOptions.getABIName();
96     if (const MDString *ModuleTargetABI = dyn_cast_or_null<MDString>(
97             F.getParent()->getModuleFlag("target-abi"))) {
98       auto TargetABI = RISCVABI::getTargetABI(ABIName);
99       if (TargetABI != RISCVABI::ABI_Unknown &&
100           ModuleTargetABI->getString() != ABIName) {
101         report_fatal_error("-target-abi option != target-abi module flag");
102       }
103       ABIName = ModuleTargetABI->getString();
104     }
105     I = std::make_unique<RISCVSubtarget>(TargetTriple, CPU, TuneCPU, FS, ABIName, *this);
106   }
107   return I.get();
108 }
109 
110 TargetTransformInfo
111 RISCVTargetMachine::getTargetTransformInfo(const Function &F) {
112   return TargetTransformInfo(RISCVTTIImpl(this, F));
113 }
114 
115 namespace {
116 class RISCVPassConfig : public TargetPassConfig {
117 public:
118   RISCVPassConfig(RISCVTargetMachine &TM, PassManagerBase &PM)
119       : TargetPassConfig(TM, PM) {}
120 
121   RISCVTargetMachine &getRISCVTargetMachine() const {
122     return getTM<RISCVTargetMachine>();
123   }
124 
125   void addIRPasses() override;
126   bool addInstSelector() override;
127   bool addIRTranslator() override;
128   bool addLegalizeMachineIR() override;
129   bool addRegBankSelect() override;
130   bool addGlobalInstructionSelect() override;
131   void addPreEmitPass() override;
132   void addPreEmitPass2() override;
133   void addPreSched2() override;
134   void addPreRegAlloc() override;
135 };
136 }
137 
138 TargetPassConfig *RISCVTargetMachine::createPassConfig(PassManagerBase &PM) {
139   return new RISCVPassConfig(*this, PM);
140 }
141 
142 void RISCVPassConfig::addIRPasses() {
143   addPass(createAtomicExpandPass());
144   TargetPassConfig::addIRPasses();
145 }
146 
147 bool RISCVPassConfig::addInstSelector() {
148   addPass(createRISCVISelDag(getRISCVTargetMachine()));
149 
150   return false;
151 }
152 
153 bool RISCVPassConfig::addIRTranslator() {
154   addPass(new IRTranslator(getOptLevel()));
155   return false;
156 }
157 
158 bool RISCVPassConfig::addLegalizeMachineIR() {
159   addPass(new Legalizer());
160   return false;
161 }
162 
163 bool RISCVPassConfig::addRegBankSelect() {
164   addPass(new RegBankSelect());
165   return false;
166 }
167 
168 bool RISCVPassConfig::addGlobalInstructionSelect() {
169   addPass(new InstructionSelect());
170   return false;
171 }
172 
173 void RISCVPassConfig::addPreSched2() {}
174 
175 void RISCVPassConfig::addPreEmitPass() { addPass(&BranchRelaxationPassID); }
176 
177 void RISCVPassConfig::addPreEmitPass2() {
178   addPass(createRISCVExpandPseudoPass());
179   // Schedule the expansion of AMOs at the last possible moment, avoiding the
180   // possibility for other passes to break the requirements for forward
181   // progress in the LR/SC block.
182   addPass(createRISCVExpandAtomicPseudoPass());
183 }
184 
185 void RISCVPassConfig::addPreRegAlloc() {
186   if (TM->getOptLevel() != CodeGenOpt::None)
187     addPass(createRISCVMergeBaseOffsetOptPass());
188 }
189