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 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
41 #define DEBUG_TYPE "asm-printer"
44 struct SrcMgrDiagInfo {
45 const MDNode *LocInfo;
46 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
51 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
52 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
54 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
55 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
56 assert(DiagInfo && "Diagnostic context not passed down?");
58 // If the inline asm had metadata associated with it, pull out a location
59 // cookie corresponding to which line the error occurred on.
60 unsigned LocCookie = 0;
61 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
62 unsigned ErrorLine = Diag.getLineNo()-1;
63 if (ErrorLine >= LocInfo->getNumOperands())
66 if (LocInfo->getNumOperands() != 0)
67 if (const ConstantInt *CI =
68 mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
69 LocCookie = CI->getZExtValue();
72 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
75 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
76 void AsmPrinter::EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
77 const MCTargetOptions &MCOptions,
78 const MDNode *LocMDNode,
79 InlineAsm::AsmDialect Dialect) const {
80 assert(!Str.empty() && "Can't emit empty inline asm block");
82 // Remember if the buffer is nul terminated or not so we can avoid a copy.
83 bool isNullTerminated = Str.back() == 0;
85 Str = Str.substr(0, Str.size()-1);
87 // If the output streamer does not have mature MC support or the integrated
88 // assembler has been disabled, just emit the blob textually.
89 // Otherwise parse the asm and emit it via MC support.
90 // This is useful in case the asm parser doesn't handle something but the
91 // system assembler does.
92 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
93 assert(MCAI && "No MCAsmInfo");
94 if (!MCAI->useIntegratedAssembler() &&
95 !OutStreamer->isIntegratedAssemblerRequired()) {
97 OutStreamer->EmitRawText(Str);
98 emitInlineAsmEnd(STI, nullptr);
103 SrcMgrDiagInfo DiagInfo;
105 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
106 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
107 bool HasDiagHandler = false;
108 if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
109 // If the source manager has an issue, we arrange for srcMgrDiagHandler
110 // to be invoked, getting DiagInfo passed into it.
111 DiagInfo.LocInfo = LocMDNode;
112 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
113 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
114 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
115 HasDiagHandler = true;
118 std::unique_ptr<MemoryBuffer> Buffer;
119 if (isNullTerminated)
120 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
122 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
124 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
125 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
127 std::unique_ptr<MCAsmParser> Parser(
128 createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI));
130 // Create a temporary copy of the original STI because the parser may modify
131 // it. For example, when switching between arm and thumb mode. If the target
132 // needs to emit code to return to the original state it can do so in
133 // emitInlineAsmEnd().
134 MCSubtargetInfo TmpSTI = STI;
136 // We create a new MCInstrInfo here since we might be at the module level
137 // and not have a MachineFunction to initialize the TargetInstrInfo from and
138 // we only need MCInstrInfo for asm parsing. We create one unconditionally
139 // because it's not subtarget dependent.
140 std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
141 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
142 TmpSTI, *Parser, *MII, MCOptions));
144 report_fatal_error("Inline asm not supported by this streamer because"
145 " we don't have an asm parser for this target\n");
146 Parser->setAssemblerDialect(Dialect);
147 Parser->setTargetParser(*TAP.get());
149 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
150 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
153 emitInlineAsmStart();
154 // Don't implicitly switch to the text section before the asm.
155 int Res = Parser->Run(/*NoInitialTextSection*/ true,
156 /*NoFinalize*/ true);
157 emitInlineAsmEnd(STI, &TmpSTI);
158 if (Res && !HasDiagHandler)
159 report_fatal_error("Error parsing inline asm\n");
162 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
163 MachineModuleInfo *MMI, int InlineAsmVariant,
164 AsmPrinter *AP, unsigned LocCookie,
166 // Switch to the inline assembly variant.
167 OS << "\t.intel_syntax\n\t";
169 const char *LastEmitted = AsmStr; // One past the last character emitted.
170 unsigned NumOperands = MI->getNumOperands();
172 while (*LastEmitted) {
173 switch (*LastEmitted) {
175 // Not a special case, emit the string section literally.
176 const char *LiteralEnd = LastEmitted+1;
177 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
178 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
181 OS.write(LastEmitted, LiteralEnd-LastEmitted);
182 LastEmitted = LiteralEnd;
186 ++LastEmitted; // Consume newline character.
187 OS << '\n'; // Indent code with newline.
190 ++LastEmitted; // Consume '$' character.
194 switch (*LastEmitted) {
195 default: Done = false; break;
197 ++LastEmitted; // Consume second '$' character.
202 const char *IDStart = LastEmitted;
203 const char *IDEnd = IDStart;
204 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
207 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
208 report_fatal_error("Bad $ operand number in inline asm string: '" +
209 Twine(AsmStr) + "'");
212 if (Val >= NumOperands-1)
213 report_fatal_error("Invalid $ operand number in inline asm string: '" +
214 Twine(AsmStr) + "'");
216 // Okay, we finally have a value number. Ask the target to print this
218 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
222 // Scan to find the machine operand number for the operand.
224 if (OpNo >= MI->getNumOperands()) break;
225 unsigned OpFlags = MI->getOperand(OpNo).getImm();
226 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
229 // We may have a location metadata attached to the end of the
230 // instruction, and at no point should see metadata at any
231 // other point while processing. It's an error if so.
232 if (OpNo >= MI->getNumOperands() ||
233 MI->getOperand(OpNo).isMetadata()) {
236 unsigned OpFlags = MI->getOperand(OpNo).getImm();
237 ++OpNo; // Skip over the ID number.
239 if (InlineAsm::isMemKind(OpFlags)) {
240 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
241 /*Modifier*/ nullptr, OS);
243 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
244 /*Modifier*/ nullptr, OS);
249 raw_string_ostream Msg(msg);
250 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
251 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
257 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
260 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
261 MachineModuleInfo *MMI, int InlineAsmVariant,
262 int AsmPrinterVariant, AsmPrinter *AP,
263 unsigned LocCookie, raw_ostream &OS) {
264 int CurVariant = -1; // The number of the {.|.|.} region we are in.
265 const char *LastEmitted = AsmStr; // One past the last character emitted.
266 unsigned NumOperands = MI->getNumOperands();
270 while (*LastEmitted) {
271 switch (*LastEmitted) {
273 // Not a special case, emit the string section literally.
274 const char *LiteralEnd = LastEmitted+1;
275 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
276 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
278 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
279 OS.write(LastEmitted, LiteralEnd-LastEmitted);
280 LastEmitted = LiteralEnd;
284 ++LastEmitted; // Consume newline character.
285 OS << '\n'; // Indent code with newline.
288 ++LastEmitted; // Consume '$' character.
292 switch (*LastEmitted) {
293 default: Done = false; break;
295 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
297 ++LastEmitted; // Consume second '$' character.
299 case '(': // $( -> same as GCC's { character.
300 ++LastEmitted; // Consume '(' character.
301 if (CurVariant != -1)
302 report_fatal_error("Nested variants found in inline asm string: '" +
303 Twine(AsmStr) + "'");
304 CurVariant = 0; // We're in the first variant now.
307 ++LastEmitted; // consume '|' character.
308 if (CurVariant == -1)
309 OS << '|'; // this is gcc's behavior for | outside a variant
311 ++CurVariant; // We're in the next variant.
313 case ')': // $) -> same as GCC's } char.
314 ++LastEmitted; // consume ')' character.
315 if (CurVariant == -1)
316 OS << '}'; // this is gcc's behavior for } outside a variant
323 bool HasCurlyBraces = false;
324 if (*LastEmitted == '{') { // ${variable}
325 ++LastEmitted; // Consume '{' character.
326 HasCurlyBraces = true;
329 // If we have ${:foo}, then this is not a real operand reference, it is a
330 // "magic" string reference, just like in .td files. Arrange to call
332 if (HasCurlyBraces && *LastEmitted == ':') {
334 const char *StrStart = LastEmitted;
335 const char *StrEnd = strchr(StrStart, '}');
337 report_fatal_error("Unterminated ${:foo} operand in inline asm"
338 " string: '" + Twine(AsmStr) + "'");
340 std::string Val(StrStart, StrEnd);
341 AP->PrintSpecial(MI, OS, Val.c_str());
342 LastEmitted = StrEnd+1;
346 const char *IDStart = LastEmitted;
347 const char *IDEnd = IDStart;
348 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
351 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
352 report_fatal_error("Bad $ operand number in inline asm string: '" +
353 Twine(AsmStr) + "'");
356 char Modifier[2] = { 0, 0 };
358 if (HasCurlyBraces) {
359 // If we have curly braces, check for a modifier character. This
360 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
361 if (*LastEmitted == ':') {
362 ++LastEmitted; // Consume ':' character.
363 if (*LastEmitted == 0)
364 report_fatal_error("Bad ${:} expression in inline asm string: '" +
365 Twine(AsmStr) + "'");
367 Modifier[0] = *LastEmitted;
368 ++LastEmitted; // Consume modifier character.
371 if (*LastEmitted != '}')
372 report_fatal_error("Bad ${} expression in inline asm string: '" +
373 Twine(AsmStr) + "'");
374 ++LastEmitted; // Consume '}' character.
377 if (Val >= NumOperands-1)
378 report_fatal_error("Invalid $ operand number in inline asm string: '" +
379 Twine(AsmStr) + "'");
381 // Okay, we finally have a value number. Ask the target to print this
383 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
384 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
388 // Scan to find the machine operand number for the operand.
390 if (OpNo >= MI->getNumOperands()) break;
391 unsigned OpFlags = MI->getOperand(OpNo).getImm();
392 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
395 // We may have a location metadata attached to the end of the
396 // instruction, and at no point should see metadata at any
397 // other point while processing. It's an error if so.
398 if (OpNo >= MI->getNumOperands() ||
399 MI->getOperand(OpNo).isMetadata()) {
402 unsigned OpFlags = MI->getOperand(OpNo).getImm();
403 ++OpNo; // Skip over the ID number.
405 if (Modifier[0] == 'l') { // Labels are target independent.
406 // FIXME: What if the operand isn't an MBB, report error?
407 const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
408 Sym->print(OS, AP->MAI);
410 if (InlineAsm::isMemKind(OpFlags)) {
411 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
412 Modifier[0] ? Modifier : nullptr,
415 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
416 Modifier[0] ? Modifier : nullptr, OS);
422 raw_string_ostream Msg(msg);
423 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
424 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
431 OS << '\n' << (char)0; // null terminate string.
434 /// EmitInlineAsm - This method formats and emits the specified machine
435 /// instruction that is an inline asm.
436 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
437 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
439 // Count the number of register definitions to find the asm string.
440 unsigned NumDefs = 0;
441 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
443 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
445 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
447 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
448 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
450 // If this asmstr is empty, just print the #APP/#NOAPP markers.
451 // These are useful to see where empty asm's wound up.
452 if (AsmStr[0] == 0) {
453 OutStreamer->emitRawComment(MAI->getInlineAsmStart());
454 OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
458 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
459 // enabled, so we use emitRawComment.
460 OutStreamer->emitRawComment(MAI->getInlineAsmStart());
462 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
464 unsigned LocCookie = 0;
465 const MDNode *LocMD = nullptr;
466 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
467 if (MI->getOperand(i-1).isMetadata() &&
468 (LocMD = MI->getOperand(i-1).getMetadata()) &&
469 LocMD->getNumOperands() != 0) {
470 if (const ConstantInt *CI =
471 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
472 LocCookie = CI->getZExtValue();
478 // Emit the inline asm to a temporary string so we can emit it through
480 SmallString<256> StringData;
481 raw_svector_ostream OS(StringData);
483 // The variant of the current asmprinter.
484 int AsmPrinterVariant = MAI->getAssemblerDialect();
485 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
486 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
487 if (InlineAsmVariant == InlineAsm::AD_ATT)
488 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
491 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
493 // Reset SanitizeAddress based on the function's attribute.
494 MCTargetOptions MCOptions = TM.Options.MCOptions;
495 MCOptions.SanitizeAddress =
496 MF->getFunction()->hasFnAttribute(Attribute::SanitizeAddress);
498 EmitInlineAsm(OS.str(), getSubtargetInfo(), MCOptions, LocMD,
499 MI->getInlineAsmDialect());
501 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
502 // enabled, so we use emitRawComment.
503 OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
507 /// PrintSpecial - Print information related to the specified machine instr
508 /// that is independent of the operand, and may be independent of the instr
509 /// itself. This can be useful for portably encoding the comment character
510 /// or other bits of target-specific knowledge into the asmstrings. The
511 /// syntax used is ${:comment}. Targets can override this to add support
512 /// for their own strange codes.
513 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
514 const char *Code) const {
515 const DataLayout *DL = TM.getDataLayout();
516 if (!strcmp(Code, "private")) {
517 OS << DL->getPrivateGlobalPrefix();
518 } else if (!strcmp(Code, "comment")) {
519 OS << MAI->getCommentString();
520 } else if (!strcmp(Code, "uid")) {
521 // Comparing the address of MI isn't sufficient, because machineinstrs may
522 // be allocated to the same address across functions.
524 // If this is a new LastFn instruction, bump the counter.
525 if (LastMI != MI || LastFn != getFunctionNumber()) {
528 LastFn = getFunctionNumber();
533 raw_string_ostream Msg(msg);
534 Msg << "Unknown special formatter '" << Code
535 << "' for machine instr: " << *MI;
536 report_fatal_error(Msg.str());
540 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
541 /// instruction, using the specified assembler variant. Targets should
542 /// override this to format as appropriate.
543 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
544 unsigned AsmVariant, const char *ExtraCode,
546 // Does this asm operand have a single letter operand modifier?
547 if (ExtraCode && ExtraCode[0]) {
548 if (ExtraCode[1] != 0) return true; // Unknown modifier.
550 const MachineOperand &MO = MI->getOperand(OpNo);
551 switch (ExtraCode[0]) {
553 return true; // Unknown modifier.
554 case 'c': // Substitute immediate value without immediate syntax
555 if (MO.getType() != MachineOperand::MO_Immediate)
559 case 'n': // Negate the immediate constant.
560 if (MO.getType() != MachineOperand::MO_Immediate)
569 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
571 const char *ExtraCode, raw_ostream &O) {
572 // Target doesn't support this yet!
576 void AsmPrinter::emitInlineAsmStart() const {}
578 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
579 const MCSubtargetInfo *EndInfo) const {}