Move emitInlineAsmEnd to the AsmPrinter interface.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinterInlineAsm.cpp
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/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"
38 using namespace llvm;
39
40 namespace {
41   struct SrcMgrDiagInfo {
42     const MDNode *LocInfo;
43     LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
44     void *DiagContext;
45   };
46 }
47
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
50 /// struct above.
51 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
52   SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
53   assert(DiagInfo && "Diagnostic context not passed down?");
54
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())
61       ErrorLine = 0;
62
63     if (LocInfo->getNumOperands() != 0)
64       if (const ConstantInt *CI =
65           dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
66         LocCookie = CI->getZExtValue();
67   }
68
69   DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
70 }
71
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");
76
77   // Remember if the buffer is nul terminated or not so we can avoid a copy.
78   bool isNullTerminated = Str.back() == 0;
79   if (isNullTerminated)
80     Str = Str.substr(0, Str.size()-1);
81
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);
88     return;
89   }
90
91   SourceMgr SrcMgr;
92   SrcMgrDiagInfo DiagInfo;
93
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;
105   }
106
107   MemoryBuffer *Buffer;
108   if (isNullTerminated)
109     Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
110   else
111     Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
112
113   // Tell SrcMgr about this buffer, it takes ownership of the buffer.
114   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
115
116   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
117                                                   OutContext, OutStreamer,
118                                                   *MAI));
119
120   // Reuse the existing Subtarget, because the AsmParser may need to
121   // modify it.  For example, when switching between ARM and
122   // Thumb mode.
123   MCSubtargetInfo* STI =
124     const_cast<MCSubtargetInfo*>(&TM.getSubtarget<MCSubtargetInfo>());
125
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;
129
130   OwningPtr<MCTargetAsmParser>
131     TAP(TM.getTarget().createMCAsmParser(*STI, *Parser, *MII));
132   if (!TAP)
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());
137
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");
144 }
145
146 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
147                                MachineModuleInfo *MMI, int InlineAsmVariant,
148                                AsmPrinter *AP, unsigned LocCookie,
149                                raw_ostream &OS) {
150   // Switch to the inline assembly variant.
151   OS << "\t.intel_syntax\n\t";
152
153   const char *LastEmitted = AsmStr; // One past the last character emitted.
154   unsigned NumOperands = MI->getNumOperands();
155
156   while (*LastEmitted) {
157     switch (*LastEmitted) {
158     default: {
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')
163         ++LiteralEnd;
164
165       OS.write(LastEmitted, LiteralEnd-LastEmitted);
166       LastEmitted = LiteralEnd;
167       break;
168     }
169     case '\n':
170       ++LastEmitted;   // Consume newline character.
171       OS << '\n';      // Indent code with newline.
172       break;
173     case '$': {
174       ++LastEmitted;   // Consume '$' character.
175       bool Done = true;
176
177       // Handle escapes.
178       switch (*LastEmitted) {
179       default: Done = false; break;
180       case '$':
181         ++LastEmitted;  // Consume second '$' character.
182         break;
183       }
184       if (Done) break;
185
186       const char *IDStart = LastEmitted;
187       const char *IDEnd = IDStart;
188       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
189
190       unsigned Val;
191       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
192         report_fatal_error("Bad $ operand number in inline asm string: '" +
193                            Twine(AsmStr) + "'");
194       LastEmitted = IDEnd;
195
196       if (Val >= NumOperands-1)
197         report_fatal_error("Invalid $ operand number in inline asm string: '" +
198                            Twine(AsmStr) + "'");
199
200       // Okay, we finally have a value number.  Ask the target to print this
201       // operand!
202       unsigned OpNo = InlineAsm::MIOp_FirstOperand;
203
204       bool Error = false;
205
206       // Scan to find the machine operand number for the operand.
207       for (; Val; --Val) {
208         if (OpNo >= MI->getNumOperands()) break;
209         unsigned OpFlags = MI->getOperand(OpNo).getImm();
210         OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
211       }
212
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()) {
218         Error = true;
219       } else {
220         unsigned OpFlags = MI->getOperand(OpNo).getImm();
221         ++OpNo;  // Skip over the ID number.
222
223         if (InlineAsm::isMemKind(OpFlags)) {
224           Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
225                                             /*Modifier*/ 0, OS);
226         } else {
227           Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
228                                       /*Modifier*/ 0, OS);
229         }
230       }
231       if (Error) {
232         std::string msg;
233         raw_string_ostream Msg(msg);
234         Msg << "invalid operand in inline asm: '" << AsmStr << "'";
235         MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
236       }
237       break;
238     }
239     }
240   }
241   OS << "\n\t.att_syntax\n" << (char)0;  // null terminate string.
242 }
243
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();
251
252   OS << '\t';
253
254   while (*LastEmitted) {
255     switch (*LastEmitted) {
256     default: {
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')
261         ++LiteralEnd;
262       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
263         OS.write(LastEmitted, LiteralEnd-LastEmitted);
264       LastEmitted = LiteralEnd;
265       break;
266     }
267     case '\n':
268       ++LastEmitted;   // Consume newline character.
269       OS << '\n';      // Indent code with newline.
270       break;
271     case '$': {
272       ++LastEmitted;   // Consume '$' character.
273       bool Done = true;
274
275       // Handle escapes.
276       switch (*LastEmitted) {
277       default: Done = false; break;
278       case '$':     // $$ -> $
279         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
280           OS << '$';
281         ++LastEmitted;  // Consume second '$' character.
282         break;
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.
289         break;
290       case '|':
291         ++LastEmitted;  // consume '|' character.
292         if (CurVariant == -1)
293           OS << '|';       // this is gcc's behavior for | outside a variant
294         else
295           ++CurVariant;   // We're in the next variant.
296         break;
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
301         else
302           CurVariant = -1;
303         break;
304       }
305       if (Done) break;
306
307       bool HasCurlyBraces = false;
308       if (*LastEmitted == '{') {     // ${variable}
309         ++LastEmitted;               // Consume '{' character.
310         HasCurlyBraces = true;
311       }
312
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
315       // PrintSpecial.
316       if (HasCurlyBraces && *LastEmitted == ':') {
317         ++LastEmitted;
318         const char *StrStart = LastEmitted;
319         const char *StrEnd = strchr(StrStart, '}');
320         if (StrEnd == 0)
321           report_fatal_error("Unterminated ${:foo} operand in inline asm"
322                              " string: '" + Twine(AsmStr) + "'");
323
324         std::string Val(StrStart, StrEnd);
325         AP->PrintSpecial(MI, OS, Val.c_str());
326         LastEmitted = StrEnd+1;
327         break;
328       }
329
330       const char *IDStart = LastEmitted;
331       const char *IDEnd = IDStart;
332       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
333
334       unsigned Val;
335       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
336         report_fatal_error("Bad $ operand number in inline asm string: '" +
337                            Twine(AsmStr) + "'");
338       LastEmitted = IDEnd;
339
340       char Modifier[2] = { 0, 0 };
341
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) + "'");
350
351           Modifier[0] = *LastEmitted;
352           ++LastEmitted;    // Consume modifier character.
353         }
354
355         if (*LastEmitted != '}')
356           report_fatal_error("Bad ${} expression in inline asm string: '" +
357                              Twine(AsmStr) + "'");
358         ++LastEmitted;    // Consume '}' character.
359       }
360
361       if (Val >= NumOperands-1)
362         report_fatal_error("Invalid $ operand number in inline asm string: '" +
363                            Twine(AsmStr) + "'");
364
365       // Okay, we finally have a value number.  Ask the target to print this
366       // operand!
367       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
368         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
369
370         bool Error = false;
371
372         // Scan to find the machine operand number for the operand.
373         for (; Val; --Val) {
374           if (OpNo >= MI->getNumOperands()) break;
375           unsigned OpFlags = MI->getOperand(OpNo).getImm();
376           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
377         }
378
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()) {
384           Error = true;
385         } else {
386           unsigned OpFlags = MI->getOperand(OpNo).getImm();
387           ++OpNo;  // Skip over the ID number.
388
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();
392           else {
393             if (InlineAsm::isMemKind(OpFlags)) {
394               Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
395                                                 Modifier[0] ? Modifier : 0,
396                                                 OS);
397             } else {
398               Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
399                                           Modifier[0] ? Modifier : 0, OS);
400             }
401           }
402         }
403         if (Error) {
404           std::string msg;
405           raw_string_ostream Msg(msg);
406           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
407           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
408         }
409       }
410       break;
411     }
412     }
413   }
414   OS << '\n' << (char)0;  // null terminate string.
415 }
416
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");
421
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();
425        ++NumDefs)
426     assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
427
428   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
429
430   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
431   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
432
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());
438     return;
439   }
440
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());
444
445   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
446   // it.
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();
455         break;
456       }
457     }
458   }
459
460   // Emit the inline asm to a temporary string so we can emit it through
461   // EmitInlineAsm.
462   SmallString<256> StringData;
463   raw_svector_ostream OS(StringData);
464
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,
471                         AP, LocCookie, OS);
472   else
473     EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
474
475   EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
476
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());
480 }
481
482
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.
499
500     // If this is a new LastFn instruction, bump the counter.
501     if (LastMI != MI || LastFn != getFunctionNumber()) {
502       ++Counter;
503       LastMI = MI;
504       LastFn = getFunctionNumber();
505     }
506     OS << Counter;
507   } else {
508     std::string msg;
509     raw_string_ostream Msg(msg);
510     Msg << "Unknown special formatter '" << Code
511          << "' for machine instr: " << *MI;
512     report_fatal_error(Msg.str());
513   }
514 }
515
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,
521                                  raw_ostream &O) {
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.
525
526     const MachineOperand &MO = MI->getOperand(OpNo);
527     switch (ExtraCode[0]) {
528     default:
529       return true;  // Unknown modifier.
530     case 'c': // Substitute immediate value without immediate syntax
531       if (MO.getType() != MachineOperand::MO_Immediate)
532         return true;
533       O << MO.getImm();
534       return false;
535     case 'n':  // Negate the immediate constant.
536       if (MO.getType() != MachineOperand::MO_Immediate)
537         return true;
538       O << -MO.getImm();
539       return false;
540     }
541   }
542   return true;
543 }
544
545 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
546                                        unsigned AsmVariant,
547                                        const char *ExtraCode, raw_ostream &O) {
548   // Target doesn't support this yet!
549   return true;
550 }
551
552 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
553                                   MCSubtargetInfo *EndInfo) const {}