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