LLVM 19.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
29#include "llvm/IR/Mangler.h"
30#include "llvm/IR/Module.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCStreamer.h"
35#include "llvm/MC/MCSymbol.h"
40
41#define DEBUG_TYPE "avr-asm-printer"
42
43namespace llvm {
44
45/// An AVR assembly code printer.
46class AVRAsmPrinter : public AsmPrinter {
47public:
48 AVRAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
49 : AsmPrinter(TM, std::move(Streamer)), MRI(*TM.getMCRegisterInfo()) {}
50
51 StringRef getPassName() const override { return "AVR Assembly Printer"; }
52
53 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
54
55 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
56 const char *ExtraCode, raw_ostream &O) override;
57
58 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
59 const char *ExtraCode, raw_ostream &O) override;
60
61 void emitInstruction(const MachineInstr *MI) override;
62
63 const MCExpr *lowerConstant(const Constant *CV) override;
64
65 void emitXXStructor(const DataLayout &DL, const Constant *CV) override;
66
67 bool doFinalization(Module &M) override;
68
69 void emitStartOfAsmFile(Module &M) override;
70
71private:
72 const MCRegisterInfo &MRI;
73 bool EmittedStructorSymbolAttrs = false;
74};
75
76void AVRAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
77 raw_ostream &O) {
78 const MachineOperand &MO = MI->getOperand(OpNo);
79
80 switch (MO.getType()) {
83 break;
85 O << MO.getImm();
86 break;
88 O << getSymbol(MO.getGlobal());
89 break;
92 break;
94 O << *MO.getMBB()->getSymbol();
95 break;
96 default:
97 llvm_unreachable("Not implemented yet!");
98 }
99}
100
102 const char *ExtraCode, raw_ostream &O) {
103 // Default asm printer can only deal with some extra codes,
104 // so try it first.
105 if (!AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O))
106 return false;
107
108 const MachineOperand &MO = MI->getOperand(OpNum);
109
110 if (ExtraCode && ExtraCode[0]) {
111 // Unknown extra code.
112 if (ExtraCode[1] != 0 || ExtraCode[0] < 'A' || ExtraCode[0] > 'Z')
113 return true;
114
115 // Operand must be a register when using 'A' ~ 'Z' extra code.
116 if (!MO.isReg())
117 return true;
118
119 Register Reg = MO.getReg();
120
121 unsigned ByteNumber = ExtraCode[0] - 'A';
122 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
123 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
124
125 const AVRSubtarget &STI = MF->getSubtarget<AVRSubtarget>();
126 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
127
128 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
129 unsigned BytesPerReg = TRI.getRegSizeInBits(*RC) / 8;
130 assert(BytesPerReg <= 2 && "Only 8 and 16 bit regs are supported.");
131
132 unsigned RegIdx = ByteNumber / BytesPerReg;
133 if (RegIdx >= NumOpRegs)
134 return true;
135 Reg = MI->getOperand(OpNum + RegIdx).getReg();
136
137 if (BytesPerReg == 2) {
138 Reg = TRI.getSubReg(Reg, (ByteNumber % BytesPerReg) ? AVR::sub_hi
139 : AVR::sub_lo);
140 }
141
143 return false;
144 }
145
147 PrintSymbolOperand(MO, O); // Print global symbols.
148 else
149 printOperand(MI, OpNum, O); // Fallback to ordinary cases.
150
151 return false;
152}
153
155 unsigned OpNum, const char *ExtraCode,
156 raw_ostream &O) {
157 if (ExtraCode && ExtraCode[0])
158 return true; // Unknown modifier
159
160 const MachineOperand &MO = MI->getOperand(OpNum);
161 (void)MO;
162 assert(MO.isReg() && "Unexpected inline asm memory operand");
163
164 // TODO: We should be able to look up the alternative name for
165 // the register if it's given.
166 // TableGen doesn't expose a way of getting retrieving names
167 // for registers.
168 if (MI->getOperand(OpNum).getReg() == AVR::R31R30) {
169 O << "Z";
170 } else if (MI->getOperand(OpNum).getReg() == AVR::R29R28) {
171 O << "Y";
172 } else if (MI->getOperand(OpNum).getReg() == AVR::R27R26) {
173 O << "X";
174 } else {
175 assert(false && "Wrong register class for memory operand.");
176 }
177
178 // If NumOpRegs == 2, then we assume it is product of a FrameIndex expansion
179 // and the second operand is an Imm.
180 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
181 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
182
183 if (NumOpRegs == 2) {
184 assert(MI->getOperand(OpNum).getReg() != AVR::R27R26 &&
185 "Base register X can not have offset/displacement.");
186 O << '+' << MI->getOperand(OpNum + 1).getImm();
187 }
188
189 return false;
190}
191
193 AVR_MC::verifyInstructionPredicates(MI->getOpcode(),
194 getSubtargetInfo().getFeatureBits());
195
196 AVRMCInstLower MCInstLowering(OutContext, *this);
197
198 MCInst I;
199 MCInstLowering.lowerInstruction(*MI, I);
201}
202
204 MCContext &Ctx = OutContext;
205
206 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
207 bool IsProgMem = GV->getAddressSpace() == AVR::ProgramMemory;
208 if (IsProgMem) {
209 const MCExpr *Expr = MCSymbolRefExpr::create(getSymbol(GV), Ctx);
210 return AVRMCExpr::create(AVRMCExpr::VK_AVR_PM, Expr, false, Ctx);
211 }
212 }
213
214 return AsmPrinter::lowerConstant(CV);
215}
216
218 if (!EmittedStructorSymbolAttrs) {
219 OutStreamer->emitRawComment(
220 " Emitting these undefined symbol references causes us to link the"
221 " libgcc code that runs our constructors/destructors");
222 OutStreamer->emitRawComment(" This matches GCC's behavior");
223
224 MCSymbol *CtorsSym = OutContext.getOrCreateSymbol("__do_global_ctors");
225 OutStreamer->emitSymbolAttribute(CtorsSym, MCSA_Global);
226
227 MCSymbol *DtorsSym = OutContext.getOrCreateSymbol("__do_global_dtors");
228 OutStreamer->emitSymbolAttribute(DtorsSym, MCSA_Global);
229
230 EmittedStructorSymbolAttrs = true;
231 }
232
234}
235
238 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
239 const AVRSubtarget *SubTM = (const AVRSubtarget *)TM.getSubtargetImpl();
240
241 bool NeedsCopyData = false;
242 bool NeedsClearBSS = false;
243 for (const auto &GO : M.globals()) {
244 if (!GO.hasInitializer() || GO.hasAvailableExternallyLinkage())
245 // These globals aren't defined in the current object file.
246 continue;
247
248 if (GO.hasCommonLinkage()) {
249 // COMMON symbols are put in .bss.
250 NeedsClearBSS = true;
251 continue;
252 }
253
254 auto *Section = cast<MCSectionELF>(TLOF.SectionForGlobal(&GO, TM));
255 if (Section->getName().starts_with(".data"))
256 NeedsCopyData = true;
257 else if (Section->getName().starts_with(".rodata") && SubTM->hasLPM())
258 // AVRs that have a separate program memory (that's most AVRs) store
259 // .rodata sections in RAM.
260 NeedsCopyData = true;
261 else if (Section->getName().starts_with(".bss"))
262 NeedsClearBSS = true;
263 }
264
265 MCSymbol *DoCopyData = OutContext.getOrCreateSymbol("__do_copy_data");
266 MCSymbol *DoClearBss = OutContext.getOrCreateSymbol("__do_clear_bss");
267
268 if (NeedsCopyData) {
269 OutStreamer->emitRawComment(
270 " Declaring this symbol tells the CRT that it should");
271 OutStreamer->emitRawComment(
272 "copy all variables from program memory to RAM on startup");
273 OutStreamer->emitSymbolAttribute(DoCopyData, MCSA_Global);
274 }
275
276 if (NeedsClearBSS) {
277 OutStreamer->emitRawComment(
278 " Declaring this symbol tells the CRT that it should");
279 OutStreamer->emitRawComment("clear the zeroed data section on startup");
280 OutStreamer->emitSymbolAttribute(DoClearBss, MCSA_Global);
281 }
282
284}
285
287 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
288 const AVRSubtarget *SubTM = (const AVRSubtarget *)TM.getSubtargetImpl();
289 if (!SubTM)
290 return;
291
292 // Emit __tmp_reg__.
293 OutStreamer->emitAssignment(
294 MMI->getContext().getOrCreateSymbol(StringRef("__tmp_reg__")),
296 // Emit __zero_reg__.
297 OutStreamer->emitAssignment(
298 MMI->getContext().getOrCreateSymbol(StringRef("__zero_reg__")),
300 // Emit __SREG__.
301 OutStreamer->emitAssignment(
304 // Emit __SP_H__ if available.
305 if (!SubTM->hasSmallStack())
306 OutStreamer->emitAssignment(
309 // Emit __SP_L__.
310 OutStreamer->emitAssignment(
313 // Emit __EIND__ if available.
314 if (SubTM->hasEIJMPCALL())
315 OutStreamer->emitAssignment(
318 // Emit __RAMPZ__ if available.
319 if (SubTM->hasELPM())
320 OutStreamer->emitAssignment(
321 MMI->getContext().getOrCreateSymbol(StringRef("__RAMPZ__")),
323}
324
325} // end of namespace llvm
326
329}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAVRAsmPrinter()
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
unsigned Reg
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
An AVR assembly code printer.
void emitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
const MCExpr * lowerConstant(const Constant *CV) override
Lower the specified LLVM Constant to an MCExpr.
bool doFinalization(Module &M) override
Shut down the asmprinter.
void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O)
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum, const char *ExtraCode, raw_ostream &O) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
void emitXXStructor(const DataLayout &DL, const Constant *CV) override
Targets can override this to change how global constants that are part of a C++ static/global constru...
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum, const char *ExtraCode, raw_ostream &O) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
void emitStartOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the start of their fi...
AVRAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > Streamer)
static const char * getPrettyRegisterName(unsigned RegNo, MCRegisterInfo const &MRI)
static const AVRMCExpr * create(VariantKind Kind, const MCExpr *Expr, bool isNegated, MCContext &Ctx)
Creates an AVR machine code expression.
Definition: AVRMCExpr.cpp:37
@ VK_AVR_PM
Corresponds to pm(), reference to program memory.
Definition: AVRMCExpr.h:30
Lowers MachineInstr objects into MCInst objects.
void lowerInstruction(const MachineInstr &MI, MCInst &OutMI) const
Lowers a MachineInstr into a MCInst.
A specific AVR target MCU.
Definition: AVRSubtarget.h:32
int getIORegRAMPZ() const
Get I/O register addresses.
Definition: AVRSubtarget.h:81
int getIORegSPL() const
Definition: AVRSubtarget.h:83
int getRegTmpIndex() const
Get GPR aliases.
Definition: AVRSubtarget.h:88
int getIORegSREG() const
Definition: AVRSubtarget.h:85
int getIORegEIND() const
Definition: AVRSubtarget.h:82
int getRegZeroIndex() const
Definition: AVRSubtarget.h:89
int getIORegSPH() const
Definition: AVRSubtarget.h:84
const AVRRegisterInfo * getRegisterInfo() const override
Definition: AVRSubtarget.h:52
A generic AVR implementation.
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:86
const TargetLoweringObjectFile & getObjFileLowering() const
Return information about object file lowering.
Definition: AsmPrinter.cpp:383
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:676
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:403
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:89
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:104
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:107
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:96
bool doFinalization(Module &M) override
Shut down the asmprinter.
MCSymbol * GetExternalSymbolSymbol(Twine Sym) const
Return the MCSymbol for the specified ExternalSymbol.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:101
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
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:572
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:398
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:42
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
unsigned getNumOperandRegisters() const
getNumOperandRegisters - Extract the number of registers field from the inline asm operand flag.
Definition: InlineAsm.h:357
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:193
Context object for machine code objects.
Definition: MCContext.h:83
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:213
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:393
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
Definition: MachineInstr.h:69
const MCContext & getContext() const
const LLVMTargetMachine & getTarget() const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() 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_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:65
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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.
Definition: TargetMachine.h:77
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ ProgramMemory
Definition: AVR.h:44
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Target & getTheAVRTarget()
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
@ MCSA_Global
.type _foo, @gnu_unique_object
Definition: MCDirectives.h:30
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...