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/ADT/SmallString.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/CodeGen/AsmPrinter.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/MCParser/MCTargetAsmParser.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.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"
43 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
44 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
46 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
47 AsmPrinter::SrcMgrDiagInfo *DiagInfo =
48 static_cast<AsmPrinter::SrcMgrDiagInfo *>(diagInfo);
49 assert(DiagInfo && "Diagnostic context not passed down?");
51 // Look up a LocInfo for the buffer this diagnostic is coming from.
52 unsigned BufNum = DiagInfo->SrcMgr.FindBufferContainingLoc(Diag.getLoc());
53 const MDNode *LocInfo = nullptr;
54 if (BufNum > 0 && BufNum <= DiagInfo->LocInfos.size())
55 LocInfo = DiagInfo->LocInfos[BufNum-1];
57 // If the inline asm had metadata associated with it, pull out a location
58 // cookie corresponding to which line the error occurred on.
59 unsigned LocCookie = 0;
61 unsigned ErrorLine = Diag.getLineNo()-1;
62 if (ErrorLine >= LocInfo->getNumOperands())
65 if (LocInfo->getNumOperands() != 0)
66 if (const ConstantInt *CI =
67 mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
68 LocCookie = CI->getZExtValue();
71 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
74 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
75 void AsmPrinter::EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
76 const MCTargetOptions &MCOptions,
77 const MDNode *LocMDNode,
78 InlineAsm::AsmDialect Dialect) const {
79 assert(!Str.empty() && "Can't emit empty inline asm block");
81 // Remember if the buffer is nul terminated or not so we can avoid a copy.
82 bool isNullTerminated = Str.back() == 0;
84 Str = Str.substr(0, Str.size()-1);
86 // If the output streamer does not have mature MC support or the integrated
87 // assembler has been disabled, just emit the blob textually.
88 // Otherwise parse the asm and emit it via MC support.
89 // This is useful in case the asm parser doesn't handle something but the
90 // system assembler does.
91 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
92 assert(MCAI && "No MCAsmInfo");
93 if (!MCAI->useIntegratedAssembler() &&
94 !OutStreamer->isIntegratedAssemblerRequired()) {
96 OutStreamer->EmitRawText(Str);
97 emitInlineAsmEnd(STI, nullptr);
102 DiagInfo = make_unique<SrcMgrDiagInfo>();
104 MCContext &Context = MMI->getContext();
105 Context.setInlineSourceManager(&DiagInfo->SrcMgr);
107 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
108 if (LLVMCtx.getInlineAsmDiagnosticHandler()) {
109 DiagInfo->DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
110 DiagInfo->DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
111 DiagInfo->SrcMgr.setDiagHandler(srcMgrDiagHandler, DiagInfo.get());
115 SourceMgr &SrcMgr = DiagInfo->SrcMgr;
116 SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths);
118 std::unique_ptr<MemoryBuffer> Buffer;
119 // The inline asm source manager will outlive Str, so make a copy of the
120 // string for SourceMgr to own.
121 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
123 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
124 unsigned BufNum = SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
126 // Store LocMDNode in DiagInfo, using BufNum as an identifier.
128 DiagInfo->LocInfos.resize(BufNum);
129 DiagInfo->LocInfos[BufNum-1] = LocMDNode;
132 std::unique_ptr<MCAsmParser> Parser(
133 createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI, BufNum));
135 // We create a new MCInstrInfo here since we might be at the module level
136 // and not have a MachineFunction to initialize the TargetInstrInfo from and
137 // we only need MCInstrInfo for asm parsing. We create one unconditionally
138 // because it's not subtarget dependent.
139 std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
140 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
141 STI, *Parser, *MII, MCOptions));
143 report_fatal_error("Inline asm not supported by this streamer because"
144 " we don't have an asm parser for this target\n");
145 Parser->setAssemblerDialect(Dialect);
146 Parser->setTargetParser(*TAP.get());
147 if (Dialect == InlineAsm::AD_Intel)
148 // We need this flag to be able to parse numbers like "0bH"
149 Parser->setParsingInlineAsm(true);
151 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
152 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
155 emitInlineAsmStart();
156 // Don't implicitly switch to the text section before the asm.
157 int Res = Parser->Run(/*NoInitialTextSection*/ true,
158 /*NoFinalize*/ true);
159 emitInlineAsmEnd(STI, &TAP->getSTI());
161 if (Res && !DiagInfo->DiagHandler)
162 report_fatal_error("Error parsing inline asm\n");
165 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
166 MachineModuleInfo *MMI, int InlineAsmVariant,
167 AsmPrinter *AP, unsigned LocCookie,
169 // Switch to the inline assembly variant.
170 OS << "\t.intel_syntax\n\t";
172 const char *LastEmitted = AsmStr; // One past the last character emitted.
173 unsigned NumOperands = MI->getNumOperands();
175 while (*LastEmitted) {
176 switch (*LastEmitted) {
178 // Not a special case, emit the string section literally.
179 const char *LiteralEnd = LastEmitted+1;
180 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
181 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
184 OS.write(LastEmitted, LiteralEnd-LastEmitted);
185 LastEmitted = LiteralEnd;
189 ++LastEmitted; // Consume newline character.
190 OS << '\n'; // Indent code with newline.
193 ++LastEmitted; // Consume '$' character.
197 switch (*LastEmitted) {
198 default: Done = false; break;
200 ++LastEmitted; // Consume second '$' character.
205 // If we have ${:foo}, then this is not a real operand reference, it is a
206 // "magic" string reference, just like in .td files. Arrange to call
208 if (LastEmitted[0] == '{' && LastEmitted[1] == ':') {
210 const char *StrStart = LastEmitted;
211 const char *StrEnd = strchr(StrStart, '}');
213 report_fatal_error("Unterminated ${:foo} operand in inline asm"
214 " string: '" + Twine(AsmStr) + "'");
216 std::string Val(StrStart, StrEnd);
217 AP->PrintSpecial(MI, OS, Val.c_str());
218 LastEmitted = StrEnd+1;
222 const char *IDStart = LastEmitted;
223 const char *IDEnd = IDStart;
224 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
227 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
228 report_fatal_error("Bad $ operand number in inline asm string: '" +
229 Twine(AsmStr) + "'");
232 if (Val >= NumOperands-1)
233 report_fatal_error("Invalid $ operand number in inline asm string: '" +
234 Twine(AsmStr) + "'");
236 // Okay, we finally have a value number. Ask the target to print this
238 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
242 // Scan to find the machine operand number for the operand.
244 if (OpNo >= MI->getNumOperands()) break;
245 unsigned OpFlags = MI->getOperand(OpNo).getImm();
246 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
249 // We may have a location metadata attached to the end of the
250 // instruction, and at no point should see metadata at any
251 // other point while processing. It's an error if so.
252 if (OpNo >= MI->getNumOperands() ||
253 MI->getOperand(OpNo).isMetadata()) {
256 unsigned OpFlags = MI->getOperand(OpNo).getImm();
257 ++OpNo; // Skip over the ID number.
259 if (InlineAsm::isMemKind(OpFlags)) {
260 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
261 /*Modifier*/ nullptr, OS);
263 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
264 /*Modifier*/ nullptr, OS);
269 raw_string_ostream Msg(msg);
270 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
271 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
277 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
280 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
281 MachineModuleInfo *MMI, int InlineAsmVariant,
282 int AsmPrinterVariant, AsmPrinter *AP,
283 unsigned LocCookie, raw_ostream &OS) {
284 int CurVariant = -1; // The number of the {.|.|.} region we are in.
285 const char *LastEmitted = AsmStr; // One past the last character emitted.
286 unsigned NumOperands = MI->getNumOperands();
290 while (*LastEmitted) {
291 switch (*LastEmitted) {
293 // Not a special case, emit the string section literally.
294 const char *LiteralEnd = LastEmitted+1;
295 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
296 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
298 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
299 OS.write(LastEmitted, LiteralEnd-LastEmitted);
300 LastEmitted = LiteralEnd;
304 ++LastEmitted; // Consume newline character.
305 OS << '\n'; // Indent code with newline.
308 ++LastEmitted; // Consume '$' character.
312 switch (*LastEmitted) {
313 default: Done = false; break;
315 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
317 ++LastEmitted; // Consume second '$' character.
319 case '(': // $( -> same as GCC's { character.
320 ++LastEmitted; // Consume '(' character.
321 if (CurVariant != -1)
322 report_fatal_error("Nested variants found in inline asm string: '" +
323 Twine(AsmStr) + "'");
324 CurVariant = 0; // We're in the first variant now.
327 ++LastEmitted; // consume '|' character.
328 if (CurVariant == -1)
329 OS << '|'; // this is gcc's behavior for | outside a variant
331 ++CurVariant; // We're in the next variant.
333 case ')': // $) -> same as GCC's } char.
334 ++LastEmitted; // consume ')' character.
335 if (CurVariant == -1)
336 OS << '}'; // this is gcc's behavior for } outside a variant
343 bool HasCurlyBraces = false;
344 if (*LastEmitted == '{') { // ${variable}
345 ++LastEmitted; // Consume '{' character.
346 HasCurlyBraces = true;
349 // If we have ${:foo}, then this is not a real operand reference, it is a
350 // "magic" string reference, just like in .td files. Arrange to call
352 if (HasCurlyBraces && *LastEmitted == ':') {
354 const char *StrStart = LastEmitted;
355 const char *StrEnd = strchr(StrStart, '}');
357 report_fatal_error("Unterminated ${:foo} operand in inline asm"
358 " string: '" + Twine(AsmStr) + "'");
360 std::string Val(StrStart, StrEnd);
361 AP->PrintSpecial(MI, OS, Val.c_str());
362 LastEmitted = StrEnd+1;
366 const char *IDStart = LastEmitted;
367 const char *IDEnd = IDStart;
368 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
371 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
372 report_fatal_error("Bad $ operand number in inline asm string: '" +
373 Twine(AsmStr) + "'");
376 char Modifier[2] = { 0, 0 };
378 if (HasCurlyBraces) {
379 // If we have curly braces, check for a modifier character. This
380 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
381 if (*LastEmitted == ':') {
382 ++LastEmitted; // Consume ':' character.
383 if (*LastEmitted == 0)
384 report_fatal_error("Bad ${:} expression in inline asm string: '" +
385 Twine(AsmStr) + "'");
387 Modifier[0] = *LastEmitted;
388 ++LastEmitted; // Consume modifier character.
391 if (*LastEmitted != '}')
392 report_fatal_error("Bad ${} expression in inline asm string: '" +
393 Twine(AsmStr) + "'");
394 ++LastEmitted; // Consume '}' character.
397 if (Val >= NumOperands-1)
398 report_fatal_error("Invalid $ operand number in inline asm string: '" +
399 Twine(AsmStr) + "'");
401 // Okay, we finally have a value number. Ask the target to print this
403 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
404 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
408 // Scan to find the machine operand number for the operand.
410 if (OpNo >= MI->getNumOperands()) break;
411 unsigned OpFlags = MI->getOperand(OpNo).getImm();
412 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
415 // We may have a location metadata attached to the end of the
416 // instruction, and at no point should see metadata at any
417 // other point while processing. It's an error if so.
418 if (OpNo >= MI->getNumOperands() ||
419 MI->getOperand(OpNo).isMetadata()) {
422 unsigned OpFlags = MI->getOperand(OpNo).getImm();
423 ++OpNo; // Skip over the ID number.
425 if (Modifier[0] == 'l') { // Labels are target independent.
426 // FIXME: What if the operand isn't an MBB, report error?
427 const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
428 Sym->print(OS, AP->MAI);
430 if (InlineAsm::isMemKind(OpFlags)) {
431 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
432 Modifier[0] ? Modifier : nullptr,
435 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
436 Modifier[0] ? Modifier : nullptr, OS);
442 raw_string_ostream Msg(msg);
443 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
444 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
451 OS << '\n' << (char)0; // null terminate string.
454 /// EmitInlineAsm - This method formats and emits the specified machine
455 /// instruction that is an inline asm.
456 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
457 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
459 // Count the number of register definitions to find the asm string.
460 unsigned NumDefs = 0;
461 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
463 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
465 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
467 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
468 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
470 // If this asmstr is empty, just print the #APP/#NOAPP markers.
471 // These are useful to see where empty asm's wound up.
472 if (AsmStr[0] == 0) {
473 OutStreamer->emitRawComment(MAI->getInlineAsmStart());
474 OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
478 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
479 // enabled, so we use emitRawComment.
480 OutStreamer->emitRawComment(MAI->getInlineAsmStart());
482 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
484 unsigned LocCookie = 0;
485 const MDNode *LocMD = nullptr;
486 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
487 if (MI->getOperand(i-1).isMetadata() &&
488 (LocMD = MI->getOperand(i-1).getMetadata()) &&
489 LocMD->getNumOperands() != 0) {
490 if (const ConstantInt *CI =
491 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
492 LocCookie = CI->getZExtValue();
498 // Emit the inline asm to a temporary string so we can emit it through
500 SmallString<256> StringData;
501 raw_svector_ostream OS(StringData);
503 // The variant of the current asmprinter.
504 int AsmPrinterVariant = MAI->getAssemblerDialect();
505 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
506 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
507 if (InlineAsmVariant == InlineAsm::AD_ATT)
508 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
511 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
513 // Reset SanitizeAddress based on the function's attribute.
514 MCTargetOptions MCOptions = TM.Options.MCOptions;
515 MCOptions.SanitizeAddress =
516 MF->getFunction()->hasFnAttribute(Attribute::SanitizeAddress);
518 EmitInlineAsm(OS.str(), getSubtargetInfo(), MCOptions, LocMD,
519 MI->getInlineAsmDialect());
521 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
522 // enabled, so we use emitRawComment.
523 OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
527 /// PrintSpecial - Print information related to the specified machine instr
528 /// that is independent of the operand, and may be independent of the instr
529 /// itself. This can be useful for portably encoding the comment character
530 /// or other bits of target-specific knowledge into the asmstrings. The
531 /// syntax used is ${:comment}. Targets can override this to add support
532 /// for their own strange codes.
533 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
534 const char *Code) const {
535 if (!strcmp(Code, "private")) {
536 const DataLayout &DL = MF->getDataLayout();
537 OS << DL.getPrivateGlobalPrefix();
538 } else if (!strcmp(Code, "comment")) {
539 OS << MAI->getCommentString();
540 } else if (!strcmp(Code, "uid")) {
541 // Comparing the address of MI isn't sufficient, because machineinstrs may
542 // be allocated to the same address across functions.
544 // If this is a new LastFn instruction, bump the counter.
545 if (LastMI != MI || LastFn != getFunctionNumber()) {
548 LastFn = getFunctionNumber();
553 raw_string_ostream Msg(msg);
554 Msg << "Unknown special formatter '" << Code
555 << "' for machine instr: " << *MI;
556 report_fatal_error(Msg.str());
560 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
561 /// instruction, using the specified assembler variant. Targets should
562 /// override this to format as appropriate.
563 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
564 unsigned AsmVariant, const char *ExtraCode,
566 // Does this asm operand have a single letter operand modifier?
567 if (ExtraCode && ExtraCode[0]) {
568 if (ExtraCode[1] != 0) return true; // Unknown modifier.
570 const MachineOperand &MO = MI->getOperand(OpNo);
571 switch (ExtraCode[0]) {
573 return true; // Unknown modifier.
574 case 'c': // Substitute immediate value without immediate syntax
575 if (MO.getType() != MachineOperand::MO_Immediate)
579 case 'n': // Negate the immediate constant.
580 if (MO.getType() != MachineOperand::MO_Immediate)
584 case 's': // The GCC deprecated s modifier
585 if (MO.getType() != MachineOperand::MO_Immediate)
587 O << ((32 - MO.getImm()) & 31);
594 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
596 const char *ExtraCode, raw_ostream &O) {
597 // Target doesn't support this yet!
601 void AsmPrinter::emitInlineAsmStart() const {}
603 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
604 const MCSubtargetInfo *EndInfo) const {}