blob: ba6fed2a78ba7eeb66601f0bfd1ac6ea7d89306b [file] [log] [blame]
Chris Lattner7e1a8f82010-04-04 19:09:29 +00001//===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
Chris Lattner736e31d2010-04-04 18:34:07 +00002//
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//
Chris Lattner7e1a8f82010-04-04 19:09:29 +000010// This file implements the inline assembler pieces of the AsmPrinter class.
Chris Lattner736e31d2010-04-04 18:34:07 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "asm-printer"
Chris Lattner736e31d2010-04-04 18:34:07 +000015#include "llvm/CodeGen/AsmPrinter.h"
Chris Lattnercf9a4152010-04-07 05:38:05 +000016#include "llvm/Constants.h"
Chris Lattner7e1a8f82010-04-04 19:09:29 +000017#include "llvm/InlineAsm.h"
Chris Lattner6eb78062010-04-06 00:55:39 +000018#include "llvm/LLVMContext.h"
19#include "llvm/Module.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000020#include "llvm/CodeGen/MachineBasicBlock.h"
Chris Lattner6eb78062010-04-06 00:55:39 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000022#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCStreamer.h"
24#include "llvm/MC/MCSymbol.h"
Chris Lattneraf632c92010-04-05 23:11:24 +000025#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"
Chris Lattner736e31d2010-04-04 18:34:07 +000030#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Support/ErrorHandling.h"
Chris Lattneraf632c92010-04-05 23:11:24 +000033#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/SourceMgr.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000036using namespace llvm;
37
38/// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
Chris Lattner885d9412010-04-06 00:58:50 +000039void AsmPrinter::EmitInlineAsm(StringRef Str, unsigned LocCookie) const {
Chris Lattner736e31d2010-04-04 18:34:07 +000040 assert(!Str.empty() && "Can't emit empty inline asm block");
41
Chris Lattneraf632c92010-04-05 23:11:24 +000042 // 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
Chris Lattner736e31d2010-04-04 18:34:07 +000047 // 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
Chris Lattneraf632c92010-04-05 23:11:24 +000055 SourceMgr SrcMgr;
Daniel Dunbard11d59e2010-05-14 04:31:50 +000056
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 }
Chris Lattner6eb78062010-04-06 00:55:39 +000067
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()) {
Chris Lattner6eb78062010-04-06 00:55:39 +000072 SrcMgr.setDiagHandler((SourceMgr::DiagHandlerTy)(intptr_t)DiagHandler,
Chris Lattner885d9412010-04-06 00:58:50 +000073 LLVMCtx.getInlineAsmDiagnosticContext(), LocCookie);
Chris Lattner6eb78062010-04-06 00:55:39 +000074 HasDiagHandler = true;
75 }
76
Chris Lattneraf632c92010-04-05 23:11:24 +000077 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(SrcMgr, OutContext, OutStreamer, *MAI);
87 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(Parser));
88 if (!TAP)
Chris Lattner75361b62010-04-07 22:58:41 +000089 report_fatal_error("Inline asm not supported by this streamer because"
Benjamin Kramer1bd73352010-04-08 10:44:28 +000090 " we don't have an asm parser for this target\n");
Chris Lattneraf632c92010-04-05 23:11:24 +000091 Parser.setTargetParser(*TAP.get());
92
93 // Don't implicitly switch to the text section before the asm.
Chris Lattner79180e22010-04-05 23:15:42 +000094 int Res = Parser.Run(/*NoInitialTextSection*/ true,
95 /*NoFinalize*/ true);
Chris Lattner6eb78062010-04-06 00:55:39 +000096 if (Res && !HasDiagHandler)
Chris Lattner75361b62010-04-07 22:58:41 +000097 report_fatal_error("Error parsing inline asm\n");
Daniel Dunbard11d59e2010-05-14 04:31:50 +000098
99 if (TmpString)
100 delete[] TmpString;
Chris Lattner736e31d2010-04-04 18:34:07 +0000101}
102
103
104/// EmitInlineAsm - This method formats and emits the specified machine
105/// instruction that is an inline asm.
106void 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)
Chris Lattnercf9a4152010-04-07 05:38:05 +0000115 assert(NumDefs != NumOperands-2 && "No asm string?");
Chris Lattner736e31d2010-04-04 18:34:07 +0000116
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) {
Chris Lattner4c842dd2010-04-05 22:42:30 +0000125 // Don't emit the comments if writing to a .o file.
Chris Lattner736e31d2010-04-04 18:34:07 +0000126 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
Chris Lattnercf9a4152010-04-07 05:38:05 +0000141 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
142 // it.
143 unsigned LocCookie = 0;
Chris Lattnerd0024fe2010-04-08 18:20:52 +0000144 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 }
Chris Lattnercf9a4152010-04-07 05:38:05 +0000153 }
154
Chris Lattner736e31d2010-04-04 18:34:07 +0000155 // 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.
Chris Lattner4c842dd2010-04-05 22:42:30 +0000183 OS << '\n'; // Indent code with newline.
Chris Lattner736e31d2010-04-04 18:34:07 +0000184 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.
Chris Lattnerfee455e2010-04-07 05:27:36 +0000199 if (CurVariant != -1)
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000200 report_fatal_error("Nested variants found in inline asm string: '" +
201 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000202 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)
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000235 report_fatal_error("Unterminated ${:foo} operand in inline asm"
236 " string: '" + Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000237
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;
Chris Lattner65eeaad2010-04-04 18:42:18 +0000245 const char *IDEnd = IDStart;
246 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
247
248 unsigned Val;
249 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000250 report_fatal_error("Bad $ operand number in inline asm string: '" +
251 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000252 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.
Chris Lattner4c842dd2010-04-05 22:42:30 +0000261 if (*LastEmitted == 0)
Chris Lattner75361b62010-04-07 22:58:41 +0000262 report_fatal_error("Bad ${:} expression in inline asm string: '" +
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000263 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000264
265 Modifier[0] = *LastEmitted;
266 ++LastEmitted; // Consume modifier character.
267 }
268
Chris Lattner4c842dd2010-04-05 22:42:30 +0000269 if (*LastEmitted != '}')
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000270 report_fatal_error("Bad ${} expression in inline asm string: '" +
271 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000272 ++LastEmitted; // Consume '}' character.
273 }
274
Chris Lattner4c842dd2010-04-05 22:42:30 +0000275 if (Val >= NumOperands-1)
Benjamin Kramer1bd73352010-04-08 10:44:28 +0000276 report_fatal_error("Invalid $ operand number in inline asm string: '" +
277 Twine(AsmStr) + "'");
Chris Lattner736e31d2010-04-04 18:34:07 +0000278
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 = 1;
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);
Chris Lattnerfee455e2010-04-07 05:27:36 +0000304 if (InlineAsm::isMemKind(OpFlags)) {
Chris Lattner736e31d2010-04-04 18:34:07 +0000305 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);
Chris Lattner38686bd2010-04-07 23:40:44 +0000317 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
318 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
Chris Lattner736e31d2010-04-04 18:34:07 +0000319 }
320 }
321 break;
322 }
323 }
324 }
Chris Lattneraf632c92010-04-05 23:11:24 +0000325 OS << '\n' << (char)0; // null terminate string.
Chris Lattnercf9a4152010-04-07 05:38:05 +0000326 EmitInlineAsm(OS.str(), LocCookie);
Chris Lattner736e31d2010-04-04 18:34:07 +0000327
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.
342void 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;
Chris Lattner75361b62010-04-07 22:58:41 +0000364 report_fatal_error(Msg.str());
Chris Lattner736e31d2010-04-04 18:34:07 +0000365 }
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.
371bool 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
378bool 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