xref: /llvm-project/llvm/lib/Target/Mips/MipsTargetMachine.cpp (revision de7be5e46f9eb3433fab194897859291e3dbc98f)
1 //===-- MipsTargetMachine.cpp - Define TargetMachine for Mips -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implements the info about Mips target spec.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MipsTargetMachine.h"
15 #include "MCTargetDesc/MipsABIInfo.h"
16 #include "MCTargetDesc/MipsMCTargetDesc.h"
17 #include "Mips.h"
18 #include "Mips16ISelDAGToDAG.h"
19 #include "MipsSEISelDAGToDAG.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetObjectFile.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/GlobalISel/IRTranslator.h"
27 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
28 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
29 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
30 #include "llvm/CodeGen/BasicTTIImpl.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/IR/Attributes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CodeGen.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include <string>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "mips"
46 
47 extern "C" void LLVMInitializeMipsTarget() {
48   // Register the target.
49   RegisterTargetMachine<MipsebTargetMachine> X(getTheMipsTarget());
50   RegisterTargetMachine<MipselTargetMachine> Y(getTheMipselTarget());
51   RegisterTargetMachine<MipsebTargetMachine> A(getTheMips64Target());
52   RegisterTargetMachine<MipselTargetMachine> B(getTheMips64elTarget());
53 
54   PassRegistry *PR = PassRegistry::getPassRegistry();
55   initializeGlobalISel(*PR);
56   initializeMipsDelaySlotFillerPass(*PR);
57   initializeMipsBranchExpansionPass(*PR);
58 }
59 
60 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
61                                      const TargetOptions &Options,
62                                      bool isLittle) {
63   std::string Ret;
64   MipsABIInfo ABI = MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions);
65 
66   // There are both little and big endian mips.
67   if (isLittle)
68     Ret += "e";
69   else
70     Ret += "E";
71 
72   if (ABI.IsO32())
73     Ret += "-m:m";
74   else
75     Ret += "-m:e";
76 
77   // Pointers are 32 bit on some ABIs.
78   if (!ABI.IsN64())
79     Ret += "-p:32:32";
80 
81   // 8 and 16 bit integers only need to have natural alignment, but try to
82   // align them to 32 bits. 64 bit integers have natural alignment.
83   Ret += "-i8:8:32-i16:16:32-i64:64";
84 
85   // 32 bit registers are always available and the stack is at least 64 bit
86   // aligned. On N64 64 bit registers are also available and the stack is
87   // 128 bit aligned.
88   if (ABI.IsN64() || ABI.IsN32())
89     Ret += "-n32:64-S128";
90   else
91     Ret += "-n32-S64";
92 
93   return Ret;
94 }
95 
96 static Reloc::Model getEffectiveRelocModel(bool JIT,
97                                            Optional<Reloc::Model> RM) {
98   if (!RM.hasValue() || JIT)
99     return Reloc::Static;
100   return *RM;
101 }
102 
103 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM) {
104   if (CM)
105     return *CM;
106   return CodeModel::Small;
107 }
108 
109 // On function prologue, the stack is created by decrementing
110 // its pointer. Once decremented, all references are done with positive
111 // offset from the stack/frame pointer, using StackGrowsUp enables
112 // an easier handling.
113 // Using CodeModel::Large enables different CALL behavior.
114 MipsTargetMachine::MipsTargetMachine(const Target &T, const Triple &TT,
115                                      StringRef CPU, StringRef FS,
116                                      const TargetOptions &Options,
117                                      Optional<Reloc::Model> RM,
118                                      Optional<CodeModel::Model> CM,
119                                      CodeGenOpt::Level OL, bool JIT,
120                                      bool isLittle)
121     : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
122                         CPU, FS, Options, getEffectiveRelocModel(JIT, RM),
123                         getEffectiveCodeModel(CM), OL),
124       isLittle(isLittle), TLOF(llvm::make_unique<MipsTargetObjectFile>()),
125       ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
126       Subtarget(nullptr), DefaultSubtarget(TT, CPU, FS, isLittle, *this,
127                                            Options.StackAlignmentOverride),
128       NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
129                         isLittle, *this, Options.StackAlignmentOverride),
130       Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
131                       isLittle, *this, Options.StackAlignmentOverride) {
132   Subtarget = &DefaultSubtarget;
133   initAsmInfo();
134 }
135 
136 MipsTargetMachine::~MipsTargetMachine() = default;
137 
138 void MipsebTargetMachine::anchor() {}
139 
140 MipsebTargetMachine::MipsebTargetMachine(const Target &T, const Triple &TT,
141                                          StringRef CPU, StringRef FS,
142                                          const TargetOptions &Options,
143                                          Optional<Reloc::Model> RM,
144                                          Optional<CodeModel::Model> CM,
145                                          CodeGenOpt::Level OL, bool JIT)
146     : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
147 
148 void MipselTargetMachine::anchor() {}
149 
150 MipselTargetMachine::MipselTargetMachine(const Target &T, const Triple &TT,
151                                          StringRef CPU, StringRef FS,
152                                          const TargetOptions &Options,
153                                          Optional<Reloc::Model> RM,
154                                          Optional<CodeModel::Model> CM,
155                                          CodeGenOpt::Level OL, bool JIT)
156     : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
157 
158 const MipsSubtarget *
159 MipsTargetMachine::getSubtargetImpl(const Function &F) const {
160   Attribute CPUAttr = F.getFnAttribute("target-cpu");
161   Attribute FSAttr = F.getFnAttribute("target-features");
162 
163   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
164                         ? CPUAttr.getValueAsString().str()
165                         : TargetCPU;
166   std::string FS = !FSAttr.hasAttribute(Attribute::None)
167                        ? FSAttr.getValueAsString().str()
168                        : TargetFS;
169   bool hasMips16Attr =
170       !F.getFnAttribute("mips16").hasAttribute(Attribute::None);
171   bool hasNoMips16Attr =
172       !F.getFnAttribute("nomips16").hasAttribute(Attribute::None);
173 
174   bool HasMicroMipsAttr =
175       !F.getFnAttribute("micromips").hasAttribute(Attribute::None);
176   bool HasNoMicroMipsAttr =
177       !F.getFnAttribute("nomicromips").hasAttribute(Attribute::None);
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 =
183       F.hasFnAttribute("use-soft-float") &&
184       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
185 
186   if (hasMips16Attr)
187     FS += FS.empty() ? "+mips16" : ",+mips16";
188   else if (hasNoMips16Attr)
189     FS += FS.empty() ? "-mips16" : ",-mips16";
190   if (HasMicroMipsAttr)
191     FS += FS.empty() ? "+micromips" : ",+micromips";
192   else if (HasNoMicroMipsAttr)
193     FS += FS.empty() ? "-micromips" : ",-micromips";
194   if (softFloat)
195     FS += FS.empty() ? "+soft-float" : ",+soft-float";
196 
197   auto &I = SubtargetMap[CPU + FS];
198   if (!I) {
199     // This needs to be done before we create a new subtarget since any
200     // creation will depend on the TM and the code generation flags on the
201     // function that reside in TargetOptions.
202     resetTargetOptions(F);
203     I = llvm::make_unique<MipsSubtarget>(TargetTriple, CPU, FS, isLittle, *this,
204                                          Options.StackAlignmentOverride);
205   }
206   return I.get();
207 }
208 
209 void MipsTargetMachine::resetSubtarget(MachineFunction *MF) {
210   LLVM_DEBUG(dbgs() << "resetSubtarget\n");
211 
212   Subtarget = const_cast<MipsSubtarget *>(getSubtargetImpl(MF->getFunction()));
213   MF->setSubtarget(Subtarget);
214 }
215 
216 namespace {
217 
218 /// Mips Code Generator Pass Configuration Options.
219 class MipsPassConfig : public TargetPassConfig {
220 public:
221   MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
222       : TargetPassConfig(TM, PM) {
223     // The current implementation of long branch pass requires a scratch
224     // register ($at) to be available before branch instructions. Tail merging
225     // can break this requirement, so disable it when long branch pass is
226     // enabled.
227     EnableTailMerge = !getMipsSubtarget().enableLongBranchPass();
228   }
229 
230   MipsTargetMachine &getMipsTargetMachine() const {
231     return getTM<MipsTargetMachine>();
232   }
233 
234   const MipsSubtarget &getMipsSubtarget() const {
235     return *getMipsTargetMachine().getSubtargetImpl();
236   }
237 
238   void addIRPasses() override;
239   bool addInstSelector() override;
240   void addPreEmitPass() override;
241   void addPreRegAlloc() override;
242   bool addIRTranslator() override;
243   bool addLegalizeMachineIR() override;
244   bool addRegBankSelect() override;
245   bool addGlobalInstructionSelect() override;
246 };
247 
248 } // end anonymous namespace
249 
250 TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM) {
251   return new MipsPassConfig(*this, PM);
252 }
253 
254 void MipsPassConfig::addIRPasses() {
255   TargetPassConfig::addIRPasses();
256   addPass(createAtomicExpandPass());
257   if (getMipsSubtarget().os16())
258     addPass(createMipsOs16Pass());
259   if (getMipsSubtarget().inMips16HardFloat())
260     addPass(createMips16HardFloatPass());
261 }
262 // Install an instruction selector pass using
263 // the ISelDag to gen Mips code.
264 bool MipsPassConfig::addInstSelector() {
265   addPass(createMipsModuleISelDagPass());
266   addPass(createMips16ISelDag(getMipsTargetMachine(), getOptLevel()));
267   addPass(createMipsSEISelDag(getMipsTargetMachine(), getOptLevel()));
268   return false;
269 }
270 
271 void MipsPassConfig::addPreRegAlloc() {
272   addPass(createMipsOptimizePICCallPass());
273 }
274 
275 TargetTransformInfo
276 MipsTargetMachine::getTargetTransformInfo(const Function &F) {
277   if (Subtarget->allowMixed16_32()) {
278     LLVM_DEBUG(errs() << "No Target Transform Info Pass Added\n");
279     // FIXME: This is no longer necessary as the TTI returned is per-function.
280     return TargetTransformInfo(F.getParent()->getDataLayout());
281   }
282 
283   LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
284   return TargetTransformInfo(BasicTTIImpl(this, F));
285 }
286 
287 // Implemented by targets that want to run passes immediately before
288 // machine code is emitted. return true if -print-machineinstrs should
289 // print out the code after the passes.
290 void MipsPassConfig::addPreEmitPass() {
291   addPass(createMicroMipsSizeReductionPass());
292 
293   // The delay slot filler pass can potientially create forbidden slot hazards
294   // for MIPSR6 and therefore it should go before MipsBranchExpansion pass.
295   addPass(createMipsDelaySlotFillerPass());
296 
297   // This pass expands branches and takes care about the forbidden slot hazards.
298   // Expanding branches may potentially create forbidden slot hazards for
299   // MIPSR6, and fixing such hazard may potentially break a branch by extending
300   // its offset out of range. That's why this pass combine these two tasks, and
301   // runs them alternately until one of them finishes without any changes. Only
302   // then we can be sure that all branches are expanded properly and no hazards
303   // exists.
304   // Any new pass should go before this pass.
305   addPass(createMipsBranchExpansion());
306 
307   addPass(createMipsConstantIslandPass());
308 }
309 
310 bool MipsPassConfig::addIRTranslator() {
311   addPass(new IRTranslator());
312   return false;
313 }
314 
315 bool MipsPassConfig::addLegalizeMachineIR() {
316   addPass(new Legalizer());
317   return false;
318 }
319 
320 bool MipsPassConfig::addRegBankSelect() {
321   addPass(new RegBankSelect());
322   return false;
323 }
324 
325 bool MipsPassConfig::addGlobalInstructionSelect() {
326   addPass(new InstructionSelect());
327   return false;
328 }
329