MC: Move several clients to using AsmParser constructor function.
[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/Constants.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/TargetAsmParser.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
35 using namespace llvm;
36
37 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
38 void AsmPrinter::EmitInlineAsm(StringRef Str, unsigned LocCookie) const {
39   assert(!Str.empty() && "Can't emit empty inline asm block");
40   
41   // Remember if the buffer is nul terminated or not so we can avoid a copy.
42   bool isNullTerminated = Str.back() == 0;
43   if (isNullTerminated)
44     Str = Str.substr(0, Str.size()-1);
45   
46   // If the output streamer is actually a .s file, just emit the blob textually.
47   // This is useful in case the asm parser doesn't handle something but the
48   // system assembler does.
49   if (OutStreamer.hasRawTextSupport()) {
50     OutStreamer.EmitRawText(Str);
51     return;
52   }
53   
54   SourceMgr SrcMgr;
55   
56   // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
57   LLVMContext &LLVMCtx = MMI->getModule()->getContext();
58   bool HasDiagHandler = false;
59   if (void *DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler()) {
60     SrcMgr.setDiagHandler((SourceMgr::DiagHandlerTy)(intptr_t)DiagHandler,
61                           LLVMCtx.getInlineAsmDiagnosticContext(), LocCookie);
62     HasDiagHandler = true;
63   }
64   
65   MemoryBuffer *Buffer;
66   if (isNullTerminated)
67     Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
68   else
69     Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
70
71   // Tell SrcMgr about this buffer, it takes ownership of the buffer.
72   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
73   
74   OwningPtr<MCAsmParser> Parser(createMCAsmParser(TM.getTarget(), SrcMgr,
75                                                   OutContext, OutStreamer,
76                                                   *MAI));
77   OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(*Parser));
78   if (!TAP)
79     report_fatal_error("Inline asm not supported by this streamer because"
80                        " we don't have an asm parser for this target\n");
81   Parser->setTargetParser(*TAP.get());
82
83   // Don't implicitly switch to the text section before the asm.
84   int Res = Parser->Run(/*NoInitialTextSection*/ true,
85                         /*NoFinalize*/ true);
86   if (Res && !HasDiagHandler)
87     report_fatal_error("Error parsing inline asm\n");
88 }
89
90
91 /// EmitInlineAsm - This method formats and emits the specified machine
92 /// instruction that is an inline asm.
93 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
94   assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
95   
96   unsigned NumOperands = MI->getNumOperands();
97   
98   // Count the number of register definitions to find the asm string.
99   unsigned NumDefs = 0;
100   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
101        ++NumDefs)
102     assert(NumDefs != NumOperands-2 && "No asm string?");
103   
104   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
105
106   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
107   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
108
109   // If this asmstr is empty, just print the #APP/#NOAPP markers.
110   // These are useful to see where empty asm's wound up.
111   if (AsmStr[0] == 0) {
112     // Don't emit the comments if writing to a .o file.
113     if (!OutStreamer.hasRawTextSupport()) return;
114
115     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
116                             MAI->getInlineAsmStart());
117     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
118                             MAI->getInlineAsmEnd());
119     return;
120   }
121
122   // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
123   // enabled, so we use EmitRawText.
124   if (OutStreamer.hasRawTextSupport())
125     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
126                             MAI->getInlineAsmStart());
127
128   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
129   // it.
130   unsigned LocCookie = 0;
131   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
132     if (MI->getOperand(i-1).isMetadata())
133       if (const MDNode *SrcLoc = MI->getOperand(i-1).getMetadata())
134         if (SrcLoc->getNumOperands() != 0)
135           if (const ConstantInt *CI =
136               dyn_cast<ConstantInt>(SrcLoc->getOperand(0))) {
137             LocCookie = CI->getZExtValue();
138             break;
139           }
140   }
141   
142   // Emit the inline asm to a temporary string so we can emit it through
143   // EmitInlineAsm.
144   SmallString<256> StringData;
145   raw_svector_ostream OS(StringData);
146   
147   OS << '\t';
148
149   // The variant of the current asmprinter.
150   int AsmPrinterVariant = MAI->getAssemblerDialect();
151
152   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
153   const char *LastEmitted = AsmStr; // One past the last character emitted.
154   
155   while (*LastEmitted) {
156     switch (*LastEmitted) {
157     default: {
158       // Not a special case, emit the string section literally.
159       const char *LiteralEnd = LastEmitted+1;
160       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
161              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
162         ++LiteralEnd;
163       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
164         OS.write(LastEmitted, LiteralEnd-LastEmitted);
165       LastEmitted = LiteralEnd;
166       break;
167     }
168     case '\n':
169       ++LastEmitted;   // Consume newline character.
170       OS << '\n';      // Indent code with newline.
171       break;
172     case '$': {
173       ++LastEmitted;   // Consume '$' character.
174       bool Done = true;
175
176       // Handle escapes.
177       switch (*LastEmitted) {
178       default: Done = false; break;
179       case '$':     // $$ -> $
180         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
181           OS << '$';
182         ++LastEmitted;  // Consume second '$' character.
183         break;
184       case '(':             // $( -> same as GCC's { character.
185         ++LastEmitted;      // Consume '(' character.
186         if (CurVariant != -1)
187           report_fatal_error("Nested variants found in inline asm string: '" +
188                              Twine(AsmStr) + "'");
189         CurVariant = 0;     // We're in the first variant now.
190         break;
191       case '|':
192         ++LastEmitted;  // consume '|' character.
193         if (CurVariant == -1)
194           OS << '|';       // this is gcc's behavior for | outside a variant
195         else
196           ++CurVariant;   // We're in the next variant.
197         break;
198       case ')':         // $) -> same as GCC's } char.
199         ++LastEmitted;  // consume ')' character.
200         if (CurVariant == -1)
201           OS << '}';     // this is gcc's behavior for } outside a variant
202         else 
203           CurVariant = -1;
204         break;
205       }
206       if (Done) break;
207       
208       bool HasCurlyBraces = false;
209       if (*LastEmitted == '{') {     // ${variable}
210         ++LastEmitted;               // Consume '{' character.
211         HasCurlyBraces = true;
212       }
213       
214       // If we have ${:foo}, then this is not a real operand reference, it is a
215       // "magic" string reference, just like in .td files.  Arrange to call
216       // PrintSpecial.
217       if (HasCurlyBraces && *LastEmitted == ':') {
218         ++LastEmitted;
219         const char *StrStart = LastEmitted;
220         const char *StrEnd = strchr(StrStart, '}');
221         if (StrEnd == 0)
222           report_fatal_error("Unterminated ${:foo} operand in inline asm"
223                              " string: '" + Twine(AsmStr) + "'");
224         
225         std::string Val(StrStart, StrEnd);
226         PrintSpecial(MI, OS, Val.c_str());
227         LastEmitted = StrEnd+1;
228         break;
229       }
230             
231       const char *IDStart = LastEmitted;
232       const char *IDEnd = IDStart;
233       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;      
234       
235       unsigned Val;
236       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
237         report_fatal_error("Bad $ operand number in inline asm string: '" +
238                            Twine(AsmStr) + "'");
239       LastEmitted = IDEnd;
240       
241       char Modifier[2] = { 0, 0 };
242       
243       if (HasCurlyBraces) {
244         // If we have curly braces, check for a modifier character.  This
245         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
246         if (*LastEmitted == ':') {
247           ++LastEmitted;    // Consume ':' character.
248           if (*LastEmitted == 0)
249             report_fatal_error("Bad ${:} expression in inline asm string: '" +
250                                Twine(AsmStr) + "'");
251           
252           Modifier[0] = *LastEmitted;
253           ++LastEmitted;    // Consume modifier character.
254         }
255         
256         if (*LastEmitted != '}')
257           report_fatal_error("Bad ${} expression in inline asm string: '" +
258                              Twine(AsmStr) + "'");
259         ++LastEmitted;    // Consume '}' character.
260       }
261       
262       if (Val >= NumOperands-1)
263         report_fatal_error("Invalid $ operand number in inline asm string: '" +
264                            Twine(AsmStr) + "'");
265       
266       // Okay, we finally have a value number.  Ask the target to print this
267       // operand!
268       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
269         unsigned OpNo = 2;
270
271         bool Error = false;
272
273         // Scan to find the machine operand number for the operand.
274         for (; Val; --Val) {
275           if (OpNo >= MI->getNumOperands()) break;
276           unsigned OpFlags = MI->getOperand(OpNo).getImm();
277           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
278         }
279
280         if (OpNo >= MI->getNumOperands()) {
281           Error = true;
282         } else {
283           unsigned OpFlags = MI->getOperand(OpNo).getImm();
284           ++OpNo;  // Skip over the ID number.
285
286           if (Modifier[0] == 'l')  // labels are target independent
287             // FIXME: What if the operand isn't an MBB, report error?
288             OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
289           else {
290             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
291             if (InlineAsm::isMemKind(OpFlags)) {
292               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
293                                                 Modifier[0] ? Modifier : 0,
294                                                 OS);
295             } else {
296               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
297                                           Modifier[0] ? Modifier : 0, OS);
298             }
299           }
300         }
301         if (Error) {
302           std::string msg;
303           raw_string_ostream Msg(msg);
304           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
305           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
306         }
307       }
308       break;
309     }
310     }
311   }
312   OS << '\n' << (char)0;  // null terminate string.
313   EmitInlineAsm(OS.str(), LocCookie);
314   
315   // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
316   // enabled, so we use EmitRawText.
317   if (OutStreamer.hasRawTextSupport())
318     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
319                             MAI->getInlineAsmEnd());
320 }
321
322
323 /// PrintSpecial - Print information related to the specified machine instr
324 /// that is independent of the operand, and may be independent of the instr
325 /// itself.  This can be useful for portably encoding the comment character
326 /// or other bits of target-specific knowledge into the asmstrings.  The
327 /// syntax used is ${:comment}.  Targets can override this to add support
328 /// for their own strange codes.
329 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
330                               const char *Code) const {
331   if (!strcmp(Code, "private")) {
332     OS << MAI->getPrivateGlobalPrefix();
333   } else if (!strcmp(Code, "comment")) {
334     OS << MAI->getCommentString();
335   } else if (!strcmp(Code, "uid")) {
336     // Comparing the address of MI isn't sufficient, because machineinstrs may
337     // be allocated to the same address across functions.
338     
339     // If this is a new LastFn instruction, bump the counter.
340     if (LastMI != MI || LastFn != getFunctionNumber()) {
341       ++Counter;
342       LastMI = MI;
343       LastFn = getFunctionNumber();
344     }
345     OS << Counter;
346   } else {
347     std::string msg;
348     raw_string_ostream Msg(msg);
349     Msg << "Unknown special formatter '" << Code
350          << "' for machine instr: " << *MI;
351     report_fatal_error(Msg.str());
352   }    
353 }
354
355 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
356 /// instruction, using the specified assembler variant.  Targets should
357 /// override this to format as appropriate.
358 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
359                                  unsigned AsmVariant, const char *ExtraCode,
360                                  raw_ostream &O) {
361   // Target doesn't support this yet!
362   return true;
363 }
364
365 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
366                                        unsigned AsmVariant,
367                                        const char *ExtraCode, raw_ostream &O) {
368   // Target doesn't support this yet!
369   return true;
370 }
371