LLVM 20.0.0git
MipsTargetMachine.cpp
Go to the documentation of this file.
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"
16#include "Mips.h"
17#include "Mips16ISelDAGToDAG.h"
18#include "MipsMachineFunction.h"
19#include "MipsSEISelDAGToDAG.h"
20#include "MipsSubtarget.h"
24#include "llvm/ADT/StringRef.h"
33#include "llvm/CodeGen/Passes.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/Function.h"
40#include "llvm/Support/Debug.h"
43#include <optional>
44#include <string>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "mips"
49
50static cl::opt<bool>
51 EnableMulMulFix("mfix4300", cl::init(false),
52 cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden);
53
55 // Register the target.
60
70}
71
72static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
73 return std::make_unique<MipsTargetObjectFile>();
74}
75
76static std::string computeDataLayout(const Triple &TT, StringRef CPU,
78 bool isLittle) {
79 std::string Ret;
80 MipsABIInfo ABI = MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions);
81
82 // There are both little and big endian mips.
83 if (isLittle)
84 Ret += "e";
85 else
86 Ret += "E";
87
88 if (ABI.IsO32())
89 Ret += "-m:m";
90 else
91 Ret += "-m:e";
92
93 // Pointers are 32 bit on some ABIs.
94 if (!ABI.IsN64())
95 Ret += "-p:32:32";
96
97 // 8 and 16 bit integers only need to have natural alignment, but try to
98 // align them to 32 bits. 64 bit integers have natural alignment.
99 Ret += "-i8:8:32-i16:16:32-i64:64";
100
101 // 32 bit registers are always available and the stack is at least 64 bit
102 // aligned. On N64 64 bit registers are also available and the stack is
103 // 128 bit aligned.
104 if (ABI.IsN64() || ABI.IsN32())
105 Ret += "-i128:128-n32:64-S128";
106 else
107 Ret += "-n32-S64";
108
109 return Ret;
110}
111
113 std::optional<Reloc::Model> RM) {
114 if (!RM || JIT)
115 return Reloc::Static;
116 return *RM;
117}
118
119// On function prologue, the stack is created by decrementing
120// its pointer. Once decremented, all references are done with positive
121// offset from the stack/frame pointer, using StackGrowsUp enables
122// an easier handling.
123// Using CodeModel::Large enables different CALL behavior.
125 StringRef CPU, StringRef FS,
126 const TargetOptions &Options,
127 std::optional<Reloc::Model> RM,
128 std::optional<CodeModel::Model> CM,
129 CodeGenOptLevel OL, bool JIT,
130 bool isLittle)
132 TT, CPU, FS, Options,
133 getEffectiveRelocModel(JIT, RM),
134 getEffectiveCodeModel(CM, CodeModel::Small), OL),
135 isLittle(isLittle), TLOF(createTLOF(getTargetTriple())),
136 ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
137 Subtarget(nullptr),
138 DefaultSubtarget(TT, CPU, FS, isLittle, *this, std::nullopt),
139 NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
140 isLittle, *this, std::nullopt),
141 Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
142 isLittle, *this, std::nullopt) {
143 Subtarget = &DefaultSubtarget;
144 initAsmInfo();
145
146 // Mips supports the debug entry values.
148}
149
151
152void MipsebTargetMachine::anchor() {}
153
155 StringRef CPU, StringRef FS,
156 const TargetOptions &Options,
157 std::optional<Reloc::Model> RM,
158 std::optional<CodeModel::Model> CM,
159 CodeGenOptLevel OL, bool JIT)
160 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
161
162void MipselTargetMachine::anchor() {}
163
165 StringRef CPU, StringRef FS,
166 const TargetOptions &Options,
167 std::optional<Reloc::Model> RM,
168 std::optional<CodeModel::Model> CM,
169 CodeGenOptLevel OL, bool JIT)
170 : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
171
172const MipsSubtarget *
174 Attribute CPUAttr = F.getFnAttribute("target-cpu");
175 Attribute FSAttr = F.getFnAttribute("target-features");
176
177 std::string CPU =
178 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
179 std::string FS =
180 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
181 bool hasMips16Attr = F.getFnAttribute("mips16").isValid();
182 bool hasNoMips16Attr = F.getFnAttribute("nomips16").isValid();
183
184 bool HasMicroMipsAttr = F.getFnAttribute("micromips").isValid();
185 bool HasNoMicroMipsAttr = F.getFnAttribute("nomicromips").isValid();
186
187 // FIXME: This is related to the code below to reset the target options,
188 // we need to know whether or not the soft float flag is set on the
189 // function, so we can enable it as a subtarget feature.
190 bool softFloat = F.getFnAttribute("use-soft-float").getValueAsBool();
191
192 if (hasMips16Attr)
193 FS += FS.empty() ? "+mips16" : ",+mips16";
194 else if (hasNoMips16Attr)
195 FS += FS.empty() ? "-mips16" : ",-mips16";
196 if (HasMicroMipsAttr)
197 FS += FS.empty() ? "+micromips" : ",+micromips";
198 else if (HasNoMicroMipsAttr)
199 FS += FS.empty() ? "-micromips" : ",-micromips";
200 if (softFloat)
201 FS += FS.empty() ? "+soft-float" : ",+soft-float";
202
203 auto &I = SubtargetMap[CPU + FS];
204 if (!I) {
205 // This needs to be done before we create a new subtarget since any
206 // creation will depend on the TM and the code generation flags on the
207 // function that reside in TargetOptions.
209 I = std::make_unique<MipsSubtarget>(
210 TargetTriple, CPU, FS, isLittle, *this,
211 MaybeAlign(F.getParent()->getOverrideStackAlignment()));
212 }
213 return I.get();
214}
215
217 LLVM_DEBUG(dbgs() << "resetSubtarget\n");
218
219 Subtarget = &MF->getSubtarget<MipsSubtarget>();
220}
221
222namespace {
223
224/// Mips Code Generator Pass Configuration Options.
225class MipsPassConfig : public TargetPassConfig {
226public:
227 MipsPassConfig(MipsTargetMachine &TM, PassManagerBase &PM)
228 : TargetPassConfig(TM, PM) {
229 // The current implementation of long branch pass requires a scratch
230 // register ($at) to be available before branch instructions. Tail merging
231 // can break this requirement, so disable it when long branch pass is
232 // enabled.
233 EnableTailMerge = !getMipsSubtarget().enableLongBranchPass();
234 }
235
236 MipsTargetMachine &getMipsTargetMachine() const {
237 return getTM<MipsTargetMachine>();
238 }
239
240 const MipsSubtarget &getMipsSubtarget() const {
241 return *getMipsTargetMachine().getSubtargetImpl();
242 }
243
244 void addIRPasses() override;
245 bool addInstSelector() override;
246 void addPreEmitPass() override;
247 void addPreRegAlloc() override;
248 bool addIRTranslator() override;
249 void addPreLegalizeMachineIR() override;
250 bool addLegalizeMachineIR() override;
251 void addPreRegBankSelect() override;
252 bool addRegBankSelect() override;
253 bool addGlobalInstructionSelect() override;
254
255 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
256};
257
258} // end anonymous namespace
259
261 return new MipsPassConfig(*this, PM);
262}
263
264std::unique_ptr<CSEConfigBase> MipsPassConfig::getCSEConfig() const {
265 return getStandardCSEConfigForOpt(TM->getOptLevel());
266}
267
268void MipsPassConfig::addIRPasses() {
271 if (getMipsSubtarget().os16())
272 addPass(createMipsOs16Pass());
273 if (getMipsSubtarget().inMips16HardFloat())
274 addPass(createMips16HardFloatPass());
275}
276// Install an instruction selector pass using
277// the ISelDag to gen Mips code.
278bool MipsPassConfig::addInstSelector() {
280 addPass(createMips16ISelDag(getMipsTargetMachine(), getOptLevel()));
281 addPass(createMipsSEISelDag(getMipsTargetMachine(), getOptLevel()));
282 return false;
283}
284
285void MipsPassConfig::addPreRegAlloc() {
287}
288
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.getDataLayout());
295 }
296
297 LLVM_DEBUG(errs() << "Target Transform Info Pass Added\n");
298 return TargetTransformInfo(MipsTTIImpl(this, F));
299}
300
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.
309void MipsPassConfig::addPreEmitPass() {
310 // Expand pseudo instructions that are sensitive to register allocation.
312
313 // The microMIPS size reduction pass performs instruction reselection for
314 // instructions which can be remapped to a 16 bit instruction.
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.
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
337}
338
339bool MipsPassConfig::addIRTranslator() {
340 addPass(new IRTranslator(getOptLevel()));
341 return false;
342}
343
344void MipsPassConfig::addPreLegalizeMachineIR() {
346}
347
348bool MipsPassConfig::addLegalizeMachineIR() {
349 addPass(new Legalizer());
350 return false;
351}
352
353void MipsPassConfig::addPreRegBankSelect() {
354 bool IsOptNone = getOptLevel() == CodeGenOptLevel::None;
355 addPass(createMipsPostLegalizeCombiner(IsOptNone));
356}
357
358bool MipsPassConfig::addRegBankSelect() {
359 addPass(new RegBankSelect());
360 return false;
361}
362
363bool MipsPassConfig::addGlobalInstructionSelect() {
364 addPass(new InstructionSelect(getOptLevel()));
365 return false;
366}
static ARMBaseTargetMachine::ARMABI computeTargetABI(const Triple &TT, StringRef CPU, const TargetOptions &Options)
This file contains the simple types necessary to represent the attributes associated with functions a...
basic Basic Alias true
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Provides analysis for continuously CSEing during GISel passes.
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:128
#define LLVM_DEBUG(...)
Definition: Debug.h:106
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file declares the IRTranslator pass.
static LVOptions Options
Definition: LVOptions.cpp:25
static std::string computeDataLayout()
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static Reloc::Model getEffectiveRelocModel(bool JIT, std::optional< Reloc::Model > RM)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeMipsTarget()
static cl::opt< bool > EnableMulMulFix("mfix4300", cl::init(false), cl::desc("Enable the VR4300 mulmul bug fix."), cl::Hidden)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
Basic Register Allocator
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static std::unique_ptr< TargetLoweringObjectFile > createTLOF()
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:392
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition: Attributes.h:208
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
implements a set of functionality in the TargetMachine class for targets that make use of the indepen...
This pass is responsible for selecting generic machine instructions to target-specific instructions.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
static MipsABIInfo computeTargetABI(const Triple &TT, StringRef CPU, const MCTargetOptions &Options)
Definition: MipsABIInfo.cpp:56
bool allowMixed16_32() const
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
MachineFunctionInfo * createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F, const TargetSubtargetInfo *STI) const override
Create the target's instance of MachineFunctionInfo.
MipsTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT, bool isLittle)
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
~MipsTargetMachine() override
void resetSubtarget(MachineFunction *MF)
Reset the subtarget for the Mips target.
const MipsSubtarget * getSubtargetImpl() const
MipsebTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
MipselTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM, CodeGenOptLevel OL, bool JIT)
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:37
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This pass implements the reg bank selector pass used in the GlobalISel pipeline.
Definition: RegBankSelect.h:91
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:229
void setSupportsDebugEntryValues(bool Enable)
Triple TargetTriple
Triple string, CPU name, and target feature strings the TargetMachine instance is created with.
Definition: TargetMachine.h:96
std::string TargetFS
Definition: TargetMachine.h:98
std::string TargetCPU
Definition: TargetMachine.h:97
std::unique_ptr< const MCSubtargetInfo > STI
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
Target-Independent Code Generator Pass Configuration Options.
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
TargetSubtargetInfo - Generic base class for all target subtargets.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Target & getTheMips64Target()
FunctionPass * createMipsConstantIslandPass()
Returns a pass that converts branches to long branches.
void initializeMipsPreLegalizerCombinerPass(PassRegistry &)
void initializeMipsBranchExpansionPass(PassRegistry &)
void initializeMipsDelaySlotFillerPass(PassRegistry &)
void initializeMipsMulMulBugFixPass(PassRegistry &)
FunctionPass * createMipsOptimizePICCallPass()
Return an OptimizeCall object.
void initializeMipsDAGToDAGISelLegacyPass(PassRegistry &)
std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition: CSEInfo.cpp:79
FunctionPass * createMipsModuleISelDagPass()
CodeModel::Model getEffectiveCodeModel(std::optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createMipsPreLegalizeCombiner()
void initializeMipsPostLegalizerCombinerPass(PassRegistry &)
FunctionPass * createMicroMipsSizeReducePass()
Returns an instance of the MicroMips size reduction pass.
FunctionPass * createMipsSEISelDag(MipsTargetMachine &TM, CodeGenOptLevel OptLevel)
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
FunctionPass * createMipsBranchExpansion()
Target & getTheMips64elTarget()
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
FunctionPass * createMipsMulMulBugPass()
void initializeMicroMipsSizeReducePass(PassRegistry &)
void initializeGlobalISel(PassRegistry &)
Initialize all passes linked into the GlobalISel library.
Definition: GlobalISel.cpp:17
Target & getTheMipselTarget()
FunctionPass * createMips16ISelDag(MipsTargetMachine &TM, CodeGenOptLevel OptLevel)
ModulePass * createMips16HardFloatPass()
FunctionPass * createMipsExpandPseudoPass()
createMipsExpandPseudoPass - returns an instance of the pseudo instruction expansion pass.
FunctionPass * createMipsDelaySlotFillerPass()
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions
FunctionPass * createAtomicExpandLegacyPass()
AtomicExpandPass - At IR level this pass replace atomic instructions with __atomic_* library calls,...
Target & getTheMipsTarget()
ModulePass * createMipsOs16Pass()
Definition: MipsOs16.cpp:160
FunctionPass * createMipsPostLegalizeCombiner(bool IsOptNone)
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
MachineFunctionInfo - This class can be derived from and used by targets to hold private target-speci...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
RegisterTargetMachine - Helper template for registering a target machine implementation,...