AsmPrinterInlineAsm.cpp revision 24f5fddbdff3d54d822555ae792a7f3bb22e342f
1//===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the inline assembler pieces of the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
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"
36using namespace llvm;
37
38namespace {
39  struct SrcMgrDiagInfo {
40    const MDNode *LocInfo;
41    LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
42    void *DiagContext;
43  };
44}
45
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
48/// struct above.
49static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
50  SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
51  assert(DiagInfo && "Diagnostic context not passed down?");
52
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())
59      ErrorLine = 0;
60
61    if (LocInfo->getNumOperands() != 0)
62      if (const ConstantInt *CI =
63          dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
64        LocCookie = CI->getZExtValue();
65  }
66
67  DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
68}
69
70/// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
71void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
72                               InlineAsm::AsmDialect Dialect) const {
73  assert(!Str.empty() && "Can't emit empty inline asm block");
74
75  // Remember if the buffer is nul terminated or not so we can avoid a copy.
76  bool isNullTerminated = Str.back() == 0;
77  if (isNullTerminated)
78    Str = Str.substr(0, Str.size()-1);
79
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);
85    return;
86  }
87
88  SourceMgr SrcMgr;
89  SrcMgrDiagInfo DiagInfo;
90
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;
102  }
103
104  MemoryBuffer *Buffer;
105  if (isNullTerminated)
106    Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
107  else
108    Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
109
110  // Tell SrcMgr about this buffer, it takes ownership of the buffer.
111  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
112
113  OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
114                                                  OutContext, OutStreamer,
115                                                  *MAI));
116
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(),
123                                             TM.getTargetCPU(),
124                                             TM.getTargetFeatureString()));
125  OwningPtr<MCTargetAsmParser>
126    TAP(TM.getTarget().createMCAsmParser(*STI, *Parser));
127  if (!TAP)
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());
132
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");
138}
139
140
141/// EmitInlineAsm - This method formats and emits the specified machine
142/// instruction that is an inline asm.
143void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
144  assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
145
146  unsigned NumOperands = MI->getNumOperands();
147
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();
151       ++NumDefs)
152    assert(NumDefs != NumOperands-2 && "No asm string?");
153
154  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
155
156  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
157  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
158
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;
164
165    OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
166                            MAI->getInlineAsmStart());
167    OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
168                            MAI->getInlineAsmEnd());
169    return;
170  }
171
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());
177
178  // Get the !srcloc metadata node if we have it, and decode the loc cookie from
179  // it.
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();
188        break;
189      }
190    }
191  }
192
193  // Emit the inline asm to a temporary string so we can emit it through
194  // EmitInlineAsm.
195  SmallString<256> StringData;
196  raw_svector_ostream OS(StringData);
197
198  OS << '\t';
199
200  // The variant of the current asmprinter.
201  int AsmPrinterVariant = MAI->getAssemblerDialect();
202  int InlineAsmVariant = MI->getInlineAsmDialect();
203
204  // Switch to the inline assembly variant.
205  if (AsmPrinterVariant != InlineAsmVariant) {
206    if (InlineAsmVariant == 0)
207      OS << ".att_syntax\n\t";
208    else
209      OS << ".intel_syntax\n\t";
210  }
211
212  int CurVariant = -1;            // The number of the {.|.|.} region we are in.
213  const char *LastEmitted = AsmStr; // One past the last character emitted.
214
215  while (*LastEmitted) {
216    switch (*LastEmitted) {
217    default: {
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')
222        ++LiteralEnd;
223      if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
224        OS.write(LastEmitted, LiteralEnd-LastEmitted);
225      LastEmitted = LiteralEnd;
226      break;
227    }
228    case '\n':
229      ++LastEmitted;   // Consume newline character.
230      OS << '\n';      // Indent code with newline.
231      break;
232    case '$': {
233      ++LastEmitted;   // Consume '$' character.
234      bool Done = true;
235
236      // Handle escapes.
237      switch (*LastEmitted) {
238      default: Done = false; break;
239      case '$':     // $$ -> $
240        if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
241          OS << '$';
242        ++LastEmitted;  // Consume second '$' character.
243        break;
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.
250        break;
251      case '|':
252        ++LastEmitted;  // consume '|' character.
253        if (CurVariant == -1)
254          OS << '|';       // this is gcc's behavior for | outside a variant
255        else
256          ++CurVariant;   // We're in the next variant.
257        break;
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
262        else
263          CurVariant = -1;
264        break;
265      }
266      if (Done) break;
267
268      bool HasCurlyBraces = false;
269      if (*LastEmitted == '{') {     // ${variable}
270        ++LastEmitted;               // Consume '{' character.
271        HasCurlyBraces = true;
272      }
273
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
276      // PrintSpecial.
277      if (HasCurlyBraces && *LastEmitted == ':') {
278        ++LastEmitted;
279        const char *StrStart = LastEmitted;
280        const char *StrEnd = strchr(StrStart, '}');
281        if (StrEnd == 0)
282          report_fatal_error("Unterminated ${:foo} operand in inline asm"
283                             " string: '" + Twine(AsmStr) + "'");
284
285        std::string Val(StrStart, StrEnd);
286        PrintSpecial(MI, OS, Val.c_str());
287        LastEmitted = StrEnd+1;
288        break;
289      }
290
291      const char *IDStart = LastEmitted;
292      const char *IDEnd = IDStart;
293      while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
294
295      unsigned Val;
296      if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
297        report_fatal_error("Bad $ operand number in inline asm string: '" +
298                           Twine(AsmStr) + "'");
299      LastEmitted = IDEnd;
300
301      char Modifier[2] = { 0, 0 };
302
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) + "'");
311
312          Modifier[0] = *LastEmitted;
313          ++LastEmitted;    // Consume modifier character.
314        }
315
316        if (*LastEmitted != '}')
317          report_fatal_error("Bad ${} expression in inline asm string: '" +
318                             Twine(AsmStr) + "'");
319        ++LastEmitted;    // Consume '}' character.
320      }
321
322      if (Val >= NumOperands-1)
323        report_fatal_error("Invalid $ operand number in inline asm string: '" +
324                           Twine(AsmStr) + "'");
325
326      // Okay, we finally have a value number.  Ask the target to print this
327      // operand!
328      if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
329        unsigned OpNo = InlineAsm::MIOp_FirstOperand;
330
331        bool Error = false;
332
333        // Scan to find the machine operand number for the operand.
334        for (; Val; --Val) {
335          if (OpNo >= MI->getNumOperands()) break;
336          unsigned OpFlags = MI->getOperand(OpNo).getImm();
337          OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
338        }
339
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()) {
345          Error = true;
346        } else {
347          unsigned OpFlags = MI->getOperand(OpNo).getImm();
348          ++OpNo;  // Skip over the ID number.
349
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();
353          else {
354            AsmPrinter *AP = const_cast<AsmPrinter*>(this);
355            if (InlineAsm::isMemKind(OpFlags)) {
356              Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
357                                                Modifier[0] ? Modifier : 0,
358                                                OS);
359            } else {
360              Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
361                                          Modifier[0] ? Modifier : 0, OS);
362            }
363          }
364        }
365        if (Error) {
366          std::string msg;
367          raw_string_ostream Msg(msg);
368          Msg << "invalid operand in inline asm: '" << AsmStr << "'";
369          MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
370        }
371      }
372      break;
373    }
374    }
375  }
376  // Switch to the AsmPrinter variant.
377  if (AsmPrinterVariant != InlineAsmVariant) {
378    if (AsmPrinterVariant == 0)
379      OS << "\n\t.att_syntax";
380    else
381      OS << "\n\t.intel_syntax";
382  }
383
384  OS << '\n' << (char)0;  // null terminate string.
385  EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
386
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());
392}
393
394
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.
401void 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.
410
411    // If this is a new LastFn instruction, bump the counter.
412    if (LastMI != MI || LastFn != getFunctionNumber()) {
413      ++Counter;
414      LastMI = MI;
415      LastFn = getFunctionNumber();
416    }
417    OS << Counter;
418  } else {
419    std::string msg;
420    raw_string_ostream Msg(msg);
421    Msg << "Unknown special formatter '" << Code
422         << "' for machine instr: " << *MI;
423    report_fatal_error(Msg.str());
424  }
425}
426
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.
430bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
431                                 unsigned AsmVariant, const char *ExtraCode,
432                                 raw_ostream &O) {
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.
436
437    const MachineOperand &MO = MI->getOperand(OpNo);
438    switch (ExtraCode[0]) {
439    default:
440      return true;  // Unknown modifier.
441    case 'c': // Substitute immediate value without immediate syntax
442      if (MO.getType() != MachineOperand::MO_Immediate)
443        return true;
444      O << MO.getImm();
445      return false;
446    case 'n':  // Negate the immediate constant.
447      if (MO.getType() != MachineOperand::MO_Immediate)
448        return true;
449      O << -MO.getImm();
450      return false;
451    }
452  }
453  return true;
454}
455
456bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
457                                       unsigned AsmVariant,
458                                       const char *ExtraCode, raw_ostream &O) {
459  // Target doesn't support this yet!
460  return true;
461}
462
463