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/ADT/OwningPtr.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
41 struct SrcMgrDiagInfo {
42 const MDNode *LocInfo;
43 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
48 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
49 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
51 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
52 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
53 assert(DiagInfo && "Diagnostic context not passed down?");
55 // If the inline asm had metadata associated with it, pull out a location
56 // cookie corresponding to which line the error occurred on.
57 unsigned LocCookie = 0;
58 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
59 unsigned ErrorLine = Diag.getLineNo()-1;
60 if (ErrorLine >= LocInfo->getNumOperands())
63 if (LocInfo->getNumOperands() != 0)
64 if (const ConstantInt *CI =
65 dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
66 LocCookie = CI->getZExtValue();
69 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
72 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
73 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
74 InlineAsm::AsmDialect Dialect) const {
75 assert(!Str.empty() && "Can't emit empty inline asm block");
77 // Remember if the buffer is nul terminated or not so we can avoid a copy.
78 bool isNullTerminated = Str.back() == 0;
80 Str = Str.substr(0, Str.size()-1);
82 // If the output streamer is actually a .s file, just emit the blob textually.
83 // This is useful in case the asm parser doesn't handle something but the
84 // system assembler does.
85 if (OutStreamer.hasRawTextSupport()) {
86 OutStreamer.EmitRawText(Str);
87 emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), 0);
92 SrcMgrDiagInfo DiagInfo;
94 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
95 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
96 bool HasDiagHandler = false;
97 if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
98 // If the source manager has an issue, we arrange for srcMgrDiagHandler
99 // to be invoked, getting DiagInfo passed into it.
100 DiagInfo.LocInfo = LocMDNode;
101 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
102 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
103 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
104 HasDiagHandler = true;
107 MemoryBuffer *Buffer;
108 if (isNullTerminated)
109 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
111 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
113 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
114 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
116 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
117 OutContext, OutStreamer,
120 // Reuse the existing Subtarget, because the AsmParser may need to
121 // modify it. For example, when switching between ARM and
123 MCSubtargetInfo* STI =
124 const_cast<MCSubtargetInfo*>(&TM.getSubtarget<MCSubtargetInfo>());
126 // Preserve a copy of the original STI because the parser may modify it.
127 // The target can restore the original state in emitInlineAsmEnd().
128 MCSubtargetInfo STIOrig = *STI;
130 OwningPtr<MCTargetAsmParser>
131 TAP(TM.getTarget().createMCAsmParser(*STI, *Parser, *MII));
133 report_fatal_error("Inline asm not supported by this streamer because"
134 " we don't have an asm parser for this target\n");
135 Parser->setAssemblerDialect(Dialect);
136 Parser->setTargetParser(*TAP.get());
138 // Don't implicitly switch to the text section before the asm.
139 int Res = Parser->Run(/*NoInitialTextSection*/ true,
140 /*NoFinalize*/ true);
141 emitInlineAsmEnd(STIOrig, STI);
142 if (Res && !HasDiagHandler)
143 report_fatal_error("Error parsing inline asm\n");
146 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
147 MachineModuleInfo *MMI, int InlineAsmVariant,
148 AsmPrinter *AP, unsigned LocCookie,
150 // Switch to the inline assembly variant.
151 OS << "\t.intel_syntax\n\t";
153 const char *LastEmitted = AsmStr; // One past the last character emitted.
154 unsigned NumOperands = MI->getNumOperands();
156 while (*LastEmitted) {
157 switch (*LastEmitted) {
159 // Not a special case, emit the string section literally.
160 const char *LiteralEnd = LastEmitted+1;
161 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
162 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
165 OS.write(LastEmitted, LiteralEnd-LastEmitted);
166 LastEmitted = LiteralEnd;
170 ++LastEmitted; // Consume newline character.
171 OS << '\n'; // Indent code with newline.
174 ++LastEmitted; // Consume '$' character.
178 switch (*LastEmitted) {
179 default: Done = false; break;
181 ++LastEmitted; // Consume second '$' character.
186 const char *IDStart = LastEmitted;
187 const char *IDEnd = IDStart;
188 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
191 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
192 report_fatal_error("Bad $ operand number in inline asm string: '" +
193 Twine(AsmStr) + "'");
196 if (Val >= NumOperands-1)
197 report_fatal_error("Invalid $ operand number in inline asm string: '" +
198 Twine(AsmStr) + "'");
200 // Okay, we finally have a value number. Ask the target to print this
202 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
206 // Scan to find the machine operand number for the operand.
208 if (OpNo >= MI->getNumOperands()) break;
209 unsigned OpFlags = MI->getOperand(OpNo).getImm();
210 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
213 // We may have a location metadata attached to the end of the
214 // instruction, and at no point should see metadata at any
215 // other point while processing. It's an error if so.
216 if (OpNo >= MI->getNumOperands() ||
217 MI->getOperand(OpNo).isMetadata()) {
220 unsigned OpFlags = MI->getOperand(OpNo).getImm();
221 ++OpNo; // Skip over the ID number.
223 if (InlineAsm::isMemKind(OpFlags)) {
224 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
227 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
233 raw_string_ostream Msg(msg);
234 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
235 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
241 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
244 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
245 MachineModuleInfo *MMI, int InlineAsmVariant,
246 int AsmPrinterVariant, AsmPrinter *AP,
247 unsigned LocCookie, raw_ostream &OS) {
248 int CurVariant = -1; // The number of the {.|.|.} region we are in.
249 const char *LastEmitted = AsmStr; // One past the last character emitted.
250 unsigned NumOperands = MI->getNumOperands();
254 while (*LastEmitted) {
255 switch (*LastEmitted) {
257 // Not a special case, emit the string section literally.
258 const char *LiteralEnd = LastEmitted+1;
259 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
260 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
262 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
263 OS.write(LastEmitted, LiteralEnd-LastEmitted);
264 LastEmitted = LiteralEnd;
268 ++LastEmitted; // Consume newline character.
269 OS << '\n'; // Indent code with newline.
272 ++LastEmitted; // Consume '$' character.
276 switch (*LastEmitted) {
277 default: Done = false; break;
279 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
281 ++LastEmitted; // Consume second '$' character.
283 case '(': // $( -> same as GCC's { character.
284 ++LastEmitted; // Consume '(' character.
285 if (CurVariant != -1)
286 report_fatal_error("Nested variants found in inline asm string: '" +
287 Twine(AsmStr) + "'");
288 CurVariant = 0; // We're in the first variant now.
291 ++LastEmitted; // consume '|' character.
292 if (CurVariant == -1)
293 OS << '|'; // this is gcc's behavior for | outside a variant
295 ++CurVariant; // We're in the next variant.
297 case ')': // $) -> same as GCC's } char.
298 ++LastEmitted; // consume ')' character.
299 if (CurVariant == -1)
300 OS << '}'; // this is gcc's behavior for } outside a variant
307 bool HasCurlyBraces = false;
308 if (*LastEmitted == '{') { // ${variable}
309 ++LastEmitted; // Consume '{' character.
310 HasCurlyBraces = true;
313 // If we have ${:foo}, then this is not a real operand reference, it is a
314 // "magic" string reference, just like in .td files. Arrange to call
316 if (HasCurlyBraces && *LastEmitted == ':') {
318 const char *StrStart = LastEmitted;
319 const char *StrEnd = strchr(StrStart, '}');
321 report_fatal_error("Unterminated ${:foo} operand in inline asm"
322 " string: '" + Twine(AsmStr) + "'");
324 std::string Val(StrStart, StrEnd);
325 AP->PrintSpecial(MI, OS, Val.c_str());
326 LastEmitted = StrEnd+1;
330 const char *IDStart = LastEmitted;
331 const char *IDEnd = IDStart;
332 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
335 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
336 report_fatal_error("Bad $ operand number in inline asm string: '" +
337 Twine(AsmStr) + "'");
340 char Modifier[2] = { 0, 0 };
342 if (HasCurlyBraces) {
343 // If we have curly braces, check for a modifier character. This
344 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
345 if (*LastEmitted == ':') {
346 ++LastEmitted; // Consume ':' character.
347 if (*LastEmitted == 0)
348 report_fatal_error("Bad ${:} expression in inline asm string: '" +
349 Twine(AsmStr) + "'");
351 Modifier[0] = *LastEmitted;
352 ++LastEmitted; // Consume modifier character.
355 if (*LastEmitted != '}')
356 report_fatal_error("Bad ${} expression in inline asm string: '" +
357 Twine(AsmStr) + "'");
358 ++LastEmitted; // Consume '}' character.
361 if (Val >= NumOperands-1)
362 report_fatal_error("Invalid $ operand number in inline asm string: '" +
363 Twine(AsmStr) + "'");
365 // Okay, we finally have a value number. Ask the target to print this
367 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
368 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
372 // Scan to find the machine operand number for the operand.
374 if (OpNo >= MI->getNumOperands()) break;
375 unsigned OpFlags = MI->getOperand(OpNo).getImm();
376 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
379 // We may have a location metadata attached to the end of the
380 // instruction, and at no point should see metadata at any
381 // other point while processing. It's an error if so.
382 if (OpNo >= MI->getNumOperands() ||
383 MI->getOperand(OpNo).isMetadata()) {
386 unsigned OpFlags = MI->getOperand(OpNo).getImm();
387 ++OpNo; // Skip over the ID number.
389 if (Modifier[0] == 'l') // labels are target independent
390 // FIXME: What if the operand isn't an MBB, report error?
391 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
393 if (InlineAsm::isMemKind(OpFlags)) {
394 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
395 Modifier[0] ? Modifier : 0,
398 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
399 Modifier[0] ? Modifier : 0, OS);
405 raw_string_ostream Msg(msg);
406 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
407 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
414 OS << '\n' << (char)0; // null terminate string.
417 /// EmitInlineAsm - This method formats and emits the specified machine
418 /// instruction that is an inline asm.
419 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
420 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
422 // Count the number of register definitions to find the asm string.
423 unsigned NumDefs = 0;
424 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
426 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
428 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
430 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
431 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
433 // If this asmstr is empty, just print the #APP/#NOAPP markers.
434 // These are useful to see where empty asm's wound up.
435 if (AsmStr[0] == 0) {
436 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
437 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
441 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
442 // enabled, so we use emitRawComment.
443 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
445 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
447 unsigned LocCookie = 0;
448 const MDNode *LocMD = 0;
449 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
450 if (MI->getOperand(i-1).isMetadata() &&
451 (LocMD = MI->getOperand(i-1).getMetadata()) &&
452 LocMD->getNumOperands() != 0) {
453 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
454 LocCookie = CI->getZExtValue();
460 // Emit the inline asm to a temporary string so we can emit it through
462 SmallString<256> StringData;
463 raw_svector_ostream OS(StringData);
465 // The variant of the current asmprinter.
466 int AsmPrinterVariant = MAI->getAssemblerDialect();
467 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
468 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
469 if (InlineAsmVariant == InlineAsm::AD_ATT)
470 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
473 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
475 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
477 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
478 // enabled, so we use emitRawComment.
479 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
483 /// PrintSpecial - Print information related to the specified machine instr
484 /// that is independent of the operand, and may be independent of the instr
485 /// itself. This can be useful for portably encoding the comment character
486 /// or other bits of target-specific knowledge into the asmstrings. The
487 /// syntax used is ${:comment}. Targets can override this to add support
488 /// for their own strange codes.
489 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
490 const char *Code) const {
491 const DataLayout *DL = TM.getDataLayout();
492 if (!strcmp(Code, "private")) {
493 OS << DL->getPrivateGlobalPrefix();
494 } else if (!strcmp(Code, "comment")) {
495 OS << MAI->getCommentString();
496 } else if (!strcmp(Code, "uid")) {
497 // Comparing the address of MI isn't sufficient, because machineinstrs may
498 // be allocated to the same address across functions.
500 // If this is a new LastFn instruction, bump the counter.
501 if (LastMI != MI || LastFn != getFunctionNumber()) {
504 LastFn = getFunctionNumber();
509 raw_string_ostream Msg(msg);
510 Msg << "Unknown special formatter '" << Code
511 << "' for machine instr: " << *MI;
512 report_fatal_error(Msg.str());
516 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
517 /// instruction, using the specified assembler variant. Targets should
518 /// override this to format as appropriate.
519 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
520 unsigned AsmVariant, const char *ExtraCode,
522 // Does this asm operand have a single letter operand modifier?
523 if (ExtraCode && ExtraCode[0]) {
524 if (ExtraCode[1] != 0) return true; // Unknown modifier.
526 const MachineOperand &MO = MI->getOperand(OpNo);
527 switch (ExtraCode[0]) {
529 return true; // Unknown modifier.
530 case 'c': // Substitute immediate value without immediate syntax
531 if (MO.getType() != MachineOperand::MO_Immediate)
535 case 'n': // Negate the immediate constant.
536 if (MO.getType() != MachineOperand::MO_Immediate)
545 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
547 const char *ExtraCode, raw_ostream &O) {
548 // Target doesn't support this yet!
552 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
553 MCSubtargetInfo *EndInfo) const {}