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