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 "MipsSEISelDAGToDAG.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetObjectFile.h"
21 #include "MipsTargetTransformInfo.h"
22 #include "TargetInfo/MipsTargetInfo.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/CodeGen/BasicTTIImpl.h"
28 #include "llvm/CodeGen/GlobalISel/CSEInfo.h"
29 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
30 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
31 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
32 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/CodeGen/TargetPassConfig.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/MC/TargetRegistry.h"
40 #include "llvm/Support/CodeGen.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include <string>
45
46 using namespace llvm;
47
48 #define DEBUG_TYPE "mips"
49
50 static cl::opt<bool>
51 EnableMulMulFix("mfix4300", cl::init(false),
52 cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden);
53
LLVMInitializeMipsTarget()54 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget() {
55 // Register the target.
56 RegisterTargetMachine<MipsebTargetMachine> X(getTheMipsTarget());
57 RegisterTargetMachine<MipselTargetMachine> Y(getTheMipselTarget());
58 RegisterTargetMachine<MipsebTargetMachine> A(getTheMips64Target());
59 RegisterTargetMachine<MipselTargetMachine> B(getTheMips64elTarget());
60
61 PassRegistry *PR = PassRegistry::getPassRegistry();
62 initializeGlobalISel(*PR);
63 initializeMipsDelaySlotFillerPass(*PR);
64 initializeMipsBranchExpansionPass(*PR);
65 initializeMicroMipsSizeReducePass(*PR);
66 initializeMipsPreLegalizerCombinerPass(*PR);
67 initializeMipsPostLegalizerCombinerPass(*PR);
68 initializeMipsMulMulBugFixPass(*PR);
69 }
70
computeDataLayout(const Triple & TT,StringRef CPU,const TargetOptions & Options,bool isLittle)71 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
72 const TargetOptions &Options,
73 bool isLittle) {
74 std::string Ret;
75 MipsABIInfo ABI = MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions);
76
77 // There are both little and big endian mips.
78 if (isLittle)
79 Ret += "e";
80 else
81 Ret += "E";
82
83 if (ABI.IsO32())
84 Ret += "-m:m";
85 else
86 Ret += "-m:e";
87
88 // Pointers are 32 bit on some ABIs.
89 if (!ABI.IsN64())
90 Ret += "-p:32:32";
91
92 // 8 and 16 bit integers only need to have natural alignment, but try to
93 // align them to 32 bits. 64 bit integers have natural alignment.
94 Ret += "-i8:8:32-i16:16:32-i64:64";
95
96 // 32 bit registers are always available and the stack is at least 64 bit
97 // aligned. On N64 64 bit registers are also available and the stack is
98 // 128 bit aligned.
99 if (ABI.IsN64() || ABI.IsN32())
100 Ret += "-n32:64-S128";
101 else
102 Ret += "-n32-S64";
103
104 return Ret;
105 }
106
getEffectiveRelocModel(bool JIT,Optional<Reloc::Model> RM)107 static Reloc::Model getEffectiveRelocModel(bool JIT,
108 Optional<Reloc::Model> RM) {
109 if (!RM || JIT)
110 return Reloc::Static;
111 return *RM;
112 }
113
114 // On function prologue, the stack is created by decrementing
115 // its pointer. Once decremented, all references are done with positive
116 // offset from the stack/frame pointer, using StackGrowsUp enables
117 // an easier handling.
118 // Using CodeModel::Large enables different CALL behavior.
MipsTargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,Optional<Reloc::Model> RM,Optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT,bool isLittle)119 MipsTargetMachine::MipsTargetMachine(const Target &T, const Triple &TT,
120 StringRef CPU, StringRef FS,
121 const TargetOptions &Options,
122 Optional<Reloc::Model> RM,
123 Optional<CodeModel::Model> CM,
124 CodeGenOpt::Level OL, bool JIT,
125 bool isLittle)
126 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
127 CPU, FS, Options, getEffectiveRelocModel(JIT, RM),
128 getEffectiveCodeModel(CM, CodeModel::Small), OL),
129 isLittle(isLittle), TLOF(std::make_unique<MipsTargetObjectFile>()),
130 ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
131 Subtarget(nullptr), DefaultSubtarget(TT, CPU, FS, isLittle, *this, None),
132 NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
133 isLittle, *this, None),
134 Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
135 isLittle, *this, None) {
136 Subtarget = &DefaultSubtarget;
137 initAsmInfo();
138
139 // Mips supports the debug entry values.
140 setSupportsDebugEntryValues(true);
141 }
142
143 MipsTargetMachine::~MipsTargetMachine() = default;
144
anchor()145 void MipsebTargetMachine::anchor() {}
146
MipsebTargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,Optional<Reloc::Model> RM,Optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT)147 MipsebTargetMachine::MipsebTargetMachine(const Target &T, const Triple &TT,
148 StringRef CPU, StringRef FS,
149 const TargetOptions &Options,
150 Optional<Reloc::Model> RM,
151 Optional<CodeModel::Model> CM,
152 CodeGenOpt::Level OL, bool JIT)
153 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
154
anchor()155 void MipselTargetMachine::anchor() {}
156
MipselTargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,Optional<Reloc::Model> RM,Optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT)157 MipselTargetMachine::MipselTargetMachine(const Target &T, const Triple &TT,
158 StringRef CPU, StringRef FS,
159 const TargetOptions &Options,
160 Optional<Reloc::Model> RM,
161 Optional<CodeModel::Model> CM,
162 CodeGenOpt::Level OL, bool JIT)
163 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
164
165 const MipsSubtarget *
getSubtargetImpl(const Function & F) const166 MipsTargetMachine::getSubtargetImpl(const Function &F) const {
167 Attribute CPUAttr = F.getFnAttribute("target-cpu");
168 Attribute FSAttr = F.getFnAttribute("target-features");
169
170 std::string CPU =
171 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
172 std::string FS =
173 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
174 bool hasMips16Attr = F.getFnAttribute("mips16").isValid();
175 bool hasNoMips16Attr = F.getFnAttribute("nomips16").isValid();
176
177 bool HasMicroMipsAttr = F.getFnAttribute("micromips").isValid();
178 bool HasNoMicroMipsAttr = F.getFnAttribute("nomicromips").isValid();
179
180 // FIXME: This is related to the code below to reset the target options,
181 // we need to know whether or not the soft float flag is set on the
182 // function, so we can enable it as a subtarget feature.
183 bool softFloat = F.getFnAttribute("use-soft-float").getValueAsBool();
184
185 if (hasMips16Attr)
186 FS += FS.empty() ? "+mips16" : ",+mips16";
187 else if (hasNoMips16Attr)
188 FS += FS.empty() ? "-mips16" : ",-mips16";
189 if (HasMicroMipsAttr)
190 FS += FS.empty() ? "+micromips" : ",+micromips";
191 else if (HasNoMicroMipsAttr)
192 FS += FS.empty() ? "-micromips" : ",-micromips";
193 if (softFloat)
194 FS += FS.empty() ? "+soft-float" : ",+soft-float";
195
196 auto &I = SubtargetMap[CPU + FS];
197 if (!I) {
198 // This needs to be done before we create a new subtarget since any
199 // creation will depend on the TM and the code generation flags on the
200 // function that reside in TargetOptions.
201 resetTargetOptions(F);
202 I = std::make_unique<MipsSubtarget>(
203 TargetTriple, CPU, FS, isLittle, *this,
204 MaybeAlign(F.getParent()->getOverrideStackAlignment()));
205 }
206 return I.get();
207 }
208
resetSubtarget(MachineFunction * MF)209 void MipsTargetMachine::resetSubtarget(MachineFunction *MF) {
210 LLVM_DEBUG(dbgs() << "resetSubtarget\n");
211
212 Subtarget = &MF->getSubtarget<MipsSubtarget>();
213 }
214
215 namespace {
216
217 /// Mips Code Generator Pass Configuration Options.
218 class MipsPassConfig : public TargetPassConfig {
219 public:
MipsPassConfig(MipsTargetMachine & TM,PassManagerBase & PM)220 MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
221 : TargetPassConfig(TM, PM) {
222 // The current implementation of long branch pass requires a scratch
223 // register ($at) to be available before branch instructions. Tail merging
224 // can break this requirement, so disable it when long branch pass is
225 // enabled.
226 EnableTailMerge = !getMipsSubtarget().enableLongBranchPass();
227 }
228
getMipsTargetMachine() const229 MipsTargetMachine &getMipsTargetMachine() const {
230 return getTM<MipsTargetMachine>();
231 }
232
getMipsSubtarget() const233 const MipsSubtarget &getMipsSubtarget() const {
234 return *getMipsTargetMachine().getSubtargetImpl();
235 }
236
237 void addIRPasses() override;
238 bool addInstSelector() override;
239 void addPreEmitPass() override;
240 void addPreRegAlloc() override;
241 bool addIRTranslator() override;
242 void addPreLegalizeMachineIR() override;
243 bool addLegalizeMachineIR() override;
244 void addPreRegBankSelect() override;
245 bool addRegBankSelect() override;
246 bool addGlobalInstructionSelect() override;
247
248 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
249 };
250
251 } // end anonymous namespace
252
createPassConfig(PassManagerBase & PM)253 TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM) {
254 return new MipsPassConfig(*this, PM);
255 }
256
getCSEConfig() const257 std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
258 return getStandardCSEConfigForOpt(TM->getOptLevel());
259 }
260
addIRPasses()261 void MipsPassConfig::addIRPasses() {
262 TargetPassConfig::addIRPasses();
263 addPass(createAtomicExpandPass());
264 if (getMipsSubtarget().os16())
265 addPass(createMipsOs16Pass());
266 if (getMipsSubtarget().inMips16HardFloat())
267 addPass(createMips16HardFloatPass());
268 }
269 // Install an instruction selector pass using
270 // the ISelDag to gen Mips code.
addInstSelector()271 bool MipsPassConfig::addInstSelector() {
272 addPass(createMipsModuleISelDagPass());
273 addPass(createMips16ISelDag(getMipsTargetMachine(), getOptLevel()));
274 addPass(createMipsSEISelDag(getMipsTargetMachine(), getOptLevel()));
275 return false;
276 }
277
addPreRegAlloc()278 void MipsPassConfig::addPreRegAlloc() {
279 addPass(createMipsOptimizePICCallPass());
280 }
281
282 TargetTransformInfo
getTargetTransformInfo(const Function & F) const283 MipsTargetMachine::getTargetTransformInfo(const Function &F) const {
284 if (Subtarget->allowMixed16_32()) {
285 LLVM_DEBUG(errs() << "No Target Transform Info Pass Added\n");
286 // FIXME: This is no longer necessary as the TTI returned is per-function.
287 return TargetTransformInfo(F.getParent()->getDataLayout());
288 }
289
290 LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
291 return TargetTransformInfo(MipsTTIImpl(this, F));
292 }
293
294 // Implemented by targets that want to run passes immediately before
295 // machine code is emitted.
addPreEmitPass()296 void MipsPassConfig::addPreEmitPass() {
297 // Expand pseudo instructions that are sensitive to register allocation.
298 addPass(createMipsExpandPseudoPass());
299
300 // The microMIPS size reduction pass performs instruction reselection for
301 // instructions which can be remapped to a 16 bit instruction.
302 addPass(createMicroMipsSizeReducePass());
303
304 // This pass inserts a nop instruction between two back-to-back multiplication
305 // instructions when the "mfix4300" flag is passed.
306 if (EnableMulMulFix)
307 addPass(createMipsMulMulBugPass());
308
309 // The delay slot filler pass can potientially create forbidden slot hazards
310 // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
311 addPass(createMipsDelaySlotFillerPass());
312
313 // This pass expands branches and takes care about the forbidden slot hazards.
314 // Expanding branches may potentially create forbidden slot hazards for
315 // MIPSR6, and fixing such hazard may potentially break a branch by extending
316 // its offset out of range. That's why this pass combine these two tasks, and
317 // runs them alternately until one of them finishes without any changes. Only
318 // then we can be sure that all branches are expanded properly and no hazards
319 // exists.
320 // Any new pass should go before this pass.
321 addPass(createMipsBranchExpansion());
322
323 addPass(createMipsConstantIslandPass());
324 }
325
addIRTranslator()326 bool MipsPassConfig::addIRTranslator() {
327 addPass(new IRTranslator(getOptLevel()));
328 return false;
329 }
330
addPreLegalizeMachineIR()331 void MipsPassConfig::addPreLegalizeMachineIR() {
332 addPass(createMipsPreLegalizeCombiner());
333 }
334
addLegalizeMachineIR()335 bool MipsPassConfig::addLegalizeMachineIR() {
336 addPass(new Legalizer());
337 return false;
338 }
339
addPreRegBankSelect()340 void MipsPassConfig::addPreRegBankSelect() {
341 bool IsOptNone = getOptLevel() == CodeGenOpt::None;
342 addPass(createMipsPostLegalizeCombiner(IsOptNone));
343 }
344
addRegBankSelect()345 bool MipsPassConfig::addRegBankSelect() {
346 addPass(new RegBankSelect());
347 return false;
348 }
349
addGlobalInstructionSelect()350 bool MipsPassConfig::addGlobalInstructionSelect() {
351 addPass(new InstructionSelect(getOptLevel()));
352 return false;
353 }
354