1//===-- MipsTargetMachine.cpp - Define TargetMachine for Mips -------------===//
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 Mips target spec.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MipsTargetMachine.h"
14#include "MCTargetDesc/MipsABIInfo.h"
15#include "MCTargetDesc/MipsMCTargetDesc.h"
16#include "Mips.h"
17#include "Mips16ISelDAGToDAG.h"
18#include "MipsMachineFunction.h"
19#include "MipsSEISelDAGToDAG.h"
20#include "MipsSubtarget.h"
21#include "MipsTargetObjectFile.h"
22#include "MipsTargetTransformInfo.h"
23#include "TargetInfo/MipsTargetInfo.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Analysis/TargetTransformInfo.h"
26#include "llvm/CodeGen/BasicTTIImpl.h"
27#include "llvm/CodeGen/GlobalISel/CSEInfo.h"
28#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
29#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
30#include "llvm/CodeGen/GlobalISel/Legalizer.h"
31#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/CodeGen/TargetPassConfig.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/Function.h"
37#include "llvm/InitializePasses.h"
38#include "llvm/MC/TargetRegistry.h"
39#include "llvm/Support/CodeGen.h"
40#include "llvm/Support/Compiler.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Target/TargetOptions.h"
44#include <optional>
45#include <string>
46
47using namespace llvm;
48
49#define DEBUG_TYPE "mips"
50
51static cl::opt<bool>
52 EnableMulMulFix("mfix4300", cl::init(Val: false),
53 cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden);
54
55static cl::opt<bool> MipsOs16(
56 "mips-os16", cl::init(Val: false),
57 cl::desc("Compile all functions that don't use floating point as Mips 16"),
58 cl::Hidden);
59
60extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget() {
61 // Register the target.
62 RegisterTargetMachine<MipsebTargetMachine> X(getTheMipsTarget());
63 RegisterTargetMachine<MipselTargetMachine> Y(getTheMipselTarget());
64 RegisterTargetMachine<MipsebTargetMachine> A(getTheMips64Target());
65 RegisterTargetMachine<MipselTargetMachine> B(getTheMips64elTarget());
66
67 PassRegistry *PR = PassRegistry::getPassRegistry();
68 initializeGlobalISel(*PR);
69 initializeMipsAsmPrinterPass(*PR);
70 initializeMipsDelaySlotFillerPass(*PR);
71 initializeMipsBranchExpansionPass(*PR);
72 initializeMicroMipsSizeReducePass(*PR);
73 initializeMipsPreLegalizerCombinerPass(*PR);
74 initializeMipsPostLegalizerCombinerPass(*PR);
75 initializeMipsMulMulBugFixPass(*PR);
76 initializeMipsDAGToDAGISelLegacyPass(*PR);
77 initializeMipsSetMachineRegisterFlagsPass(*PR);
78}
79
80static std::unique_ptr<TargetLoweringObjectFile>
81createTLOF(const Triple &TT, bool UseSmallSection) {
82 if (TT.isOSBinFormatCOFF())
83 return std::make_unique<TargetLoweringObjectFileCOFF>();
84 return std::make_unique<MipsTargetObjectFile>(args&: UseSmallSection);
85}
86
87static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
88 return RM.value_or(u: Reloc::Static);
89}
90
91// On function prologue, the stack is created by decrementing
92// its pointer. Once decremented, all references are done with positive
93// offset from the stack/frame pointer, using StackGrowsUp enables
94// an easier handling.
95// Using CodeModel::Large enables different CALL behavior.
96MipsTargetMachine::MipsTargetMachine(const Target &T, const Triple &TT,
97 StringRef CPU, StringRef FS,
98 const TargetOptions &Options,
99 std::optional<Reloc::Model> RM,
100 std::optional<CodeModel::Model> CM,
101 CodeGenOptLevel OL, bool JIT,
102 bool isLittle)
103 : CodeGenTargetMachineImpl(T, TT, CPU, FS, Options,
104 getEffectiveRelocModel(RM),
105 getEffectiveCodeModel(CM, Default: CodeModel::Small), OL),
106 isLittle(isLittle), IsJIT(JIT),
107 DefaultSubtarget(TT, CPU, FS, Options.MCOptions.getABIName(), isLittle,
108 *this, std::nullopt),
109 TLOF(createTLOF(TT, UseSmallSection: DefaultSubtarget.useSmallSection())) {
110 initAsmInfo();
111
112 // Mips supports the debug entry values.
113 setSupportsDebugEntryValues(true);
114}
115
116MipsTargetMachine::~MipsTargetMachine() = default;
117
118void MipsebTargetMachine::anchor() {}
119
120MipsebTargetMachine::MipsebTargetMachine(const Target &T, const Triple &TT,
121 StringRef CPU, StringRef FS,
122 const TargetOptions &Options,
123 std::optional<Reloc::Model> RM,
124 std::optional<CodeModel::Model> CM,
125 CodeGenOptLevel OL, bool JIT)
126 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
127
128void MipselTargetMachine::anchor() {}
129
130MipselTargetMachine::MipselTargetMachine(const Target &T, const Triple &TT,
131 StringRef CPU, StringRef FS,
132 const TargetOptions &Options,
133 std::optional<Reloc::Model> RM,
134 std::optional<CodeModel::Model> CM,
135 CodeGenOptLevel OL, bool JIT)
136 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
137
138const MipsSubtarget *
139MipsTargetMachine::getSubtargetImpl(const Function &F) const {
140 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
141 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
142
143 std::string CPU =
144 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
145 std::string FS =
146 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
147 bool hasMips16Attr = F.getFnAttribute(Kind: "mips16").isValid();
148 bool hasNoMips16Attr = F.getFnAttribute(Kind: "nomips16").isValid();
149
150 bool HasMicroMipsAttr = F.getFnAttribute(Kind: "micromips").isValid();
151 bool HasNoMicroMipsAttr = F.getFnAttribute(Kind: "nomicromips").isValid();
152
153 // FIXME: This is related to the code below to reset the target options,
154 // we need to know whether or not the soft float flag is set on the
155 // function, so we can enable it as a subtarget feature.
156 bool softFloat = F.getFnAttribute(Kind: "use-soft-float").getValueAsBool();
157
158 if (hasMips16Attr)
159 FS += FS.empty() ? "+mips16" : ",+mips16";
160 else if (hasNoMips16Attr)
161 FS += FS.empty() ? "-mips16" : ",-mips16";
162 if (HasMicroMipsAttr)
163 FS += FS.empty() ? "+micromips" : ",+micromips";
164 else if (HasNoMicroMipsAttr)
165 FS += FS.empty() ? "-micromips" : ",-micromips";
166 if (softFloat)
167 FS += FS.empty() ? "+soft-float" : ",+soft-float";
168
169 StringRef ABIName = getTargetABIName(M: *F.getParent());
170
171 auto &I = SubtargetMap[CPU + FS + ABIName.str()];
172 if (!I) {
173 I = std::make_unique<MipsSubtarget>(
174 args: TargetTriple, args&: CPU, args&: FS, args&: ABIName, args: isLittle, args: *this,
175 args: MaybeAlign(F.getParent()->getOverrideStackAlignment()));
176 }
177 return I.get();
178}
179
180namespace {
181
182/// Mips Code Generator Pass Configuration Options.
183class MipsPassConfig : public TargetPassConfig {
184public:
185 MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
186 : TargetPassConfig(TM, PM) {
187 // The current implementation of long branch pass requires a scratch
188 // register ($at) to be available before branch instructions. Tail merging
189 // can break this requirement.
190 EnableTailMerge = false;
191 EnableLoopTermFold = true;
192 }
193
194 MipsTargetMachine &getMipsTargetMachine() const {
195 return getTM<MipsTargetMachine>();
196 }
197
198 void addIRPasses() override;
199 bool addInstSelector() override;
200 void addPreEmitPass() override;
201 void addPreRegAlloc() override;
202 bool addIRTranslator() override;
203 void addPreLegalizeMachineIR() override;
204 bool addLegalizeMachineIR() override;
205 void addPreRegBankSelect() override;
206 bool addRegBankSelect() override;
207 bool addGlobalInstructionSelect() override;
208
209 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
210};
211
212} // end anonymous namespace
213
214TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM) {
215 return new MipsPassConfig(*this, PM);
216}
217
218std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
219 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
220}
221
222void MipsPassConfig::addIRPasses() {
223 TargetPassConfig::addIRPasses();
224 addPass(P: createAtomicExpandLegacyPass());
225 if (MipsOs16)
226 addPass(P: createMipsOs16Pass());
227 addPass(P: createMips16HardFloatPass());
228}
229// Install an instruction selector pass using
230// the ISelDag to gen Mips code.
231bool MipsPassConfig::addInstSelector() {
232 addPass(P: createMips16ISelDag(TM&: getMipsTargetMachine(), OptLevel: getOptLevel()));
233 addPass(P: createMipsSEISelDag(TM&: getMipsTargetMachine(), OptLevel: getOptLevel()));
234 return false;
235}
236
237void MipsPassConfig::addPreRegAlloc() {
238 addPass(P: createMipsOptimizePICCallPass());
239 addPass(P: createMipsSetMachineRegisterFlagsPass());
240}
241
242TargetTransformInfo
243MipsTargetMachine::getTargetTransformInfo(const Function &F) const {
244 LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
245 return TargetTransformInfo(std::make_unique<MipsTTIImpl>(args: this, args: F));
246}
247
248MachineFunctionInfo *MipsTargetMachine::createMachineFunctionInfo(
249 BumpPtrAllocator &Allocator, const Function &F,
250 const TargetSubtargetInfo *STI) const {
251 return MipsFunctionInfo::create<MipsFunctionInfo>(Allocator, F, STI);
252}
253
254// Implemented by targets that want to run passes immediately before
255// machine code is emitted.
256void MipsPassConfig::addPreEmitPass() {
257 // Expand pseudo instructions that are sensitive to register allocation.
258 addPass(P: createMipsExpandPseudoPass());
259
260 // The microMIPS size reduction pass performs instruction reselection for
261 // instructions which can be remapped to a 16 bit instruction.
262 addPass(P: createMicroMipsSizeReducePass());
263
264 // This pass inserts a nop instruction between two back-to-back multiplication
265 // instructions when the "mfix4300" flag is passed.
266 if (EnableMulMulFix)
267 addPass(P: createMipsMulMulBugPass());
268
269 // The delay slot filler pass can potientially create forbidden slot hazards
270 // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
271 addPass(P: createMipsDelaySlotFillerPass());
272
273 // This pass expands branches and takes care about the forbidden slot hazards.
274 // Expanding branches may potentially create forbidden slot hazards for
275 // MIPSR6, and fixing such hazard may potentially break a branch by extending
276 // its offset out of range. That's why this pass combine these two tasks, and
277 // runs them alternately until one of them finishes without any changes. Only
278 // then we can be sure that all branches are expanded properly and no hazards
279 // exists.
280 // Any new pass should go before this pass.
281 addPass(P: createMipsBranchExpansion());
282
283 addPass(P: createMipsConstantIslandPass());
284}
285
286bool MipsPassConfig::addIRTranslator() {
287 addPass(P: new IRTranslatorLegacy(getOptLevel()));
288 return false;
289}
290
291void MipsPassConfig::addPreLegalizeMachineIR() {
292 addPass(P: createMipsPreLegalizeCombiner());
293}
294
295bool MipsPassConfig::addLegalizeMachineIR() {
296 addPass(P: new LegalizerLegacy());
297 return false;
298}
299
300void MipsPassConfig::addPreRegBankSelect() {
301 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
302 addPass(P: createMipsPostLegalizeCombiner(IsOptNone));
303}
304
305bool MipsPassConfig::addRegBankSelect() {
306 addPass(P: new RegBankSelectLegacy());
307 return false;
308}
309
310bool MipsPassConfig::addGlobalInstructionSelect() {
311 addPass(P: new InstructionSelectLegacy(getOptLevel()));
312 return false;
313}
314