OSDN Git Service

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