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