Reapply r201180 with an additional error path.
[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   // Initialize the parser with a fresh subtarget info. It is better to use a
121   // new STI here because the parser may modify it and we do not want those
122   // modifications to persist after parsing the inlineasm. The modifications
123   // made by the parser will be seen by the code emitters because it passes
124   // the current STI down to the EncodeInstruction() method.
125   OwningPtr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
126       TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
127
128   // Preserve a copy of the original STI because the parser may modify it.  For
129   // example, when switching between arm and thumb mode. If the target needs to
130   // emit code to return to the original state it can do so in emitInlineAsmEnd().
131   MCSubtargetInfo STIOrig = *STI;
132
133   OwningPtr<MCTargetAsmParser>
134     TAP(TM.getTarget().createMCAsmParser(*STI, *Parser, *MII));
135   if (!TAP)
136     report_fatal_error("Inline asm not supported by this streamer because"
137                        " we don't have an asm parser for this target\n");
138   Parser->setAssemblerDialect(Dialect);
139   Parser->setTargetParser(*TAP.get());
140
141   // Don't implicitly switch to the text section before the asm.
142   int Res = Parser->Run(/*NoInitialTextSection*/ true,
143                         /*NoFinalize*/ true);
144   emitInlineAsmEnd(STIOrig, STI.get());
145   if (Res && !HasDiagHandler)
146     report_fatal_error("Error parsing inline asm\n");
147 }
148
149 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
150                                MachineModuleInfo *MMI, int InlineAsmVariant,
151                                AsmPrinter *AP, unsigned LocCookie,
152                                raw_ostream &OS) {
153   // Switch to the inline assembly variant.
154   OS << "\t.intel_syntax\n\t";
155
156   const char *LastEmitted = AsmStr; // One past the last character emitted.
157   unsigned NumOperands = MI->getNumOperands();
158
159   while (*LastEmitted) {
160     switch (*LastEmitted) {
161     default: {
162       // Not a special case, emit the string section literally.
163       const char *LiteralEnd = LastEmitted+1;
164       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
165              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
166         ++LiteralEnd;
167
168       OS.write(LastEmitted, LiteralEnd-LastEmitted);
169       LastEmitted = LiteralEnd;
170       break;
171     }
172     case '\n':
173       ++LastEmitted;   // Consume newline character.
174       OS << '\n';      // Indent code with newline.
175       break;
176     case '$': {
177       ++LastEmitted;   // Consume '$' character.
178       bool Done = true;
179
180       // Handle escapes.
181       switch (*LastEmitted) {
182       default: Done = false; break;
183       case '$':
184         ++LastEmitted;  // Consume second '$' character.
185         break;
186       }
187       if (Done) break;
188
189       const char *IDStart = LastEmitted;
190       const char *IDEnd = IDStart;
191       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
192
193       unsigned Val;
194       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
195         report_fatal_error("Bad $ operand number in inline asm string: '" +
196                            Twine(AsmStr) + "'");
197       LastEmitted = IDEnd;
198
199       if (Val >= NumOperands-1)
200         report_fatal_error("Invalid $ operand number in inline asm string: '" +
201                            Twine(AsmStr) + "'");
202
203       // Okay, we finally have a value number.  Ask the target to print this
204       // operand!
205       unsigned OpNo = InlineAsm::MIOp_FirstOperand;
206
207       bool Error = false;
208
209       // Scan to find the machine operand number for the operand.
210       for (; Val; --Val) {
211         if (OpNo >= MI->getNumOperands()) break;
212         unsigned OpFlags = MI->getOperand(OpNo).getImm();
213         OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
214       }
215
216       // We may have a location metadata attached to the end of the
217       // instruction, and at no point should see metadata at any
218       // other point while processing. It's an error if so.
219       if (OpNo >= MI->getNumOperands() ||
220           MI->getOperand(OpNo).isMetadata()) {
221         Error = true;
222       } else {
223         unsigned OpFlags = MI->getOperand(OpNo).getImm();
224         ++OpNo;  // Skip over the ID number.
225
226         if (InlineAsm::isMemKind(OpFlags)) {
227           Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
228                                             /*Modifier*/ 0, OS);
229         } else {
230           Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
231                                       /*Modifier*/ 0, OS);
232         }
233       }
234       if (Error) {
235         std::string msg;
236         raw_string_ostream Msg(msg);
237         Msg << "invalid operand in inline asm: '" << AsmStr << "'";
238         MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
239       }
240       break;
241     }
242     }
243   }
244   OS << "\n\t.att_syntax\n" << (char)0;  // null terminate string.
245 }
246
247 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
248                                 MachineModuleInfo *MMI, int InlineAsmVariant,
249                                 int AsmPrinterVariant, AsmPrinter *AP,
250                                 unsigned LocCookie, raw_ostream &OS) {
251   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
252   const char *LastEmitted = AsmStr; // One past the last character emitted.
253   unsigned NumOperands = MI->getNumOperands();
254
255   OS << '\t';
256
257   while (*LastEmitted) {
258     switch (*LastEmitted) {
259     default: {
260       // Not a special case, emit the string section literally.
261       const char *LiteralEnd = LastEmitted+1;
262       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
263              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
264         ++LiteralEnd;
265       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
266         OS.write(LastEmitted, LiteralEnd-LastEmitted);
267       LastEmitted = LiteralEnd;
268       break;
269     }
270     case '\n':
271       ++LastEmitted;   // Consume newline character.
272       OS << '\n';      // Indent code with newline.
273       break;
274     case '$': {
275       ++LastEmitted;   // Consume '$' character.
276       bool Done = true;
277
278       // Handle escapes.
279       switch (*LastEmitted) {
280       default: Done = false; break;
281       case '$':     // $$ -> $
282         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
283           OS << '$';
284         ++LastEmitted;  // Consume second '$' character.
285         break;
286       case '(':             // $( -> same as GCC's { character.
287         ++LastEmitted;      // Consume '(' character.
288         if (CurVariant != -1)
289           report_fatal_error("Nested variants found in inline asm string: '" +
290                              Twine(AsmStr) + "'");
291         CurVariant = 0;     // We're in the first variant now.
292         break;
293       case '|':
294         ++LastEmitted;  // consume '|' character.
295         if (CurVariant == -1)
296           OS << '|';       // this is gcc's behavior for | outside a variant
297         else
298           ++CurVariant;   // We're in the next variant.
299         break;
300       case ')':         // $) -> same as GCC's } char.
301         ++LastEmitted;  // consume ')' character.
302         if (CurVariant == -1)
303           OS << '}';     // this is gcc's behavior for } outside a variant
304         else
305           CurVariant = -1;
306         break;
307       }
308       if (Done) break;
309
310       bool HasCurlyBraces = false;
311       if (*LastEmitted == '{') {     // ${variable}
312         ++LastEmitted;               // Consume '{' character.
313         HasCurlyBraces = true;
314       }
315
316       // If we have ${:foo}, then this is not a real operand reference, it is a
317       // "magic" string reference, just like in .td files.  Arrange to call
318       // PrintSpecial.
319       if (HasCurlyBraces && *LastEmitted == ':') {
320         ++LastEmitted;
321         const char *StrStart = LastEmitted;
322         const char *StrEnd = strchr(StrStart, '}');
323         if (StrEnd == 0)
324           report_fatal_error("Unterminated ${:foo} operand in inline asm"
325                              " string: '" + Twine(AsmStr) + "'");
326
327         std::string Val(StrStart, StrEnd);
328         AP->PrintSpecial(MI, OS, Val.c_str());
329         LastEmitted = StrEnd+1;
330         break;
331       }
332
333       const char *IDStart = LastEmitted;
334       const char *IDEnd = IDStart;
335       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
336
337       unsigned Val;
338       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
339         report_fatal_error("Bad $ operand number in inline asm string: '" +
340                            Twine(AsmStr) + "'");
341       LastEmitted = IDEnd;
342
343       char Modifier[2] = { 0, 0 };
344
345       if (HasCurlyBraces) {
346         // If we have curly braces, check for a modifier character.  This
347         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
348         if (*LastEmitted == ':') {
349           ++LastEmitted;    // Consume ':' character.
350           if (*LastEmitted == 0)
351             report_fatal_error("Bad ${:} expression in inline asm string: '" +
352                                Twine(AsmStr) + "'");
353
354           Modifier[0] = *LastEmitted;
355           ++LastEmitted;    // Consume modifier character.
356         }
357
358         if (*LastEmitted != '}')
359           report_fatal_error("Bad ${} expression in inline asm string: '" +
360                              Twine(AsmStr) + "'");
361         ++LastEmitted;    // Consume '}' character.
362       }
363
364       if (Val >= NumOperands-1)
365         report_fatal_error("Invalid $ operand number in inline asm string: '" +
366                            Twine(AsmStr) + "'");
367
368       // Okay, we finally have a value number.  Ask the target to print this
369       // operand!
370       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
371         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
372
373         bool Error = false;
374
375         // Scan to find the machine operand number for the operand.
376         for (; Val; --Val) {
377           if (OpNo >= MI->getNumOperands()) break;
378           unsigned OpFlags = MI->getOperand(OpNo).getImm();
379           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
380         }
381
382         // We may have a location metadata attached to the end of the
383         // instruction, and at no point should see metadata at any
384         // other point while processing. It's an error if so.
385         if (OpNo >= MI->getNumOperands() ||
386             MI->getOperand(OpNo).isMetadata()) {
387           Error = true;
388         } else {
389           unsigned OpFlags = MI->getOperand(OpNo).getImm();
390           ++OpNo;  // Skip over the ID number.
391
392           if (Modifier[0] == 'l')  // labels are target independent
393             // FIXME: What if the operand isn't an MBB, report error?
394             OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
395           else {
396             if (InlineAsm::isMemKind(OpFlags)) {
397               Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
398                                                 Modifier[0] ? Modifier : 0,
399                                                 OS);
400             } else {
401               Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
402                                           Modifier[0] ? Modifier : 0, OS);
403             }
404           }
405         }
406         if (Error) {
407           std::string msg;
408           raw_string_ostream Msg(msg);
409           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
410           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
411         }
412       }
413       break;
414     }
415     }
416   }
417   OS << '\n' << (char)0;  // null terminate string.
418 }
419
420 /// EmitInlineAsm - This method formats and emits the specified machine
421 /// instruction that is an inline asm.
422 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
423   assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
424
425   // Count the number of register definitions to find the asm string.
426   unsigned NumDefs = 0;
427   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
428        ++NumDefs)
429     assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
430
431   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
432
433   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
434   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
435
436   // If this asmstr is empty, just print the #APP/#NOAPP markers.
437   // These are useful to see where empty asm's wound up.
438   if (AsmStr[0] == 0) {
439     OutStreamer.emitRawComment(MAI->getInlineAsmStart());
440     OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
441     return;
442   }
443
444   // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
445   // enabled, so we use emitRawComment.
446   OutStreamer.emitRawComment(MAI->getInlineAsmStart());
447
448   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
449   // it.
450   unsigned LocCookie = 0;
451   const MDNode *LocMD = 0;
452   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
453     if (MI->getOperand(i-1).isMetadata() &&
454         (LocMD = MI->getOperand(i-1).getMetadata()) &&
455         LocMD->getNumOperands() != 0) {
456       if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
457         LocCookie = CI->getZExtValue();
458         break;
459       }
460     }
461   }
462
463   // Emit the inline asm to a temporary string so we can emit it through
464   // EmitInlineAsm.
465   SmallString<256> StringData;
466   raw_svector_ostream OS(StringData);
467
468   // The variant of the current asmprinter.
469   int AsmPrinterVariant = MAI->getAssemblerDialect();
470   InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
471   AsmPrinter *AP = const_cast<AsmPrinter*>(this);
472   if (InlineAsmVariant == InlineAsm::AD_ATT)
473     EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
474                         AP, LocCookie, OS);
475   else
476     EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
477
478   EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
479
480   // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
481   // enabled, so we use emitRawComment.
482   OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
483 }
484
485
486 /// PrintSpecial - Print information related to the specified machine instr
487 /// that is independent of the operand, and may be independent of the instr
488 /// itself.  This can be useful for portably encoding the comment character
489 /// or other bits of target-specific knowledge into the asmstrings.  The
490 /// syntax used is ${:comment}.  Targets can override this to add support
491 /// for their own strange codes.
492 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
493                               const char *Code) const {
494   const DataLayout *DL = TM.getDataLayout();
495   if (!strcmp(Code, "private")) {
496     OS << DL->getPrivateGlobalPrefix();
497   } else if (!strcmp(Code, "comment")) {
498     OS << MAI->getCommentString();
499   } else if (!strcmp(Code, "uid")) {
500     // Comparing the address of MI isn't sufficient, because machineinstrs may
501     // be allocated to the same address across functions.
502
503     // If this is a new LastFn instruction, bump the counter.
504     if (LastMI != MI || LastFn != getFunctionNumber()) {
505       ++Counter;
506       LastMI = MI;
507       LastFn = getFunctionNumber();
508     }
509     OS << Counter;
510   } else {
511     std::string msg;
512     raw_string_ostream Msg(msg);
513     Msg << "Unknown special formatter '" << Code
514          << "' for machine instr: " << *MI;
515     report_fatal_error(Msg.str());
516   }
517 }
518
519 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
520 /// instruction, using the specified assembler variant.  Targets should
521 /// override this to format as appropriate.
522 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
523                                  unsigned AsmVariant, const char *ExtraCode,
524                                  raw_ostream &O) {
525   // Does this asm operand have a single letter operand modifier?
526   if (ExtraCode && ExtraCode[0]) {
527     if (ExtraCode[1] != 0) return true; // Unknown modifier.
528
529     const MachineOperand &MO = MI->getOperand(OpNo);
530     switch (ExtraCode[0]) {
531     default:
532       return true;  // Unknown modifier.
533     case 'c': // Substitute immediate value without immediate syntax
534       if (MO.getType() != MachineOperand::MO_Immediate)
535         return true;
536       O << MO.getImm();
537       return false;
538     case 'n':  // Negate the immediate constant.
539       if (MO.getType() != MachineOperand::MO_Immediate)
540         return true;
541       O << -MO.getImm();
542       return false;
543     }
544   }
545   return true;
546 }
547
548 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
549                                        unsigned AsmVariant,
550                                        const char *ExtraCode, raw_ostream &O) {
551   // Target doesn't support this yet!
552   return true;
553 }
554
555 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
556                                   const MCSubtargetInfo *EndInfo) const {}