1 //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the inline assembler pieces of the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/TargetAsmParser.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
38 struct SrcMgrDiagInfo {
39 const MDNode *LocInfo;
40 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
45 /// SrcMgrDiagHandler - This callback is invoked when the SourceMgr for an
46 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
48 static void SrcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
49 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
50 assert(DiagInfo && "Diagnostic context not passed down?");
52 // If the inline asm had metadata associated with it, pull out a location
53 // cookie corresponding to which line the error occurred on.
54 unsigned LocCookie = 0;
55 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
56 unsigned ErrorLine = Diag.getLineNo()-1;
57 if (ErrorLine >= LocInfo->getNumOperands())
60 if (LocInfo->getNumOperands() != 0)
61 if (const ConstantInt *CI =
62 dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
63 LocCookie = CI->getZExtValue();
66 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
69 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
70 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode) const {
71 assert(!Str.empty() && "Can't emit empty inline asm block");
73 // Remember if the buffer is nul terminated or not so we can avoid a copy.
74 bool isNullTerminated = Str.back() == 0;
76 Str = Str.substr(0, Str.size()-1);
78 // If the output streamer is actually a .s file, just emit the blob textually.
79 // This is useful in case the asm parser doesn't handle something but the
80 // system assembler does.
81 if (OutStreamer.hasRawTextSupport()) {
82 OutStreamer.EmitRawText(Str);
87 SrcMgrDiagInfo DiagInfo;
89 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
90 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
91 bool HasDiagHandler = false;
92 if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
93 // If the source manager has an issue, we arrange for SrcMgrDiagHandler
94 // to be invoked, getting DiagInfo passed into it.
95 DiagInfo.LocInfo = LocMDNode;
96 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
97 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
98 SrcMgr.setDiagHandler(SrcMgrDiagHandler, &DiagInfo);
99 HasDiagHandler = true;
102 MemoryBuffer *Buffer;
103 if (isNullTerminated)
104 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
106 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
108 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
109 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
111 OwningPtr<MCAsmParser> Parser(createMCAsmParser(TM.getTarget(), SrcMgr,
112 OutContext, OutStreamer,
114 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(*Parser, TM));
116 report_fatal_error("Inline asm not supported by this streamer because"
117 " we don't have an asm parser for this target\n");
118 Parser->setTargetParser(*TAP.get());
120 // Don't implicitly switch to the text section before the asm.
121 int Res = Parser->Run(/*NoInitialTextSection*/ true,
122 /*NoFinalize*/ true);
123 if (Res && !HasDiagHandler)
124 report_fatal_error("Error parsing inline asm\n");
128 /// EmitInlineAsm - This method formats and emits the specified machine
129 /// instruction that is an inline asm.
130 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
131 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
133 unsigned NumOperands = MI->getNumOperands();
135 // Count the number of register definitions to find the asm string.
136 unsigned NumDefs = 0;
137 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
139 assert(NumDefs != NumOperands-2 && "No asm string?");
141 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
143 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
144 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
146 // If this asmstr is empty, just print the #APP/#NOAPP markers.
147 // These are useful to see where empty asm's wound up.
148 if (AsmStr[0] == 0) {
149 // Don't emit the comments if writing to a .o file.
150 if (!OutStreamer.hasRawTextSupport()) return;
152 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
153 MAI->getInlineAsmStart());
154 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
155 MAI->getInlineAsmEnd());
159 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
160 // enabled, so we use EmitRawText.
161 if (OutStreamer.hasRawTextSupport())
162 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
163 MAI->getInlineAsmStart());
165 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
167 unsigned LocCookie = 0;
168 const MDNode *LocMD = 0;
169 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
170 if (MI->getOperand(i-1).isMetadata() &&
171 (LocMD = MI->getOperand(i-1).getMetadata()) &&
172 LocMD->getNumOperands() != 0) {
173 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
174 LocCookie = CI->getZExtValue();
180 // Emit the inline asm to a temporary string so we can emit it through
182 SmallString<256> StringData;
183 raw_svector_ostream OS(StringData);
187 // The variant of the current asmprinter.
188 int AsmPrinterVariant = MAI->getAssemblerDialect();
190 int CurVariant = -1; // The number of the {.|.|.} region we are in.
191 const char *LastEmitted = AsmStr; // One past the last character emitted.
193 while (*LastEmitted) {
194 switch (*LastEmitted) {
196 // Not a special case, emit the string section literally.
197 const char *LiteralEnd = LastEmitted+1;
198 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
199 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
201 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
202 OS.write(LastEmitted, LiteralEnd-LastEmitted);
203 LastEmitted = LiteralEnd;
207 ++LastEmitted; // Consume newline character.
208 OS << '\n'; // Indent code with newline.
211 ++LastEmitted; // Consume '$' character.
215 switch (*LastEmitted) {
216 default: Done = false; break;
218 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
220 ++LastEmitted; // Consume second '$' character.
222 case '(': // $( -> same as GCC's { character.
223 ++LastEmitted; // Consume '(' character.
224 if (CurVariant != -1)
225 report_fatal_error("Nested variants found in inline asm string: '" +
226 Twine(AsmStr) + "'");
227 CurVariant = 0; // We're in the first variant now.
230 ++LastEmitted; // consume '|' character.
231 if (CurVariant == -1)
232 OS << '|'; // this is gcc's behavior for | outside a variant
234 ++CurVariant; // We're in the next variant.
236 case ')': // $) -> same as GCC's } char.
237 ++LastEmitted; // consume ')' character.
238 if (CurVariant == -1)
239 OS << '}'; // this is gcc's behavior for } outside a variant
246 bool HasCurlyBraces = false;
247 if (*LastEmitted == '{') { // ${variable}
248 ++LastEmitted; // Consume '{' character.
249 HasCurlyBraces = true;
252 // If we have ${:foo}, then this is not a real operand reference, it is a
253 // "magic" string reference, just like in .td files. Arrange to call
255 if (HasCurlyBraces && *LastEmitted == ':') {
257 const char *StrStart = LastEmitted;
258 const char *StrEnd = strchr(StrStart, '}');
260 report_fatal_error("Unterminated ${:foo} operand in inline asm"
261 " string: '" + Twine(AsmStr) + "'");
263 std::string Val(StrStart, StrEnd);
264 PrintSpecial(MI, OS, Val.c_str());
265 LastEmitted = StrEnd+1;
269 const char *IDStart = LastEmitted;
270 const char *IDEnd = IDStart;
271 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
274 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
275 report_fatal_error("Bad $ operand number in inline asm string: '" +
276 Twine(AsmStr) + "'");
279 char Modifier[2] = { 0, 0 };
281 if (HasCurlyBraces) {
282 // If we have curly braces, check for a modifier character. This
283 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
284 if (*LastEmitted == ':') {
285 ++LastEmitted; // Consume ':' character.
286 if (*LastEmitted == 0)
287 report_fatal_error("Bad ${:} expression in inline asm string: '" +
288 Twine(AsmStr) + "'");
290 Modifier[0] = *LastEmitted;
291 ++LastEmitted; // Consume modifier character.
294 if (*LastEmitted != '}')
295 report_fatal_error("Bad ${} expression in inline asm string: '" +
296 Twine(AsmStr) + "'");
297 ++LastEmitted; // Consume '}' character.
300 if (Val >= NumOperands-1)
301 report_fatal_error("Invalid $ operand number in inline asm string: '" +
302 Twine(AsmStr) + "'");
304 // Okay, we finally have a value number. Ask the target to print this
306 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
307 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
311 // Scan to find the machine operand number for the operand.
313 if (OpNo >= MI->getNumOperands()) break;
314 unsigned OpFlags = MI->getOperand(OpNo).getImm();
315 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
318 if (OpNo >= MI->getNumOperands()) {
321 unsigned OpFlags = MI->getOperand(OpNo).getImm();
322 ++OpNo; // Skip over the ID number.
324 if (Modifier[0] == 'l') // labels are target independent
325 // FIXME: What if the operand isn't an MBB, report error?
326 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
328 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
329 if (InlineAsm::isMemKind(OpFlags)) {
330 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
331 Modifier[0] ? Modifier : 0,
334 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
335 Modifier[0] ? Modifier : 0, OS);
341 raw_string_ostream Msg(msg);
342 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
343 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
350 OS << '\n' << (char)0; // null terminate string.
351 EmitInlineAsm(OS.str(), LocMD);
353 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
354 // enabled, so we use EmitRawText.
355 if (OutStreamer.hasRawTextSupport())
356 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
357 MAI->getInlineAsmEnd());
361 /// PrintSpecial - Print information related to the specified machine instr
362 /// that is independent of the operand, and may be independent of the instr
363 /// itself. This can be useful for portably encoding the comment character
364 /// or other bits of target-specific knowledge into the asmstrings. The
365 /// syntax used is ${:comment}. Targets can override this to add support
366 /// for their own strange codes.
367 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
368 const char *Code) const {
369 if (!strcmp(Code, "private")) {
370 OS << MAI->getPrivateGlobalPrefix();
371 } else if (!strcmp(Code, "comment")) {
372 OS << MAI->getCommentString();
373 } else if (!strcmp(Code, "uid")) {
374 // Comparing the address of MI isn't sufficient, because machineinstrs may
375 // be allocated to the same address across functions.
377 // If this is a new LastFn instruction, bump the counter.
378 if (LastMI != MI || LastFn != getFunctionNumber()) {
381 LastFn = getFunctionNumber();
386 raw_string_ostream Msg(msg);
387 Msg << "Unknown special formatter '" << Code
388 << "' for machine instr: " << *MI;
389 report_fatal_error(Msg.str());
393 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
394 /// instruction, using the specified assembler variant. Targets should
395 /// override this to format as appropriate.
396 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
397 unsigned AsmVariant, const char *ExtraCode,
399 // Target doesn't support this yet!
403 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
405 const char *ExtraCode, raw_ostream &O) {
406 // Target doesn't support this yet!