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,
115 OwningPtr<TargetAsmParser>
116 TAP(TM.getTarget().createAsmParser(TM.getTargetTriple(),
118 TM.getTargetFeatureString(),
121 report_fatal_error("Inline asm not supported by this streamer because"
122 " we don't have an asm parser for this target\n");
123 Parser->setTargetParser(*TAP.get());
125 // Don't implicitly switch to the text section before the asm.
126 int Res = Parser->Run(/*NoInitialTextSection*/ true,
127 /*NoFinalize*/ true);
128 if (Res && !HasDiagHandler)
129 report_fatal_error("Error parsing inline asm\n");
133 /// EmitInlineAsm - This method formats and emits the specified machine
134 /// instruction that is an inline asm.
135 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
136 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
138 unsigned NumOperands = MI->getNumOperands();
140 // Count the number of register definitions to find the asm string.
141 unsigned NumDefs = 0;
142 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
144 assert(NumDefs != NumOperands-2 && "No asm string?");
146 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
148 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
149 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
151 // If this asmstr is empty, just print the #APP/#NOAPP markers.
152 // These are useful to see where empty asm's wound up.
153 if (AsmStr[0] == 0) {
154 // Don't emit the comments if writing to a .o file.
155 if (!OutStreamer.hasRawTextSupport()) return;
157 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
158 MAI->getInlineAsmStart());
159 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
160 MAI->getInlineAsmEnd());
164 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
165 // enabled, so we use EmitRawText.
166 if (OutStreamer.hasRawTextSupport())
167 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
168 MAI->getInlineAsmStart());
170 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
172 unsigned LocCookie = 0;
173 const MDNode *LocMD = 0;
174 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
175 if (MI->getOperand(i-1).isMetadata() &&
176 (LocMD = MI->getOperand(i-1).getMetadata()) &&
177 LocMD->getNumOperands() != 0) {
178 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
179 LocCookie = CI->getZExtValue();
185 // Emit the inline asm to a temporary string so we can emit it through
187 SmallString<256> StringData;
188 raw_svector_ostream OS(StringData);
192 // The variant of the current asmprinter.
193 int AsmPrinterVariant = MAI->getAssemblerDialect();
195 int CurVariant = -1; // The number of the {.|.|.} region we are in.
196 const char *LastEmitted = AsmStr; // One past the last character emitted.
198 while (*LastEmitted) {
199 switch (*LastEmitted) {
201 // Not a special case, emit the string section literally.
202 const char *LiteralEnd = LastEmitted+1;
203 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
204 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
206 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
207 OS.write(LastEmitted, LiteralEnd-LastEmitted);
208 LastEmitted = LiteralEnd;
212 ++LastEmitted; // Consume newline character.
213 OS << '\n'; // Indent code with newline.
216 ++LastEmitted; // Consume '$' character.
220 switch (*LastEmitted) {
221 default: Done = false; break;
223 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
225 ++LastEmitted; // Consume second '$' character.
227 case '(': // $( -> same as GCC's { character.
228 ++LastEmitted; // Consume '(' character.
229 if (CurVariant != -1)
230 report_fatal_error("Nested variants found in inline asm string: '" +
231 Twine(AsmStr) + "'");
232 CurVariant = 0; // We're in the first variant now.
235 ++LastEmitted; // consume '|' character.
236 if (CurVariant == -1)
237 OS << '|'; // this is gcc's behavior for | outside a variant
239 ++CurVariant; // We're in the next variant.
241 case ')': // $) -> same as GCC's } char.
242 ++LastEmitted; // consume ')' character.
243 if (CurVariant == -1)
244 OS << '}'; // this is gcc's behavior for } outside a variant
251 bool HasCurlyBraces = false;
252 if (*LastEmitted == '{') { // ${variable}
253 ++LastEmitted; // Consume '{' character.
254 HasCurlyBraces = true;
257 // If we have ${:foo}, then this is not a real operand reference, it is a
258 // "magic" string reference, just like in .td files. Arrange to call
260 if (HasCurlyBraces && *LastEmitted == ':') {
262 const char *StrStart = LastEmitted;
263 const char *StrEnd = strchr(StrStart, '}');
265 report_fatal_error("Unterminated ${:foo} operand in inline asm"
266 " string: '" + Twine(AsmStr) + "'");
268 std::string Val(StrStart, StrEnd);
269 PrintSpecial(MI, OS, Val.c_str());
270 LastEmitted = StrEnd+1;
274 const char *IDStart = LastEmitted;
275 const char *IDEnd = IDStart;
276 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
279 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
280 report_fatal_error("Bad $ operand number in inline asm string: '" +
281 Twine(AsmStr) + "'");
284 char Modifier[2] = { 0, 0 };
286 if (HasCurlyBraces) {
287 // If we have curly braces, check for a modifier character. This
288 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
289 if (*LastEmitted == ':') {
290 ++LastEmitted; // Consume ':' character.
291 if (*LastEmitted == 0)
292 report_fatal_error("Bad ${:} expression in inline asm string: '" +
293 Twine(AsmStr) + "'");
295 Modifier[0] = *LastEmitted;
296 ++LastEmitted; // Consume modifier character.
299 if (*LastEmitted != '}')
300 report_fatal_error("Bad ${} expression in inline asm string: '" +
301 Twine(AsmStr) + "'");
302 ++LastEmitted; // Consume '}' character.
305 if (Val >= NumOperands-1)
306 report_fatal_error("Invalid $ operand number in inline asm string: '" +
307 Twine(AsmStr) + "'");
309 // Okay, we finally have a value number. Ask the target to print this
311 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
312 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
316 // Scan to find the machine operand number for the operand.
318 if (OpNo >= MI->getNumOperands()) break;
319 unsigned OpFlags = MI->getOperand(OpNo).getImm();
320 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
323 if (OpNo >= MI->getNumOperands()) {
326 unsigned OpFlags = MI->getOperand(OpNo).getImm();
327 ++OpNo; // Skip over the ID number.
329 if (Modifier[0] == 'l') // labels are target independent
330 // FIXME: What if the operand isn't an MBB, report error?
331 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
333 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
334 if (InlineAsm::isMemKind(OpFlags)) {
335 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
336 Modifier[0] ? Modifier : 0,
339 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
340 Modifier[0] ? Modifier : 0, OS);
346 raw_string_ostream Msg(msg);
347 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
348 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
355 OS << '\n' << (char)0; // null terminate string.
356 EmitInlineAsm(OS.str(), LocMD);
358 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
359 // enabled, so we use EmitRawText.
360 if (OutStreamer.hasRawTextSupport())
361 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
362 MAI->getInlineAsmEnd());
366 /// PrintSpecial - Print information related to the specified machine instr
367 /// that is independent of the operand, and may be independent of the instr
368 /// itself. This can be useful for portably encoding the comment character
369 /// or other bits of target-specific knowledge into the asmstrings. The
370 /// syntax used is ${:comment}. Targets can override this to add support
371 /// for their own strange codes.
372 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
373 const char *Code) const {
374 if (!strcmp(Code, "private")) {
375 OS << MAI->getPrivateGlobalPrefix();
376 } else if (!strcmp(Code, "comment")) {
377 OS << MAI->getCommentString();
378 } else if (!strcmp(Code, "uid")) {
379 // Comparing the address of MI isn't sufficient, because machineinstrs may
380 // be allocated to the same address across functions.
382 // If this is a new LastFn instruction, bump the counter.
383 if (LastMI != MI || LastFn != getFunctionNumber()) {
386 LastFn = getFunctionNumber();
391 raw_string_ostream Msg(msg);
392 Msg << "Unknown special formatter '" << Code
393 << "' for machine instr: " << *MI;
394 report_fatal_error(Msg.str());
398 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
399 /// instruction, using the specified assembler variant. Targets should
400 /// override this to format as appropriate.
401 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
402 unsigned AsmVariant, const char *ExtraCode,
404 // Target doesn't support this yet!
408 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
410 const char *ExtraCode, raw_ostream &O) {
411 // Target doesn't support this yet!