LLVM 23.0.0git
LanaiAsmPrinter.cpp
Go to the documentation of this file.
1//===-- LanaiAsmPrinter.cpp - Lanai LLVM assembly writer ------------------===//
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// This file contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to the Lanai assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LanaiAsmPrinter.h"
15#include "LanaiAluCode.h"
16#include "LanaiCondCode.h"
17#include "LanaiMCInstLower.h"
18#include "LanaiTargetMachine.h"
27#include "llvm/IR/Analysis.h"
28#include "llvm/IR/Mangler.h"
29#include "llvm/IR/PassManager.h"
30#include "llvm/MC/MCAsmInfo.h"
31#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
38
39#define DEBUG_TYPE "asm-printer"
40
41using namespace llvm;
42
43namespace {
44class LanaiAsmPrinter : public AsmPrinter {
45public:
46 explicit LanaiAsmPrinter(TargetMachine &TM,
47 std::unique_ptr<MCStreamer> Streamer)
48 : AsmPrinter(TM, std::move(Streamer), ID) {}
49
50 StringRef getPassName() const override { return "Lanai Assembly Printer"; }
51
52 void printOperand(const MachineInstr *MI, int OpNum, raw_ostream &O);
53 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
54 const char *ExtraCode, raw_ostream &O) override;
55 void emitInstruction(const MachineInstr *MI) override;
56 bool isBlockOnlyReachableByFallthrough(
57 const MachineBasicBlock *MBB) const override;
58
59private:
60 void customEmitInstruction(const MachineInstr *MI);
61 void emitCallInstruction(const MachineInstr *MI);
62
63public:
64 static char ID;
65};
66} // end of anonymous namespace
67
68void LanaiAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
69 raw_ostream &O) {
70 const MachineOperand &MO = MI->getOperand(OpNum);
71
72 switch (MO.getType()) {
75 break;
76
78 O << MO.getImm();
79 break;
80
82 O << *MO.getMBB()->getSymbol();
83 break;
84
86 O << *getSymbol(MO.getGlobal());
87 break;
88
90 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
91 O << BA->getName();
92 break;
93 }
94
96 O << *GetExternalSymbolSymbol(MO.getSymbolName());
97 break;
98
100 O << MAI.getInternalSymbolPrefix() << "JTI" << getFunctionNumber() << '_'
101 << MO.getIndex();
102 break;
103
105 O << MAI.getInternalSymbolPrefix() << "CPI" << getFunctionNumber() << '_'
106 << MO.getIndex();
107 return;
108
109 default:
110 llvm_unreachable("<unknown operand type>");
111 }
112}
113
114// PrintAsmOperand - Print out an operand for an inline asm expression.
115bool LanaiAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
116 const char *ExtraCode, raw_ostream &O) {
117 // Does this asm operand have a single letter operand modifier?
118 if (ExtraCode && ExtraCode[0]) {
119 if (ExtraCode[1])
120 return true; // Unknown modifier.
121
122 switch (ExtraCode[0]) {
123 // The highest-numbered register of a pair.
124 case 'H': {
125 if (OpNo == 0)
126 return true;
127 const MachineOperand &FlagsOP = MI->getOperand(OpNo - 1);
128 if (!FlagsOP.isImm())
129 return true;
130 const InlineAsm::Flag Flags(FlagsOP.getImm());
131 const unsigned NumVals = Flags.getNumOperandRegisters();
132 if (NumVals != 2)
133 return true;
134 unsigned RegOp = OpNo + 1;
135 if (RegOp >= MI->getNumOperands())
136 return true;
137 const MachineOperand &MO = MI->getOperand(RegOp);
138 if (!MO.isReg())
139 return true;
140 Register Reg = MO.getReg();
142 return false;
143 }
144 default:
145 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
146 }
147 }
148 printOperand(MI, OpNo, O);
149 return false;
150}
151
152//===----------------------------------------------------------------------===//
153void LanaiAsmPrinter::emitCallInstruction(const MachineInstr *MI) {
154 assert((MI->getOpcode() == Lanai::CALL || MI->getOpcode() == Lanai::CALLR) &&
155 "Unsupported call function");
156
157 LanaiMCInstLower MCInstLowering(OutContext, *this);
158 MCSubtargetInfo STI = getSubtargetInfo();
159 // Insert save rca instruction immediately before the call.
160 // TODO: We should generate a pc-relative mov instruction here instead
161 // of pc + 16 (should be mov .+16 %rca).
162 OutStreamer->emitInstruction(MCInstBuilder(Lanai::ADD_I_LO)
163 .addReg(Lanai::RCA)
164 .addReg(Lanai::PC)
165 .addImm(16),
166 STI);
167
168 // Push rca onto the stack.
169 // st %rca, [--%sp]
170 OutStreamer->emitInstruction(MCInstBuilder(Lanai::SW_RI)
171 .addReg(Lanai::RCA)
172 .addReg(Lanai::SP)
173 .addImm(-4)
174 .addImm(LPAC::makePreOp(LPAC::ADD)),
175 STI);
176
177 // Lower the call instruction.
178 if (MI->getOpcode() == Lanai::CALL) {
179 MCInst TmpInst;
180 MCInstLowering.Lower(MI, TmpInst);
181 TmpInst.setOpcode(Lanai::BT);
182 OutStreamer->emitInstruction(TmpInst, STI);
183 } else {
184 OutStreamer->emitInstruction(MCInstBuilder(Lanai::ADD_R)
185 .addReg(Lanai::PC)
186 .addReg(MI->getOperand(0).getReg())
187 .addReg(Lanai::R0)
188 .addImm(LPCC::ICC_T),
189 STI);
190 }
191}
192
193void LanaiAsmPrinter::customEmitInstruction(const MachineInstr *MI) {
194 LanaiMCInstLower MCInstLowering(OutContext, *this);
195 MCSubtargetInfo STI = getSubtargetInfo();
196 MCInst TmpInst;
197 MCInstLowering.Lower(MI, TmpInst);
198 OutStreamer->emitInstruction(TmpInst, STI);
199}
200
201void LanaiAsmPrinter::emitInstruction(const MachineInstr *MI) {
202 Lanai_MC::verifyInstructionPredicates(MI->getOpcode(),
203 getSubtargetInfo().getFeatureBits());
204
206 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
207
208 do {
209 if (I->isCall()) {
210 emitCallInstruction(&*I);
211 continue;
212 }
213
214 customEmitInstruction(&*I);
215 } while ((++I != E) && I->isInsideBundle());
216}
217
218// isBlockOnlyReachableByFallthough - Return true if the basic block has
219// exactly one predecessor and the control transfer mechanism between
220// the predecessor and this block is a fall-through.
221// FIXME: could the overridden cases be handled in analyzeBranch?
222bool LanaiAsmPrinter::isBlockOnlyReachableByFallthrough(
223 const MachineBasicBlock *MBB) const {
224 // The predecessor has to be immediately before this block.
225 const MachineBasicBlock *Pred = *MBB->pred_begin();
226
227 // If the predecessor is a switch statement, assume a jump table
228 // implementation, so it is not a fall through.
229 if (const BasicBlock *B = Pred->getBasicBlock())
230 if (isa<SwitchInst>(B->getTerminator()))
231 return false;
232
233 // Check default implementation
235 return false;
236
237 // Otherwise, check the last instruction.
238 // Check if the last terminator is an unconditional branch.
240 while (I != Pred->begin() && !(--I)->isTerminator()) {
241 }
242
243 return !I->isBarrier();
244}
245
246char LanaiAsmPrinter::ID = 0;
247
248INITIALIZE_PASS(LanaiAsmPrinter, "lanai-asm-printer", "Lanai Assembly Printer",
249 false, false)
250
251// Force static initialization.
253LLVMInitializeLanaiAsmPrinter() {
255}
256
259 LanaiAsmPrinter &AsmPrinter = static_cast<LanaiAsmPrinter &>(
260 MAM.getResult<AsmPrinterAnalysis>(M).getPrinter());
263 return PreservedAnalyses::all();
264}
265
269 LanaiAsmPrinter &AsmPrinter = static_cast<LanaiAsmPrinter &>(
271 .getCachedResult<AsmPrinterAnalysis>(*MF.getFunction().getParent())
272 ->getPrinter());
275 return PreservedAnalyses::all();
276}
277
280 LanaiAsmPrinter &AsmPrinter = static_cast<LanaiAsmPrinter &>(
281 MAM.getResult<AsmPrinterAnalysis>(M).getPrinter());
284 return PreservedAnalyses::all();
285}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
IRTranslator LLVM IR MI
This header defines various interfaces for pass management in LLVM.
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const
Return true if the basic block has exactly one predecessor and the control transfer mechanism between...
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
bool doFinalization(Module &M) override
Shut down the asmprinter.
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition AsmPrinter.h:453
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MFAM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MFAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static const char * getRegisterName(MCRegister Reg)
void setOpcode(unsigned Op)
Definition MCInst.h:201
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
Instructions::const_iterator const_instr_iterator
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
const BlockAddress * getBlockAddress() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
static unsigned makePreOp(unsigned AluOp)
This is an optimization pass for GlobalISel generic memory operations.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
Target & getTheLanaiTarget()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...