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