LLVM 23.0.0git
AVRAsmPrinter.cpp
Go to the documentation of this file.
1//===-- AVRAsmPrinter.cpp - AVR 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 GAS-format AVR assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AVR.h"
15#include "AVRMCInstLower.h"
16#include "AVRSubtarget.h"
17#include "AVRTargetMachine.h"
21
28#include "llvm/IR/Mangler.h"
29#include "llvm/IR/Module.h"
30#include "llvm/MC/MCContext.h"
31#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
40
41#define DEBUG_TYPE "avr-asm-printer"
42
43using namespace llvm;
44
45namespace {
46
47/// An AVR assembly code printer.
48class AVRAsmPrinter : public AsmPrinter {
49public:
50 AVRAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
51 : AsmPrinter(TM, std::move(Streamer), ID), MRI(TM.getMCRegisterInfo()) {}
52
53 StringRef getPassName() const override { return "AVR Assembly Printer"; }
54
55 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
56
57 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
58 const char *ExtraCode, raw_ostream &O) override;
59
60 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
61 const char *ExtraCode, raw_ostream &O) override;
62
63 void emitInstruction(const MachineInstr *MI) override;
64
65 const MCExpr *lowerConstant(const Constant *CV, const Constant *BaseCV,
66 uint64_t Offset) override;
67
68 void emitXXStructor(const DataLayout &DL, const Constant *CV) override;
69
70 bool doFinalization(Module &M) override;
71
72 void emitStartOfAsmFile(Module &M) override;
73
74 static char ID;
75
76private:
77 const MCRegisterInfo &MRI;
78 bool EmittedStructorSymbolAttrs = false;
79};
80
81} // namespace
82
83void AVRAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
84 raw_ostream &O) {
85 const MachineOperand &MO = MI->getOperand(OpNo);
86
87 switch (MO.getType()) {
90 break;
92 O << MO.getImm();
93 break;
95 O << getSymbol(MO.getGlobal());
96 break;
98 O << *GetExternalSymbolSymbol(MO.getSymbolName());
99 break;
101 O << *MO.getMBB()->getSymbol();
102 break;
103 default:
104 llvm_unreachable("Not implemented yet!");
105 }
106}
107
108bool AVRAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
109 const char *ExtraCode, raw_ostream &O) {
110 // Default asm printer can only deal with some extra codes,
111 // so try it first.
112 if (!AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O))
113 return false;
114
115 const MachineOperand &MO = MI->getOperand(OpNum);
116
117 // Operand must be a register when using 'A' ~ 'Z' extra code.
118 if (ExtraCode && ExtraCode[0] && MO.isReg()) {
119 // Unknown extra code.
120 if (ExtraCode[1] != 0 || ExtraCode[0] < 'A' || ExtraCode[0] > 'Z')
121 return true;
122
123 Register Reg = MO.getReg();
124
125 unsigned ByteNumber = ExtraCode[0] - 'A';
126 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
127 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
128
129 const AVRSubtarget &STI = MF->getSubtarget<AVRSubtarget>();
130 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
131
132 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
133 unsigned BytesPerReg = TRI.getRegSizeInBits(*RC) / 8;
134 assert(BytesPerReg <= 2 && "Only 8 and 16 bit regs are supported.");
135
136 unsigned RegIdx = ByteNumber / BytesPerReg;
137 if (RegIdx >= NumOpRegs)
138 return true;
139 Reg = MI->getOperand(OpNum + RegIdx).getReg();
140
141 if (BytesPerReg == 2) {
142 Reg = TRI.getSubReg(Reg, (ByteNumber % BytesPerReg) ? AVR::sub_hi
143 : AVR::sub_lo);
144 }
145
147 return false;
148 }
149
151 PrintSymbolOperand(MO, O); // Print global symbols.
152 else
153 printOperand(MI, OpNum, O); // Fallback to ordinary cases.
154
155 return false;
156}
157
158bool AVRAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
159 unsigned OpNum, const char *ExtraCode,
160 raw_ostream &O) {
161 if (ExtraCode && ExtraCode[0])
162 return true; // Unknown modifier
163
164 const MachineOperand &MO = MI->getOperand(OpNum);
165
166 // Print direct memory operands.
167 if (MO.isGlobal() || MO.isSymbol() || MO.isMCSymbol()) {
168 PrintSymbolOperand(MO, O);
169 return false;
170 }
171
172 assert(MO.isReg() && "Unexpected inline asm memory operand");
173
174 // TODO: We should be able to look up the alternative name for
175 // the register if it's given.
176 // TableGen doesn't expose a way of getting retrieving names
177 // for registers.
178 if (MI->getOperand(OpNum).getReg() == AVR::R31R30) {
179 O << "Z";
180 } else if (MI->getOperand(OpNum).getReg() == AVR::R29R28) {
181 O << "Y";
182 } else if (MI->getOperand(OpNum).getReg() == AVR::R27R26) {
183 O << "X";
184 } else {
185 assert(false && "Wrong register class for memory operand.");
186 }
187
188 // If NumOpRegs == 2, then we assume it is product of a FrameIndex expansion
189 // and the second operand is an Imm.
190 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
191 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
192
193 if (NumOpRegs == 2) {
194 assert(MI->getOperand(OpNum).getReg() != AVR::R27R26 &&
195 "Base register X can not have offset/displacement.");
196 O << '+' << MI->getOperand(OpNum + 1).getImm();
197 }
198
199 return false;
200}
201
202void AVRAsmPrinter::emitInstruction(const MachineInstr *MI) {
203 AVR_MC::verifyInstructionPredicates(MI->getOpcode(),
204 getSubtargetInfo().getFeatureBits());
205
206 AVRMCInstLower MCInstLowering(OutContext, *this);
207
208 MCInst I;
209 MCInstLowering.lowerInstruction(*MI, I);
210 EmitToStreamer(*OutStreamer, I);
211}
212
213const MCExpr *AVRAsmPrinter::lowerConstant(const Constant *CV,
214 const Constant *BaseCV,
215 uint64_t Offset) {
216 MCContext &Ctx = OutContext;
217
218 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
219 bool IsProgMem = GV->getAddressSpace() == AVR::ProgramMemory;
220 if (IsProgMem) {
221 const MCExpr *Expr = MCSymbolRefExpr::create(getSymbol(GV), Ctx);
222 return AVRMCExpr::create(AVR::S_PM, Expr, false, Ctx);
223 }
224 }
225
226 return AsmPrinter::lowerConstant(CV, BaseCV, Offset);
227}
228
229void AVRAsmPrinter::emitXXStructor(const DataLayout &DL, const Constant *CV) {
230 if (!EmittedStructorSymbolAttrs) {
231 OutStreamer->emitRawComment(
232 " Emitting these undefined symbol references causes us to link the"
233 " libgcc code that runs our constructors/destructors");
234 OutStreamer->emitRawComment(" This matches GCC's behavior");
235
236 MCSymbol *CtorsSym = OutContext.getOrCreateSymbol("__do_global_ctors");
237 OutStreamer->emitSymbolAttribute(CtorsSym, MCSA_Global);
238
239 MCSymbol *DtorsSym = OutContext.getOrCreateSymbol("__do_global_dtors");
240 OutStreamer->emitSymbolAttribute(DtorsSym, MCSA_Global);
241
242 EmittedStructorSymbolAttrs = true;
243 }
244
246}
247
248bool AVRAsmPrinter::doFinalization(Module &M) {
249 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
250 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
251 const AVRSubtarget *SubTM = TM.getSubtargetImpl();
252
253 bool NeedsCopyData = false;
254 bool NeedsClearBSS = false;
255 for (const auto &GO : M.globals()) {
256 if (!GO.hasInitializer() || GO.hasAvailableExternallyLinkage())
257 // These globals aren't defined in the current object file.
258 continue;
259
260 if (GO.hasCommonLinkage()) {
261 // COMMON symbols are put in .bss.
262 NeedsClearBSS = true;
263 continue;
264 }
265
266 auto *Section = static_cast<MCSectionELF *>(TLOF.SectionForGlobal(&GO, TM));
267 if (Section->getName().starts_with(".data"))
268 NeedsCopyData = true;
269 else if (Section->getName().starts_with(".rodata") && SubTM->hasLPM())
270 // AVRs that have a separate program memory (that's most AVRs) store
271 // .rodata sections in RAM.
272 NeedsCopyData = true;
273 else if (Section->getName().starts_with(".bss"))
274 NeedsClearBSS = true;
275 }
276
277 MCSymbol *DoCopyData = OutContext.getOrCreateSymbol("__do_copy_data");
278 MCSymbol *DoClearBss = OutContext.getOrCreateSymbol("__do_clear_bss");
279
280 if (NeedsCopyData) {
281 OutStreamer->emitRawComment(
282 " Declaring this symbol tells the CRT that it should");
283 OutStreamer->emitRawComment(
284 "copy all variables from program memory to RAM on startup");
285 OutStreamer->emitSymbolAttribute(DoCopyData, MCSA_Global);
286 }
287
288 if (NeedsClearBSS) {
289 OutStreamer->emitRawComment(
290 " Declaring this symbol tells the CRT that it should");
291 OutStreamer->emitRawComment("clear the zeroed data section on startup");
292 OutStreamer->emitSymbolAttribute(DoClearBss, MCSA_Global);
293 }
294
296}
297
298void AVRAsmPrinter::emitStartOfAsmFile(Module &M) {
299 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
300 const AVRSubtarget *SubTM = TM.getSubtargetImpl();
301 if (!SubTM)
302 return;
303
304 // Emit __tmp_reg__.
305 OutStreamer->emitAssignment(
306 MMI->getContext().getOrCreateSymbol(StringRef("__tmp_reg__")),
307 MCConstantExpr::create(SubTM->getRegTmpIndex(), MMI->getContext()));
308 // Emit __zero_reg__.
309 OutStreamer->emitAssignment(
310 MMI->getContext().getOrCreateSymbol(StringRef("__zero_reg__")),
311 MCConstantExpr::create(SubTM->getRegZeroIndex(), MMI->getContext()));
312 // Emit __SREG__.
313 OutStreamer->emitAssignment(
314 MMI->getContext().getOrCreateSymbol(StringRef("__SREG__")),
315 MCConstantExpr::create(SubTM->getIORegSREG(), MMI->getContext()));
316 // Emit __SP_H__ if available.
317 if (!SubTM->hasSmallStack())
318 OutStreamer->emitAssignment(
319 MMI->getContext().getOrCreateSymbol(StringRef("__SP_H__")),
320 MCConstantExpr::create(SubTM->getIORegSPH(), MMI->getContext()));
321 // Emit __SP_L__.
322 OutStreamer->emitAssignment(
323 MMI->getContext().getOrCreateSymbol(StringRef("__SP_L__")),
324 MCConstantExpr::create(SubTM->getIORegSPL(), MMI->getContext()));
325 // Emit __EIND__ if available.
326 if (SubTM->hasEIJMPCALL())
327 OutStreamer->emitAssignment(
328 MMI->getContext().getOrCreateSymbol(StringRef("__EIND__")),
329 MCConstantExpr::create(SubTM->getIORegEIND(), MMI->getContext()));
330 // Emit __RAMPZ__ if available.
331 if (SubTM->hasELPM())
332 OutStreamer->emitAssignment(
333 MMI->getContext().getOrCreateSymbol(StringRef("__RAMPZ__")),
334 MCConstantExpr::create(SubTM->getIORegRAMPZ(), MMI->getContext()));
335}
336
337char AVRAsmPrinter::ID = 0;
338
339INITIALIZE_PASS(AVRAsmPrinter, "avr-asm-printer", "AVR Assembly Printer", false,
340 false)
341
343LLVMInitializeAVRAsmPrinter() {
345}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, const RISCVSubtarget &Subtarget)
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
static const char * getPrettyRegisterName(MCRegister Reg, MCRegisterInfo const &MRI)
static const AVRMCExpr * create(Specifier S, const MCExpr *Expr, bool isNegated, MCContext &Ctx)
Specifies the type of an expression.
Definition AVRMCExpr.cpp:17
int getIORegRAMPZ() const
Get I/O register addresses.
int getIORegSPL() const
int getRegTmpIndex() const
Get GPR aliases.
int getIORegSREG() const
int getIORegEIND() const
int getRegZeroIndex() const
int getIORegSPH() const
const AVRRegisterInfo * getRegisterInfo() const override
const AVRSubtarget * getSubtargetImpl() const
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
virtual const MCExpr * lowerConstant(const Constant *CV, const Constant *BaseCV=nullptr, uint64_t Offset=0)
Lower the specified LLVM Constant to an MCExpr.
bool doFinalization(Module &M) override
Shut down the asmprinter.
virtual void emitXXStructor(const DataLayout &DL, const Constant *CV)
Targets can override this to change how global constants that are part of a C++ static/global constru...
Definition AsmPrinter.h:655
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.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
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 isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
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_GlobalAddress
Address of a global value.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Represent a constant reference to a string, i.e.
Definition StringRef.h:55
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
Primary interface to the complete machine description for the target machine.
const Target & getTarget() const
const MCRegisterInfo & getMCRegisterInfo() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ ProgramMemory
Definition AVR.h:45
@ S_PM
Corresponds to pm(), reference to program memory.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:557
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Target & getTheAVRTarget()
@ MCSA_Global
.type _foo, @gnu_unique_object
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...