1 //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the inline assembler pieces of the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
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"
38 struct SrcMgrDiagInfo {
39 const MDNode *LocInfo;
45 /// SrcMgrDiagHandler - This callback is invoked when the SourceMgr for an
46 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
48 static void SrcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo,
50 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
51 assert(DiagInfo && "Diagnostic context not passed down?");
53 unsigned LocCookie = 0;
54 if (const MDNode *LocInfo = DiagInfo->LocInfo)
55 if (LocInfo->getNumOperands() > 0)
56 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocInfo->getOperand(0)))
57 LocCookie = CI->getZExtValue();
59 SourceMgr::DiagHandlerTy ChainHandler =
60 (SourceMgr::DiagHandlerTy)(intptr_t)DiagInfo->DiagHandler;
62 ChainHandler(Diag, DiagInfo->DiagContext, LocCookie);
65 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
66 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode) const {
67 assert(!Str.empty() && "Can't emit empty inline asm block");
69 // Remember if the buffer is nul terminated or not so we can avoid a copy.
70 bool isNullTerminated = Str.back() == 0;
72 Str = Str.substr(0, Str.size()-1);
74 // If the output streamer is actually a .s file, just emit the blob textually.
75 // This is useful in case the asm parser doesn't handle something but the
76 // system assembler does.
77 if (OutStreamer.hasRawTextSupport()) {
78 OutStreamer.EmitRawText(Str);
83 SrcMgrDiagInfo DiagInfo;
85 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
86 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
87 bool HasDiagHandler = false;
88 if (void *DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler()) {
89 // If the source manager has an issue, we arrange for SrcMgrDiagHandler
90 // to be invoked, getting DiagInfo passed into it.
91 DiagInfo.LocInfo = LocMDNode;
92 DiagInfo.DiagHandler = DiagHandler;
93 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
94 SrcMgr.setDiagHandler(SrcMgrDiagHandler, &DiagInfo);
95 HasDiagHandler = true;
100 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
102 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
104 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
105 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
107 OwningPtr<MCAsmParser> Parser(createMCAsmParser(TM.getTarget(), SrcMgr,
108 OutContext, OutStreamer,
110 OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(*Parser, TM));
112 report_fatal_error("Inline asm not supported by this streamer because"
113 " we don't have an asm parser for this target\n");
114 Parser->setTargetParser(*TAP.get());
116 // Don't implicitly switch to the text section before the asm.
117 int Res = Parser->Run(/*NoInitialTextSection*/ true,
118 /*NoFinalize*/ true);
119 if (Res && !HasDiagHandler)
120 report_fatal_error("Error parsing inline asm\n");
124 /// EmitInlineAsm - This method formats and emits the specified machine
125 /// instruction that is an inline asm.
126 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
127 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
129 unsigned NumOperands = MI->getNumOperands();
131 // Count the number of register definitions to find the asm string.
132 unsigned NumDefs = 0;
133 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
135 assert(NumDefs != NumOperands-2 && "No asm string?");
137 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
139 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
140 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
142 // If this asmstr is empty, just print the #APP/#NOAPP markers.
143 // These are useful to see where empty asm's wound up.
144 if (AsmStr[0] == 0) {
145 // Don't emit the comments if writing to a .o file.
146 if (!OutStreamer.hasRawTextSupport()) return;
148 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
149 MAI->getInlineAsmStart());
150 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
151 MAI->getInlineAsmEnd());
155 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
156 // enabled, so we use EmitRawText.
157 if (OutStreamer.hasRawTextSupport())
158 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
159 MAI->getInlineAsmStart());
161 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
163 unsigned LocCookie = 0;
164 const MDNode *LocMD = 0;
165 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
166 if (MI->getOperand(i-1).isMetadata() &&
167 (LocMD = MI->getOperand(i-1).getMetadata()) &&
168 LocMD->getNumOperands() != 0) {
169 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
170 LocCookie = CI->getZExtValue();
176 // Emit the inline asm to a temporary string so we can emit it through
178 SmallString<256> StringData;
179 raw_svector_ostream OS(StringData);
183 // The variant of the current asmprinter.
184 int AsmPrinterVariant = MAI->getAssemblerDialect();
186 int CurVariant = -1; // The number of the {.|.|.} region we are in.
187 const char *LastEmitted = AsmStr; // One past the last character emitted.
189 while (*LastEmitted) {
190 switch (*LastEmitted) {
192 // Not a special case, emit the string section literally.
193 const char *LiteralEnd = LastEmitted+1;
194 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
195 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
197 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
198 OS.write(LastEmitted, LiteralEnd-LastEmitted);
199 LastEmitted = LiteralEnd;
203 ++LastEmitted; // Consume newline character.
204 OS << '\n'; // Indent code with newline.
207 ++LastEmitted; // Consume '$' character.
211 switch (*LastEmitted) {
212 default: Done = false; break;
214 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
216 ++LastEmitted; // Consume second '$' character.
218 case '(': // $( -> same as GCC's { character.
219 ++LastEmitted; // Consume '(' character.
220 if (CurVariant != -1)
221 report_fatal_error("Nested variants found in inline asm string: '" +
222 Twine(AsmStr) + "'");
223 CurVariant = 0; // We're in the first variant now.
226 ++LastEmitted; // consume '|' character.
227 if (CurVariant == -1)
228 OS << '|'; // this is gcc's behavior for | outside a variant
230 ++CurVariant; // We're in the next variant.
232 case ')': // $) -> same as GCC's } char.
233 ++LastEmitted; // consume ')' character.
234 if (CurVariant == -1)
235 OS << '}'; // this is gcc's behavior for } outside a variant
242 bool HasCurlyBraces = false;
243 if (*LastEmitted == '{') { // ${variable}
244 ++LastEmitted; // Consume '{' character.
245 HasCurlyBraces = true;
248 // If we have ${:foo}, then this is not a real operand reference, it is a
249 // "magic" string reference, just like in .td files. Arrange to call
251 if (HasCurlyBraces && *LastEmitted == ':') {
253 const char *StrStart = LastEmitted;
254 const char *StrEnd = strchr(StrStart, '}');
256 report_fatal_error("Unterminated ${:foo} operand in inline asm"
257 " string: '" + Twine(AsmStr) + "'");
259 std::string Val(StrStart, StrEnd);
260 PrintSpecial(MI, OS, Val.c_str());
261 LastEmitted = StrEnd+1;
265 const char *IDStart = LastEmitted;
266 const char *IDEnd = IDStart;
267 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
270 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
271 report_fatal_error("Bad $ operand number in inline asm string: '" +
272 Twine(AsmStr) + "'");
275 char Modifier[2] = { 0, 0 };
277 if (HasCurlyBraces) {
278 // If we have curly braces, check for a modifier character. This
279 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
280 if (*LastEmitted == ':') {
281 ++LastEmitted; // Consume ':' character.
282 if (*LastEmitted == 0)
283 report_fatal_error("Bad ${:} expression in inline asm string: '" +
284 Twine(AsmStr) + "'");
286 Modifier[0] = *LastEmitted;
287 ++LastEmitted; // Consume modifier character.
290 if (*LastEmitted != '}')
291 report_fatal_error("Bad ${} expression in inline asm string: '" +
292 Twine(AsmStr) + "'");
293 ++LastEmitted; // Consume '}' character.
296 if (Val >= NumOperands-1)
297 report_fatal_error("Invalid $ operand number in inline asm string: '" +
298 Twine(AsmStr) + "'");
300 // Okay, we finally have a value number. Ask the target to print this
302 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
307 // Scan to find the machine operand number for the operand.
309 if (OpNo >= MI->getNumOperands()) break;
310 unsigned OpFlags = MI->getOperand(OpNo).getImm();
311 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
314 if (OpNo >= MI->getNumOperands()) {
317 unsigned OpFlags = MI->getOperand(OpNo).getImm();
318 ++OpNo; // Skip over the ID number.
320 if (Modifier[0] == 'l') // labels are target independent
321 // FIXME: What if the operand isn't an MBB, report error?
322 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
324 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
325 if (InlineAsm::isMemKind(OpFlags)) {
326 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
327 Modifier[0] ? Modifier : 0,
330 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
331 Modifier[0] ? Modifier : 0, OS);
337 raw_string_ostream Msg(msg);
338 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
339 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
346 OS << '\n' << (char)0; // null terminate string.
347 EmitInlineAsm(OS.str(), LocMD);
349 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
350 // enabled, so we use EmitRawText.
351 if (OutStreamer.hasRawTextSupport())
352 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
353 MAI->getInlineAsmEnd());
357 /// PrintSpecial - Print information related to the specified machine instr
358 /// that is independent of the operand, and may be independent of the instr
359 /// itself. This can be useful for portably encoding the comment character
360 /// or other bits of target-specific knowledge into the asmstrings. The
361 /// syntax used is ${:comment}. Targets can override this to add support
362 /// for their own strange codes.
363 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
364 const char *Code) const {
365 if (!strcmp(Code, "private")) {
366 OS << MAI->getPrivateGlobalPrefix();
367 } else if (!strcmp(Code, "comment")) {
368 OS << MAI->getCommentString();
369 } else if (!strcmp(Code, "uid")) {
370 // Comparing the address of MI isn't sufficient, because machineinstrs may
371 // be allocated to the same address across functions.
373 // If this is a new LastFn instruction, bump the counter.
374 if (LastMI != MI || LastFn != getFunctionNumber()) {
377 LastFn = getFunctionNumber();
382 raw_string_ostream Msg(msg);
383 Msg << "Unknown special formatter '" << Code
384 << "' for machine instr: " << *MI;
385 report_fatal_error(Msg.str());
389 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
390 /// instruction, using the specified assembler variant. Targets should
391 /// override this to format as appropriate.
392 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
393 unsigned AsmVariant, const char *ExtraCode,
395 // Target doesn't support this yet!
399 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
401 const char *ExtraCode, raw_ostream &O) {
402 // Target doesn't support this yet!