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