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