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/MCSubtargetInfo.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCTargetAsmParser.h"
27 #include "llvm/Target/TargetMachine.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/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
39 struct SrcMgrDiagInfo {
40 const MDNode *LocInfo;
41 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
46 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
47 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
49 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
50 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
51 assert(DiagInfo && "Diagnostic context not passed down?");
53 // If the inline asm had metadata associated with it, pull out a location
54 // cookie corresponding to which line the error occurred on.
55 unsigned LocCookie = 0;
56 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
57 unsigned ErrorLine = Diag.getLineNo()-1;
58 if (ErrorLine >= LocInfo->getNumOperands())
61 if (LocInfo->getNumOperands() != 0)
62 if (const ConstantInt *CI =
63 dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
64 LocCookie = CI->getZExtValue();
67 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
70 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
71 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
72 InlineAsm::AsmDialect Dialect) const {
73 assert(!Str.empty() && "Can't emit empty inline asm block");
75 // Remember if the buffer is nul terminated or not so we can avoid a copy.
76 bool isNullTerminated = Str.back() == 0;
78 Str = Str.substr(0, Str.size()-1);
80 // If the output streamer is actually a .s file, just emit the blob textually.
81 // This is useful in case the asm parser doesn't handle something but the
82 // system assembler does.
83 if (OutStreamer.hasRawTextSupport()) {
84 OutStreamer.EmitRawText(Str);
89 SrcMgrDiagInfo DiagInfo;
91 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
92 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
93 bool HasDiagHandler = false;
94 if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
95 // If the source manager has an issue, we arrange for srcMgrDiagHandler
96 // to be invoked, getting DiagInfo passed into it.
97 DiagInfo.LocInfo = LocMDNode;
98 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
99 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
100 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
101 HasDiagHandler = true;
104 MemoryBuffer *Buffer;
105 if (isNullTerminated)
106 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
108 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
110 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
111 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
113 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
114 OutContext, OutStreamer,
117 // FIXME: It would be nice if we can avoid createing a new instance of
118 // MCSubtargetInfo here given TargetSubtargetInfo is available. However,
119 // we have to watch out for asm directives which can change subtarget
120 // state. e.g. .code 16, .code 32.
121 OwningPtr<MCSubtargetInfo>
122 STI(TM.getTarget().createMCSubtargetInfo(TM.getTargetTriple(),
124 TM.getTargetFeatureString()));
125 OwningPtr<MCTargetAsmParser>
126 TAP(TM.getTarget().createMCAsmParser(*STI, *Parser));
128 report_fatal_error("Inline asm not supported by this streamer because"
129 " we don't have an asm parser for this target\n");
130 Parser->setAssemblerDialect(Dialect);
131 Parser->setTargetParser(*TAP.get());
133 // Don't implicitly switch to the text section before the asm.
134 int Res = Parser->Run(/*NoInitialTextSection*/ true,
135 /*NoFinalize*/ true);
136 if (Res && !HasDiagHandler)
137 report_fatal_error("Error parsing inline asm\n");
141 /// EmitInlineAsm - This method formats and emits the specified machine
142 /// instruction that is an inline asm.
143 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
144 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
146 unsigned NumOperands = MI->getNumOperands();
148 // Count the number of register definitions to find the asm string.
149 unsigned NumDefs = 0;
150 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
152 assert(NumDefs != NumOperands-2 && "No asm string?");
154 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
156 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
157 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
159 // If this asmstr is empty, just print the #APP/#NOAPP markers.
160 // These are useful to see where empty asm's wound up.
161 if (AsmStr[0] == 0) {
162 // Don't emit the comments if writing to a .o file.
163 if (!OutStreamer.hasRawTextSupport()) return;
165 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
166 MAI->getInlineAsmStart());
167 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
168 MAI->getInlineAsmEnd());
172 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
173 // enabled, so we use EmitRawText.
174 if (OutStreamer.hasRawTextSupport())
175 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
176 MAI->getInlineAsmStart());
178 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
180 unsigned LocCookie = 0;
181 const MDNode *LocMD = 0;
182 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
183 if (MI->getOperand(i-1).isMetadata() &&
184 (LocMD = MI->getOperand(i-1).getMetadata()) &&
185 LocMD->getNumOperands() != 0) {
186 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
187 LocCookie = CI->getZExtValue();
193 // Emit the inline asm to a temporary string so we can emit it through
195 SmallString<256> StringData;
196 raw_svector_ostream OS(StringData);
200 // The variant of the current asmprinter.
201 int AsmPrinterVariant = MAI->getAssemblerDialect();
202 int InlineAsmVariant = MI->getInlineAsmDialect();
204 // Switch to the inline assembly variant.
205 if (AsmPrinterVariant != InlineAsmVariant) {
206 if (InlineAsmVariant == 0)
207 OS << ".att_syntax\n\t";
209 OS << ".intel_syntax\n\t";
212 int CurVariant = -1; // The number of the {.|.|.} region we are in.
213 const char *LastEmitted = AsmStr; // One past the last character emitted.
215 while (*LastEmitted) {
216 switch (*LastEmitted) {
218 // Not a special case, emit the string section literally.
219 const char *LiteralEnd = LastEmitted+1;
220 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
221 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
223 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
224 OS.write(LastEmitted, LiteralEnd-LastEmitted);
225 LastEmitted = LiteralEnd;
229 ++LastEmitted; // Consume newline character.
230 OS << '\n'; // Indent code with newline.
233 ++LastEmitted; // Consume '$' character.
237 switch (*LastEmitted) {
238 default: Done = false; break;
240 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
242 ++LastEmitted; // Consume second '$' character.
244 case '(': // $( -> same as GCC's { character.
245 ++LastEmitted; // Consume '(' character.
246 if (CurVariant != -1)
247 report_fatal_error("Nested variants found in inline asm string: '" +
248 Twine(AsmStr) + "'");
249 CurVariant = 0; // We're in the first variant now.
252 ++LastEmitted; // consume '|' character.
253 if (CurVariant == -1)
254 OS << '|'; // this is gcc's behavior for | outside a variant
256 ++CurVariant; // We're in the next variant.
258 case ')': // $) -> same as GCC's } char.
259 ++LastEmitted; // consume ')' character.
260 if (CurVariant == -1)
261 OS << '}'; // this is gcc's behavior for } outside a variant
268 bool HasCurlyBraces = false;
269 if (*LastEmitted == '{') { // ${variable}
270 ++LastEmitted; // Consume '{' character.
271 HasCurlyBraces = true;
274 // If we have ${:foo}, then this is not a real operand reference, it is a
275 // "magic" string reference, just like in .td files. Arrange to call
277 if (HasCurlyBraces && *LastEmitted == ':') {
279 const char *StrStart = LastEmitted;
280 const char *StrEnd = strchr(StrStart, '}');
282 report_fatal_error("Unterminated ${:foo} operand in inline asm"
283 " string: '" + Twine(AsmStr) + "'");
285 std::string Val(StrStart, StrEnd);
286 PrintSpecial(MI, OS, Val.c_str());
287 LastEmitted = StrEnd+1;
291 const char *IDStart = LastEmitted;
292 const char *IDEnd = IDStart;
293 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
296 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
297 report_fatal_error("Bad $ operand number in inline asm string: '" +
298 Twine(AsmStr) + "'");
301 char Modifier[2] = { 0, 0 };
303 if (HasCurlyBraces) {
304 // If we have curly braces, check for a modifier character. This
305 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
306 if (*LastEmitted == ':') {
307 ++LastEmitted; // Consume ':' character.
308 if (*LastEmitted == 0)
309 report_fatal_error("Bad ${:} expression in inline asm string: '" +
310 Twine(AsmStr) + "'");
312 Modifier[0] = *LastEmitted;
313 ++LastEmitted; // Consume modifier character.
316 if (*LastEmitted != '}')
317 report_fatal_error("Bad ${} expression in inline asm string: '" +
318 Twine(AsmStr) + "'");
319 ++LastEmitted; // Consume '}' character.
322 if (Val >= NumOperands-1)
323 report_fatal_error("Invalid $ operand number in inline asm string: '" +
324 Twine(AsmStr) + "'");
326 // Okay, we finally have a value number. Ask the target to print this
328 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
329 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
333 // Scan to find the machine operand number for the operand.
335 if (OpNo >= MI->getNumOperands()) break;
336 unsigned OpFlags = MI->getOperand(OpNo).getImm();
337 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
340 // We may have a location metadata attached to the end of the
341 // instruction, and at no point should see metadata at any
342 // other point while processing. It's an error if so.
343 if (OpNo >= MI->getNumOperands() ||
344 MI->getOperand(OpNo).isMetadata()) {
347 unsigned OpFlags = MI->getOperand(OpNo).getImm();
348 ++OpNo; // Skip over the ID number.
350 if (Modifier[0] == 'l') // labels are target independent
351 // FIXME: What if the operand isn't an MBB, report error?
352 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
354 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
355 if (InlineAsm::isMemKind(OpFlags)) {
356 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
357 Modifier[0] ? Modifier : 0,
360 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
361 Modifier[0] ? Modifier : 0, OS);
367 raw_string_ostream Msg(msg);
368 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
369 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
376 // Switch to the AsmPrinter variant.
377 if (AsmPrinterVariant != InlineAsmVariant) {
378 if (AsmPrinterVariant == 0)
379 OS << "\n\t.att_syntax";
381 OS << "\n\t.intel_syntax";
384 OS << '\n' << (char)0; // null terminate string.
385 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
387 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
388 // enabled, so we use EmitRawText.
389 if (OutStreamer.hasRawTextSupport())
390 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
391 MAI->getInlineAsmEnd());
395 /// PrintSpecial - Print information related to the specified machine instr
396 /// that is independent of the operand, and may be independent of the instr
397 /// itself. This can be useful for portably encoding the comment character
398 /// or other bits of target-specific knowledge into the asmstrings. The
399 /// syntax used is ${:comment}. Targets can override this to add support
400 /// for their own strange codes.
401 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
402 const char *Code) const {
403 if (!strcmp(Code, "private")) {
404 OS << MAI->getPrivateGlobalPrefix();
405 } else if (!strcmp(Code, "comment")) {
406 OS << MAI->getCommentString();
407 } else if (!strcmp(Code, "uid")) {
408 // Comparing the address of MI isn't sufficient, because machineinstrs may
409 // be allocated to the same address across functions.
411 // If this is a new LastFn instruction, bump the counter.
412 if (LastMI != MI || LastFn != getFunctionNumber()) {
415 LastFn = getFunctionNumber();
420 raw_string_ostream Msg(msg);
421 Msg << "Unknown special formatter '" << Code
422 << "' for machine instr: " << *MI;
423 report_fatal_error(Msg.str());
427 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
428 /// instruction, using the specified assembler variant. Targets should
429 /// override this to format as appropriate.
430 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
431 unsigned AsmVariant, const char *ExtraCode,
433 // Does this asm operand have a single letter operand modifier?
434 if (ExtraCode && ExtraCode[0]) {
435 if (ExtraCode[1] != 0) return true; // Unknown modifier.
437 const MachineOperand &MO = MI->getOperand(OpNo);
438 switch (ExtraCode[0]) {
440 return true; // Unknown modifier.
441 case 'c': // Substitute immediate value without immediate syntax
442 if (MO.getType() != MachineOperand::MO_Immediate)
446 case 'n': // Negate the immediate constant.
447 if (MO.getType() != MachineOperand::MO_Immediate)
456 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
458 const char *ExtraCode, raw_ostream &O) {
459 // Target doesn't support this yet!