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