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