AsmPrinterInlineAsm.cpp revision ebdeeab812beec0385b445f3d4c41a114e0d972f
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/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"
35using namespace llvm;
36
37namespace {
38  struct SrcMgrDiagInfo {
39    const MDNode *LocInfo;
40    LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
41    void *DiagContext;
42  };
43}
44
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
47/// struct above.
48static void SrcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
49  SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
50  assert(DiagInfo && "Diagnostic context not passed down?");
51
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())
58      ErrorLine = 0;
59
60    if (LocInfo->getNumOperands() != 0)
61      if (const ConstantInt *CI =
62          dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
63        LocCookie = CI->getZExtValue();
64  }
65
66  DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
67}
68
69/// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
70void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode) const {
71  assert(!Str.empty() && "Can't emit empty inline asm block");
72
73  // Remember if the buffer is nul terminated or not so we can avoid a copy.
74  bool isNullTerminated = Str.back() == 0;
75  if (isNullTerminated)
76    Str = Str.substr(0, Str.size()-1);
77
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);
83    return;
84  }
85
86  SourceMgr SrcMgr;
87  SrcMgrDiagInfo DiagInfo;
88
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;
100  }
101
102  MemoryBuffer *Buffer;
103  if (isNullTerminated)
104    Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
105  else
106    Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
107
108  // Tell SrcMgr about this buffer, it takes ownership of the buffer.
109  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
110
111  OwningPtr<MCAsmParser> Parser(createMCAsmParser(TM.getTarget(), SrcMgr,
112                                                  OutContext, OutStreamer,
113                                                  *MAI));
114
115  OwningPtr<TargetAsmParser>
116    TAP(TM.getTarget().createAsmParser(TM.getTargetTriple(),
117                                       TM.getTargetCPU(),
118                                       TM.getTargetFeatureString(),
119                                       *Parser));
120  if (!TAP)
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());
124
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");
130}
131
132
133/// EmitInlineAsm - This method formats and emits the specified machine
134/// instruction that is an inline asm.
135void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
136  assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
137
138  unsigned NumOperands = MI->getNumOperands();
139
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();
143       ++NumDefs)
144    assert(NumDefs != NumOperands-2 && "No asm string?");
145
146  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
147
148  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
149  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
150
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;
156
157    OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
158                            MAI->getInlineAsmStart());
159    OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
160                            MAI->getInlineAsmEnd());
161    return;
162  }
163
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());
169
170  // Get the !srcloc metadata node if we have it, and decode the loc cookie from
171  // it.
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();
180        break;
181      }
182    }
183  }
184
185  // Emit the inline asm to a temporary string so we can emit it through
186  // EmitInlineAsm.
187  SmallString<256> StringData;
188  raw_svector_ostream OS(StringData);
189
190  OS << '\t';
191
192  // The variant of the current asmprinter.
193  int AsmPrinterVariant = MAI->getAssemblerDialect();
194
195  int CurVariant = -1;            // The number of the {.|.|.} region we are in.
196  const char *LastEmitted = AsmStr; // One past the last character emitted.
197
198  while (*LastEmitted) {
199    switch (*LastEmitted) {
200    default: {
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')
205        ++LiteralEnd;
206      if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
207        OS.write(LastEmitted, LiteralEnd-LastEmitted);
208      LastEmitted = LiteralEnd;
209      break;
210    }
211    case '\n':
212      ++LastEmitted;   // Consume newline character.
213      OS << '\n';      // Indent code with newline.
214      break;
215    case '$': {
216      ++LastEmitted;   // Consume '$' character.
217      bool Done = true;
218
219      // Handle escapes.
220      switch (*LastEmitted) {
221      default: Done = false; break;
222      case '$':     // $$ -> $
223        if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
224          OS << '$';
225        ++LastEmitted;  // Consume second '$' character.
226        break;
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.
233        break;
234      case '|':
235        ++LastEmitted;  // consume '|' character.
236        if (CurVariant == -1)
237          OS << '|';       // this is gcc's behavior for | outside a variant
238        else
239          ++CurVariant;   // We're in the next variant.
240        break;
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
245        else
246          CurVariant = -1;
247        break;
248      }
249      if (Done) break;
250
251      bool HasCurlyBraces = false;
252      if (*LastEmitted == '{') {     // ${variable}
253        ++LastEmitted;               // Consume '{' character.
254        HasCurlyBraces = true;
255      }
256
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
259      // PrintSpecial.
260      if (HasCurlyBraces && *LastEmitted == ':') {
261        ++LastEmitted;
262        const char *StrStart = LastEmitted;
263        const char *StrEnd = strchr(StrStart, '}');
264        if (StrEnd == 0)
265          report_fatal_error("Unterminated ${:foo} operand in inline asm"
266                             " string: '" + Twine(AsmStr) + "'");
267
268        std::string Val(StrStart, StrEnd);
269        PrintSpecial(MI, OS, Val.c_str());
270        LastEmitted = StrEnd+1;
271        break;
272      }
273
274      const char *IDStart = LastEmitted;
275      const char *IDEnd = IDStart;
276      while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
277
278      unsigned Val;
279      if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
280        report_fatal_error("Bad $ operand number in inline asm string: '" +
281                           Twine(AsmStr) + "'");
282      LastEmitted = IDEnd;
283
284      char Modifier[2] = { 0, 0 };
285
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) + "'");
294
295          Modifier[0] = *LastEmitted;
296          ++LastEmitted;    // Consume modifier character.
297        }
298
299        if (*LastEmitted != '}')
300          report_fatal_error("Bad ${} expression in inline asm string: '" +
301                             Twine(AsmStr) + "'");
302        ++LastEmitted;    // Consume '}' character.
303      }
304
305      if (Val >= NumOperands-1)
306        report_fatal_error("Invalid $ operand number in inline asm string: '" +
307                           Twine(AsmStr) + "'");
308
309      // Okay, we finally have a value number.  Ask the target to print this
310      // operand!
311      if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
312        unsigned OpNo = InlineAsm::MIOp_FirstOperand;
313
314        bool Error = false;
315
316        // Scan to find the machine operand number for the operand.
317        for (; Val; --Val) {
318          if (OpNo >= MI->getNumOperands()) break;
319          unsigned OpFlags = MI->getOperand(OpNo).getImm();
320          OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
321        }
322
323        if (OpNo >= MI->getNumOperands()) {
324          Error = true;
325        } else {
326          unsigned OpFlags = MI->getOperand(OpNo).getImm();
327          ++OpNo;  // Skip over the ID number.
328
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();
332          else {
333            AsmPrinter *AP = const_cast<AsmPrinter*>(this);
334            if (InlineAsm::isMemKind(OpFlags)) {
335              Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
336                                                Modifier[0] ? Modifier : 0,
337                                                OS);
338            } else {
339              Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
340                                          Modifier[0] ? Modifier : 0, OS);
341            }
342          }
343        }
344        if (Error) {
345          std::string msg;
346          raw_string_ostream Msg(msg);
347          Msg << "invalid operand in inline asm: '" << AsmStr << "'";
348          MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
349        }
350      }
351      break;
352    }
353    }
354  }
355  OS << '\n' << (char)0;  // null terminate string.
356  EmitInlineAsm(OS.str(), LocMD);
357
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());
363}
364
365
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.
372void 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.
381
382    // If this is a new LastFn instruction, bump the counter.
383    if (LastMI != MI || LastFn != getFunctionNumber()) {
384      ++Counter;
385      LastMI = MI;
386      LastFn = getFunctionNumber();
387    }
388    OS << Counter;
389  } else {
390    std::string msg;
391    raw_string_ostream Msg(msg);
392    Msg << "Unknown special formatter '" << Code
393         << "' for machine instr: " << *MI;
394    report_fatal_error(Msg.str());
395  }
396}
397
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.
401bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
402                                 unsigned AsmVariant, const char *ExtraCode,
403                                 raw_ostream &O) {
404  // Target doesn't support this yet!
405  return true;
406}
407
408bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
409                                       unsigned AsmVariant,
410                                       const char *ExtraCode, raw_ostream &O) {
411  // Target doesn't support this yet!
412  return true;
413}
414
415