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