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