LLVM 24.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 "AVRAsmPrinter.h"
15#include "AVR.h"
16#include "AVRMCInstLower.h"
17#include "AVRSubtarget.h"
18#include "AVRTargetMachine.h"
22
31#include "llvm/IR/Analysis.h"
32#include "llvm/IR/Mangler.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/PassManager.h"
35#include "llvm/MC/MCContext.h"
36#include "llvm/MC/MCInst.h"
38#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
45
46#define DEBUG_TYPE "avr-asm-printer"
47
48using namespace llvm;
49
50namespace {
51
52/// An AVR assembly code printer.
53class AVRAsmPrinter : public AsmPrinter {
54public:
55 AVRAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
56 : AsmPrinter(TM, std::move(Streamer), ID), MRI(TM.getMCRegisterInfo()) {}
57
58 StringRef getPassName() const override { return "AVR Assembly Printer"; }
59
60 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
61
62 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
63 const char *ExtraCode, raw_ostream &O) override;
64
65 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
66 const char *ExtraCode, raw_ostream &O) override;
67
68 void emitInstruction(const MachineInstr *MI) override;
69
70 const MCExpr *lowerConstant(const Constant *CV, const Constant *BaseCV,
71 uint64_t Offset) override;
72
73 void emitXXStructor(const DataLayout &DL, const Constant *CV) override;
74
75 bool doFinalization(Module &M) override;
76
77 void emitStartOfAsmFile(Module &M) override;
78
79 static char ID;
80
81private:
82 const MCRegisterInfo &MRI;
83 bool EmittedStructorSymbolAttrs = false;
84};
85
86} // namespace
87
88void AVRAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
89 raw_ostream &O) {
90 const MachineOperand &MO = MI->getOperand(OpNo);
91
92 switch (MO.getType()) {
95 break;
97 O << MO.getImm();
98 break;
100 O << getSymbol(MO.getGlobal());
101 break;
103 O << *GetExternalSymbolSymbol(MO.getSymbolName());
104 break;
106 O << *MO.getMBB()->getSymbol();
107 break;
108 default:
109 llvm_unreachable("Not implemented yet!");
110 }
111}
112
113bool AVRAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
114 const char *ExtraCode, raw_ostream &O) {
115 // Default asm printer can only deal with some extra codes,
116 // so try it first.
117 if (!AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O))
118 return false;
119
120 const MachineOperand &MO = MI->getOperand(OpNum);
121
122 // Operand must be a register when using 'A' ~ 'Z' extra code.
123 if (ExtraCode && ExtraCode[0] && MO.isReg()) {
124 // Unknown extra code.
125 if (ExtraCode[1] != 0 || ExtraCode[0] < 'A' || ExtraCode[0] > 'Z')
126 return true;
127
128 Register Reg = MO.getReg();
129
130 unsigned ByteNumber = ExtraCode[0] - 'A';
131 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
132 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
133
134 const AVRSubtarget &STI = MF->getSubtarget<AVRSubtarget>();
135 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
136
137 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
138 unsigned BytesPerReg = TRI.getRegSizeInBits(*RC) / 8;
139 assert(BytesPerReg <= 2 && "Only 8 and 16 bit regs are supported.");
140
141 unsigned RegIdx = ByteNumber / BytesPerReg;
142 if (RegIdx >= NumOpRegs)
143 return true;
144 Reg = MI->getOperand(OpNum + RegIdx).getReg();
145
146 if (BytesPerReg == 2) {
147 Reg = TRI.getSubReg(Reg, (ByteNumber % BytesPerReg) ? AVR::sub_hi
148 : AVR::sub_lo);
149 }
150
152 return false;
153 }
154
156 PrintSymbolOperand(MO, O); // Print global symbols.
157 else
158 printOperand(MI, OpNum, O); // Fallback to ordinary cases.
159
160 return false;
161}
162
163bool AVRAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
164 unsigned OpNum, const char *ExtraCode,
165 raw_ostream &O) {
166 if (ExtraCode && ExtraCode[0])
167 return true; // Unknown modifier
168
169 const MachineOperand &MO = MI->getOperand(OpNum);
170
171 // Print direct memory operands.
172 if (MO.isGlobal() || MO.isSymbol() || MO.isMCSymbol()) {
173 PrintSymbolOperand(MO, O);
174 return false;
175 }
176
177 assert(MO.isReg() && "Unexpected inline asm memory operand");
178
179 // TODO: We should be able to look up the alternative name for
180 // the register if it's given.
181 // TableGen doesn't expose a way of getting retrieving names
182 // for registers.
183 if (MI->getOperand(OpNum).getReg() == AVR::R31R30) {
184 O << "Z";
185 } else if (MI->getOperand(OpNum).getReg() == AVR::R29R28) {
186 O << "Y";
187 } else if (MI->getOperand(OpNum).getReg() == AVR::R27R26) {
188 O << "X";
189 } else {
190 assert(false && "Wrong register class for memory operand.");
191 }
192
193 // If NumOpRegs == 2, then we assume it is product of a FrameIndex expansion
194 // and the second operand is an Imm.
195 const InlineAsm::Flag OpFlags(MI->getOperand(OpNum - 1).getImm());
196 const unsigned NumOpRegs = OpFlags.getNumOperandRegisters();
197
198 if (NumOpRegs == 2) {
199 assert(MI->getOperand(OpNum).getReg() != AVR::R27R26 &&
200 "Base register X can not have offset/displacement.");
201 O << '+' << MI->getOperand(OpNum + 1).getImm();
202 }
203
204 return false;
205}
206
207void AVRAsmPrinter::emitInstruction(const MachineInstr *MI) {
208 AVR_MC::verifyInstructionPredicates(MI->getOpcode(),
209 getSubtargetInfo().getFeatureBits());
210
211 AVRMCInstLower MCInstLowering(OutContext, *this);
212
213 MCInst I;
214 MCInstLowering.lowerInstruction(*MI, I);
215 EmitToStreamer(*OutStreamer, I);
216}
217
218const MCExpr *AVRAsmPrinter::lowerConstant(const Constant *CV,
219 const Constant *BaseCV,
221 MCContext &Ctx = OutContext;
222
223 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
224 bool IsProgMem = GV->getAddressSpace() == AVR::ProgramMemory;
225 if (IsProgMem) {
226 const MCExpr *Expr = MCSymbolRefExpr::create(getSymbol(GV), Ctx);
227 return AVRMCExpr::create(AVR::S_PM, Expr, false, Ctx);
228 }
229 }
230
231 return AsmPrinter::lowerConstant(CV, BaseCV, Offset);
232}
233
234void AVRAsmPrinter::emitXXStructor(const DataLayout &DL, const Constant *CV) {
235 if (!EmittedStructorSymbolAttrs) {
236 OutStreamer->emitRawComment(
237 " Emitting these undefined symbol references causes us to link the"
238 " libgcc code that runs our constructors/destructors");
239 OutStreamer->emitRawComment(" This matches GCC's behavior");
240
241 MCSymbol *CtorsSym = OutContext.getOrCreateSymbol("__do_global_ctors");
242 OutStreamer->emitSymbolAttribute(CtorsSym, MCSA_Global);
243
244 MCSymbol *DtorsSym = OutContext.getOrCreateSymbol("__do_global_dtors");
245 OutStreamer->emitSymbolAttribute(DtorsSym, MCSA_Global);
246
247 EmittedStructorSymbolAttrs = true;
248 }
249
251}
252
253bool AVRAsmPrinter::doFinalization(Module &M) {
254 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
255 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
256 const AVRSubtarget *SubTM = TM.getSubtargetImpl();
257
258 bool NeedsCopyData = false;
259 bool NeedsClearBSS = false;
260 for (const auto &GO : M.globals()) {
261 if (!GO.hasInitializer() || GO.hasAvailableExternallyLinkage())
262 // These globals aren't defined in the current object file.
263 continue;
264
265 if (GO.hasCommonLinkage()) {
266 // COMMON symbols are put in .bss.
267 NeedsClearBSS = true;
268 continue;
269 }
270
271 auto *Section = static_cast<MCSectionELF *>(TLOF.SectionForGlobal(&GO, TM));
272 if (Section->getName().starts_with(".data"))
273 NeedsCopyData = true;
274 else if (Section->getName().starts_with(".rodata") && SubTM->hasLPM())
275 // AVRs that have a separate program memory (that's most AVRs) store
276 // .rodata sections in RAM.
277 NeedsCopyData = true;
278 else if (Section->getName().starts_with(".bss"))
279 NeedsClearBSS = true;
280 }
281
282 MCSymbol *DoCopyData = OutContext.getOrCreateSymbol("__do_copy_data");
283 MCSymbol *DoClearBss = OutContext.getOrCreateSymbol("__do_clear_bss");
284
285 if (NeedsCopyData) {
286 OutStreamer->emitRawComment(
287 " Declaring this symbol tells the CRT that it should");
288 OutStreamer->emitRawComment(
289 "copy all variables from program memory to RAM on startup");
290 OutStreamer->emitSymbolAttribute(DoCopyData, MCSA_Global);
291 }
292
293 if (NeedsClearBSS) {
294 OutStreamer->emitRawComment(
295 " Declaring this symbol tells the CRT that it should");
296 OutStreamer->emitRawComment("clear the zeroed data section on startup");
297 OutStreamer->emitSymbolAttribute(DoClearBss, MCSA_Global);
298 }
299
301}
302
303void AVRAsmPrinter::emitStartOfAsmFile(Module &M) {
304 const AVRTargetMachine &TM = (const AVRTargetMachine &)MMI->getTarget();
305 const AVRSubtarget *SubTM = TM.getSubtargetImpl();
306 if (!SubTM)
307 return;
308
309 // Emit __tmp_reg__.
310 OutStreamer->emitAssignment(
311 MMI->getContext().getOrCreateSymbol(StringRef("__tmp_reg__")),
312 MCConstantExpr::create(SubTM->getRegTmpIndex(), MMI->getContext()));
313 // Emit __zero_reg__.
314 OutStreamer->emitAssignment(
315 MMI->getContext().getOrCreateSymbol(StringRef("__zero_reg__")),
316 MCConstantExpr::create(SubTM->getRegZeroIndex(), MMI->getContext()));
317 // Emit __SREG__.
318 OutStreamer->emitAssignment(
319 MMI->getContext().getOrCreateSymbol(StringRef("__SREG__")),
320 MCConstantExpr::create(SubTM->getIORegSREG(), MMI->getContext()));
321 // Emit __SP_H__ if available.
322 if (!SubTM->hasSmallStack())
323 OutStreamer->emitAssignment(
324 MMI->getContext().getOrCreateSymbol(StringRef("__SP_H__")),
325 MCConstantExpr::create(SubTM->getIORegSPH(), MMI->getContext()));
326 // Emit __SP_L__.
327 OutStreamer->emitAssignment(
328 MMI->getContext().getOrCreateSymbol(StringRef("__SP_L__")),
329 MCConstantExpr::create(SubTM->getIORegSPL(), MMI->getContext()));
330 // Emit __EIND__ if available.
331 if (SubTM->hasEIJMPCALL())
332 OutStreamer->emitAssignment(
333 MMI->getContext().getOrCreateSymbol(StringRef("__EIND__")),
334 MCConstantExpr::create(SubTM->getIORegEIND(), MMI->getContext()));
335 // Emit __RAMPZ__ if available.
336 if (SubTM->hasELPM())
337 OutStreamer->emitAssignment(
338 MMI->getContext().getOrCreateSymbol(StringRef("__RAMPZ__")),
339 MCConstantExpr::create(SubTM->getIORegRAMPZ(), MMI->getContext()));
340}
341
342char AVRAsmPrinter::ID = 0;
343
344INITIALIZE_PASS(AVRAsmPrinter, "avr-asm-printer", "AVR Assembly Printer", false,
345 false)
346
348LLVMInitializeAVRAsmPrinter() {
350}
351
354 AVRAsmPrinter &AsmPrinter = static_cast<AVRAsmPrinter &>(
355 MAM.getResult<AsmPrinterAnalysis>(M).getPrinter());
358 return PreservedAnalyses::all();
359}
360
363 AVRAsmPrinter &AsmPrinter = static_cast<AVRAsmPrinter &>(
365 .getCachedResult<AsmPrinterAnalysis>(*MF.getFunction().getParent())
366 ->getPrinter());
369 return PreservedAnalyses::all();
370}
371
374 AVRAsmPrinter &AsmPrinter = static_cast<AVRAsmPrinter &>(
375 MAM.getResult<AsmPrinterAnalysis>(M).getPrinter());
378 return PreservedAnalyses::all();
379}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#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
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, const RISCVSubtarget &Subtarget)
MachineRegisterInfo & MRI
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
std::unique_ptr< MCStreamer > && Streamer
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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
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:95
virtual const MCExpr * lowerConstant(const Constant *CV, const Constant *BaseCV=nullptr, uint64_t Offset=0)
Lower the specified LLVM Constant to an MCExpr.
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:478
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:688
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:44
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:213
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
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 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:68
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
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
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ ProgramMemory
Definition AVR.h:76
@ S_PM
Corresponds to pm(), reference to program memory.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
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()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
LLVM_ABI void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
@ MCSA_Global
.type _foo, @gnu_unique_object
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...