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