OSDN Git Service

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