LLVM  10.0.0
AsmPrinterInlineAsm.cpp
Go to the documentation of this file.
1 //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the inline assembler pieces of the AsmPrinter class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/Twine.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/SourceMgr.h"
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "asm-printer"
40 
41 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
42 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
43 /// struct above.
44 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
45  AsmPrinter::SrcMgrDiagInfo *DiagInfo =
46  static_cast<AsmPrinter::SrcMgrDiagInfo *>(diagInfo);
47  assert(DiagInfo && "Diagnostic context not passed down?");
48 
49  // Look up a LocInfo for the buffer this diagnostic is coming from.
50  unsigned BufNum = DiagInfo->SrcMgr.FindBufferContainingLoc(Diag.getLoc());
51  const MDNode *LocInfo = nullptr;
52  if (BufNum > 0 && BufNum <= DiagInfo->LocInfos.size())
53  LocInfo = DiagInfo->LocInfos[BufNum-1];
54 
55  // If the inline asm had metadata associated with it, pull out a location
56  // cookie corresponding to which line the error occurred on.
57  unsigned LocCookie = 0;
58  if (LocInfo) {
59  unsigned ErrorLine = Diag.getLineNo()-1;
60  if (ErrorLine >= LocInfo->getNumOperands())
61  ErrorLine = 0;
62 
63  if (LocInfo->getNumOperands() != 0)
64  if (const ConstantInt *CI =
65  mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
66  LocCookie = CI->getZExtValue();
67  }
68 
69  DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
70 }
71 
72 unsigned AsmPrinter::addInlineAsmDiagBuffer(StringRef AsmStr,
73  const MDNode *LocMDNode) const {
74  if (!DiagInfo) {
75  DiagInfo = std::make_unique<SrcMgrDiagInfo>();
76 
78  Context.setInlineSourceManager(&DiagInfo->SrcMgr);
79 
80  LLVMContext &LLVMCtx = MMI->getModule()->getContext();
81  if (LLVMCtx.getInlineAsmDiagnosticHandler()) {
82  DiagInfo->DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
83  DiagInfo->DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
84  DiagInfo->SrcMgr.setDiagHandler(srcMgrDiagHandler, DiagInfo.get());
85  }
86  }
87 
88  SourceMgr &SrcMgr = DiagInfo->SrcMgr;
89 
90  std::unique_ptr<MemoryBuffer> Buffer;
91  // The inline asm source manager will outlive AsmStr, so make a copy of the
92  // string for SourceMgr to own.
93  Buffer = MemoryBuffer::getMemBufferCopy(AsmStr, "<inline asm>");
94 
95  // Tell SrcMgr about this buffer, it takes ownership of the buffer.
96  unsigned BufNum = SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
97 
98  // Store LocMDNode in DiagInfo, using BufNum as an identifier.
99  if (LocMDNode) {
100  DiagInfo->LocInfos.resize(BufNum);
101  DiagInfo->LocInfos[BufNum - 1] = LocMDNode;
102  }
103 
104  return BufNum;
105 }
106 
107 
108 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
109 void AsmPrinter::EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
110  const MCTargetOptions &MCOptions,
111  const MDNode *LocMDNode,
112  InlineAsm::AsmDialect Dialect) const {
113  assert(!Str.empty() && "Can't emit empty inline asm block");
114 
115  // Remember if the buffer is nul terminated or not so we can avoid a copy.
116  bool isNullTerminated = Str.back() == 0;
117  if (isNullTerminated)
118  Str = Str.substr(0, Str.size()-1);
119 
120  // If the output streamer does not have mature MC support or the integrated
121  // assembler has been disabled, just emit the blob textually.
122  // Otherwise parse the asm and emit it via MC support.
123  // This is useful in case the asm parser doesn't handle something but the
124  // system assembler does.
125  const MCAsmInfo *MCAI = TM.getMCAsmInfo();
126  assert(MCAI && "No MCAsmInfo");
127  if (!MCAI->useIntegratedAssembler() &&
128  !OutStreamer->isIntegratedAssemblerRequired()) {
130  OutStreamer->EmitRawText(Str);
131  emitInlineAsmEnd(STI, nullptr);
132  return;
133  }
134 
135  unsigned BufNum = addInlineAsmDiagBuffer(Str, LocMDNode);
136  DiagInfo->SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths);
137 
138  std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(
139  DiagInfo->SrcMgr, OutContext, *OutStreamer, *MAI, BufNum));
140 
141  // Do not use assembler-level information for parsing inline assembly.
142  OutStreamer->setUseAssemblerInfoForParsing(false);
143 
144  // We create a new MCInstrInfo here since we might be at the module level
145  // and not have a MachineFunction to initialize the TargetInstrInfo from and
146  // we only need MCInstrInfo for asm parsing. We create one unconditionally
147  // because it's not subtarget dependent.
148  std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
149  std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
150  STI, *Parser, *MII, MCOptions));
151  if (!TAP)
152  report_fatal_error("Inline asm not supported by this streamer because"
153  " we don't have an asm parser for this target\n");
154  Parser->setAssemblerDialect(Dialect);
155  Parser->setTargetParser(*TAP.get());
156  // Enable lexing Masm binary and hex integer literals in intel inline
157  // assembly.
158  if (Dialect == InlineAsm::AD_Intel)
159  Parser->getLexer().setLexMasmIntegers(true);
160 
162  // Don't implicitly switch to the text section before the asm.
163  int Res = Parser->Run(/*NoInitialTextSection*/ true,
164  /*NoFinalize*/ true);
165  emitInlineAsmEnd(STI, &TAP->getSTI());
166 
167  if (Res && !DiagInfo->DiagHandler)
168  report_fatal_error("Error parsing inline asm\n");
169 }
170 
171 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
173  unsigned LocCookie, raw_ostream &OS) {
174  // Switch to the inline assembly variant.
175  OS << "\t.intel_syntax\n\t";
176 
177  const char *LastEmitted = AsmStr; // One past the last character emitted.
178  unsigned NumOperands = MI->getNumOperands();
179 
180  while (*LastEmitted) {
181  switch (*LastEmitted) {
182  default: {
183  // Not a special case, emit the string section literally.
184  const char *LiteralEnd = LastEmitted+1;
185  while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
186  *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
187  ++LiteralEnd;
188 
189  OS.write(LastEmitted, LiteralEnd-LastEmitted);
190  LastEmitted = LiteralEnd;
191  break;
192  }
193  case '\n':
194  ++LastEmitted; // Consume newline character.
195  OS << '\n'; // Indent code with newline.
196  break;
197  case '$': {
198  ++LastEmitted; // Consume '$' character.
199  bool Done = true;
200 
201  // Handle escapes.
202  switch (*LastEmitted) {
203  default: Done = false; break;
204  case '$':
205  ++LastEmitted; // Consume second '$' character.
206  break;
207  }
208  if (Done) break;
209 
210  bool HasCurlyBraces = false;
211  if (*LastEmitted == '{') { // ${variable}
212  ++LastEmitted; // Consume '{' character.
213  HasCurlyBraces = true;
214  }
215 
216  // If we have ${:foo}, then this is not a real operand reference, it is a
217  // "magic" string reference, just like in .td files. Arrange to call
218  // PrintSpecial.
219  if (HasCurlyBraces && LastEmitted[0] == ':') {
220  ++LastEmitted;
221  const char *StrStart = LastEmitted;
222  const char *StrEnd = strchr(StrStart, '}');
223  if (!StrEnd)
224  report_fatal_error("Unterminated ${:foo} operand in inline asm"
225  " string: '" + Twine(AsmStr) + "'");
226 
227  std::string Val(StrStart, StrEnd);
228  AP->PrintSpecial(MI, OS, Val.c_str());
229  LastEmitted = StrEnd+1;
230  break;
231  }
232 
233  const char *IDStart = LastEmitted;
234  const char *IDEnd = IDStart;
235  while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
236 
237  unsigned Val;
238  if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
239  report_fatal_error("Bad $ operand number in inline asm string: '" +
240  Twine(AsmStr) + "'");
241  LastEmitted = IDEnd;
242 
243  if (Val >= NumOperands-1)
244  report_fatal_error("Invalid $ operand number in inline asm string: '" +
245  Twine(AsmStr) + "'");
246 
247  char Modifier[2] = { 0, 0 };
248 
249  if (HasCurlyBraces) {
250  // If we have curly braces, check for a modifier character. This
251  // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
252  if (*LastEmitted == ':') {
253  ++LastEmitted; // Consume ':' character.
254  if (*LastEmitted == 0)
255  report_fatal_error("Bad ${:} expression in inline asm string: '" +
256  Twine(AsmStr) + "'");
257 
258  Modifier[0] = *LastEmitted;
259  ++LastEmitted; // Consume modifier character.
260  }
261 
262  if (*LastEmitted != '}')
263  report_fatal_error("Bad ${} expression in inline asm string: '" +
264  Twine(AsmStr) + "'");
265  ++LastEmitted; // Consume '}' character.
266  }
267 
268  // Okay, we finally have a value number. Ask the target to print this
269  // operand!
270  unsigned OpNo = InlineAsm::MIOp_FirstOperand;
271 
272  bool Error = false;
273 
274  // Scan to find the machine operand number for the operand.
275  for (; Val; --Val) {
276  if (OpNo >= MI->getNumOperands()) break;
277  unsigned OpFlags = MI->getOperand(OpNo).getImm();
278  OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
279  }
280 
281  // We may have a location metadata attached to the end of the
282  // instruction, and at no point should see metadata at any
283  // other point while processing. It's an error if so.
284  if (OpNo >= MI->getNumOperands() ||
285  MI->getOperand(OpNo).isMetadata()) {
286  Error = true;
287  } else {
288  unsigned OpFlags = MI->getOperand(OpNo).getImm();
289  ++OpNo; // Skip over the ID number.
290 
291  if (InlineAsm::isMemKind(OpFlags)) {
292  Error = AP->PrintAsmMemoryOperand(
293  MI, OpNo, Modifier[0] ? Modifier : nullptr, OS);
294  } else {
295  Error = AP->PrintAsmOperand(MI, OpNo,
296  Modifier[0] ? Modifier : nullptr, OS);
297  }
298  }
299  if (Error) {
300  std::string msg;
301  raw_string_ostream Msg(msg);
302  Msg << "invalid operand in inline asm: '" << AsmStr << "'";
303  MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
304  }
305  break;
306  }
307  }
308  }
309  OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
310 }
311 
312 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
313  MachineModuleInfo *MMI, int AsmPrinterVariant,
314  AsmPrinter *AP, unsigned LocCookie,
315  raw_ostream &OS) {
316  int CurVariant = -1; // The number of the {.|.|.} region we are in.
317  const char *LastEmitted = AsmStr; // One past the last character emitted.
318  unsigned NumOperands = MI->getNumOperands();
319 
320  OS << '\t';
321 
322  while (*LastEmitted) {
323  switch (*LastEmitted) {
324  default: {
325  // Not a special case, emit the string section literally.
326  const char *LiteralEnd = LastEmitted+1;
327  while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
328  *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
329  ++LiteralEnd;
330  if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
331  OS.write(LastEmitted, LiteralEnd-LastEmitted);
332  LastEmitted = LiteralEnd;
333  break;
334  }
335  case '\n':
336  ++LastEmitted; // Consume newline character.
337  OS << '\n'; // Indent code with newline.
338  break;
339  case '$': {
340  ++LastEmitted; // Consume '$' character.
341  bool Done = true;
342 
343  // Handle escapes.
344  switch (*LastEmitted) {
345  default: Done = false; break;
346  case '$': // $$ -> $
347  if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
348  OS << '$';
349  ++LastEmitted; // Consume second '$' character.
350  break;
351  case '(': // $( -> same as GCC's { character.
352  ++LastEmitted; // Consume '(' character.
353  if (CurVariant != -1)
354  report_fatal_error("Nested variants found in inline asm string: '" +
355  Twine(AsmStr) + "'");
356  CurVariant = 0; // We're in the first variant now.
357  break;
358  case '|':
359  ++LastEmitted; // consume '|' character.
360  if (CurVariant == -1)
361  OS << '|'; // this is gcc's behavior for | outside a variant
362  else
363  ++CurVariant; // We're in the next variant.
364  break;
365  case ')': // $) -> same as GCC's } char.
366  ++LastEmitted; // consume ')' character.
367  if (CurVariant == -1)
368  OS << '}'; // this is gcc's behavior for } outside a variant
369  else
370  CurVariant = -1;
371  break;
372  }
373  if (Done) break;
374 
375  bool HasCurlyBraces = false;
376  if (*LastEmitted == '{') { // ${variable}
377  ++LastEmitted; // Consume '{' character.
378  HasCurlyBraces = true;
379  }
380 
381  // If we have ${:foo}, then this is not a real operand reference, it is a
382  // "magic" string reference, just like in .td files. Arrange to call
383  // PrintSpecial.
384  if (HasCurlyBraces && *LastEmitted == ':') {
385  ++LastEmitted;
386  const char *StrStart = LastEmitted;
387  const char *StrEnd = strchr(StrStart, '}');
388  if (!StrEnd)
389  report_fatal_error("Unterminated ${:foo} operand in inline asm"
390  " string: '" + Twine(AsmStr) + "'");
391 
392  std::string Val(StrStart, StrEnd);
393  AP->PrintSpecial(MI, OS, Val.c_str());
394  LastEmitted = StrEnd+1;
395  break;
396  }
397 
398  const char *IDStart = LastEmitted;
399  const char *IDEnd = IDStart;
400  while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
401 
402  unsigned Val;
403  if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
404  report_fatal_error("Bad $ operand number in inline asm string: '" +
405  Twine(AsmStr) + "'");
406  LastEmitted = IDEnd;
407 
408  char Modifier[2] = { 0, 0 };
409 
410  if (HasCurlyBraces) {
411  // If we have curly braces, check for a modifier character. This
412  // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
413  if (*LastEmitted == ':') {
414  ++LastEmitted; // Consume ':' character.
415  if (*LastEmitted == 0)
416  report_fatal_error("Bad ${:} expression in inline asm string: '" +
417  Twine(AsmStr) + "'");
418 
419  Modifier[0] = *LastEmitted;
420  ++LastEmitted; // Consume modifier character.
421  }
422 
423  if (*LastEmitted != '}')
424  report_fatal_error("Bad ${} expression in inline asm string: '" +
425  Twine(AsmStr) + "'");
426  ++LastEmitted; // Consume '}' character.
427  }
428 
429  if (Val >= NumOperands-1)
430  report_fatal_error("Invalid $ operand number in inline asm string: '" +
431  Twine(AsmStr) + "'");
432 
433  // Okay, we finally have a value number. Ask the target to print this
434  // operand!
435  if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
436  unsigned OpNo = InlineAsm::MIOp_FirstOperand;
437 
438  bool Error = false;
439 
440  // Scan to find the machine operand number for the operand.
441  for (; Val; --Val) {
442  if (OpNo >= MI->getNumOperands()) break;
443  unsigned OpFlags = MI->getOperand(OpNo).getImm();
444  OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
445  }
446 
447  // We may have a location metadata attached to the end of the
448  // instruction, and at no point should see metadata at any
449  // other point while processing. It's an error if so.
450  if (OpNo >= MI->getNumOperands() ||
451  MI->getOperand(OpNo).isMetadata()) {
452  Error = true;
453  } else {
454  unsigned OpFlags = MI->getOperand(OpNo).getImm();
455  ++OpNo; // Skip over the ID number.
456 
457  // FIXME: Shouldn't arch-independent output template handling go into
458  // PrintAsmOperand?
459  // Labels are target independent.
460  if (MI->getOperand(OpNo).isBlockAddress()) {
461  const BlockAddress *BA = MI->getOperand(OpNo).getBlockAddress();
462  MCSymbol *Sym = AP->GetBlockAddressSymbol(BA);
463  Sym->print(OS, AP->MAI);
465  } else if (MI->getOperand(OpNo).isMBB()) {
466  const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
467  Sym->print(OS, AP->MAI);
468  } else if (Modifier[0] == 'l') {
469  Error = true;
470  } else if (InlineAsm::isMemKind(OpFlags)) {
471  Error = AP->PrintAsmMemoryOperand(
472  MI, OpNo, Modifier[0] ? Modifier : nullptr, OS);
473  } else {
474  Error = AP->PrintAsmOperand(MI, OpNo,
475  Modifier[0] ? Modifier : nullptr, OS);
476  }
477  }
478  if (Error) {
479  std::string msg;
480  raw_string_ostream Msg(msg);
481  Msg << "invalid operand in inline asm: '" << AsmStr << "'";
482  MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
483  }
484  }
485  break;
486  }
487  }
488  }
489  OS << '\n' << (char)0; // null terminate string.
490 }
491 
492 /// EmitInlineAsm - This method formats and emits the specified machine
493 /// instruction that is an inline asm.
494 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
495  assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
496 
497  // Count the number of register definitions to find the asm string.
498  unsigned NumDefs = 0;
499  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
500  ++NumDefs)
501  assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
502 
503  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
504 
505  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
506  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
507 
508  // If this asmstr is empty, just print the #APP/#NOAPP markers.
509  // These are useful to see where empty asm's wound up.
510  if (AsmStr[0] == 0) {
511  OutStreamer->emitRawComment(MAI->getInlineAsmStart());
512  OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
513  return;
514  }
515 
516  // Emit the #APP start marker. This has to happen even if verbose-asm isn't
517  // enabled, so we use emitRawComment.
518  OutStreamer->emitRawComment(MAI->getInlineAsmStart());
519 
520  // Get the !srcloc metadata node if we have it, and decode the loc cookie from
521  // it.
522  unsigned LocCookie = 0;
523  const MDNode *LocMD = nullptr;
524  for (unsigned i = MI->getNumOperands(); i != 0; --i) {
525  if (MI->getOperand(i-1).isMetadata() &&
526  (LocMD = MI->getOperand(i-1).getMetadata()) &&
527  LocMD->getNumOperands() != 0) {
528  if (const ConstantInt *CI =
529  mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
530  LocCookie = CI->getZExtValue();
531  break;
532  }
533  }
534  }
535 
536  // Emit the inline asm to a temporary string so we can emit it through
537  // EmitInlineAsm.
538  SmallString<256> StringData;
539  raw_svector_ostream OS(StringData);
540 
541  // The variant of the current asmprinter.
542  int AsmPrinterVariant = MAI->getAssemblerDialect();
543  AsmPrinter *AP = const_cast<AsmPrinter*>(this);
545  EmitGCCInlineAsmStr(AsmStr, MI, MMI, AsmPrinterVariant, AP, LocCookie, OS);
546  else
547  EmitMSInlineAsmStr(AsmStr, MI, MMI, AP, LocCookie, OS);
548 
549  // Emit warnings if we use reserved registers on the clobber list, as
550  // that might give surprising results.
551  std::vector<std::string> RestrRegs;
552  // Start with the first operand descriptor, and iterate over them.
553  for (unsigned I = InlineAsm::MIOp_FirstOperand, NumOps = MI->getNumOperands();
554  I < NumOps; ++I) {
555  const MachineOperand &MO = MI->getOperand(I);
556  if (MO.isImm()) {
557  unsigned Flags = MO.getImm();
560  !TRI->isAsmClobberable(*MF, MI->getOperand(I + 1).getReg())) {
561  RestrRegs.push_back(TRI->getName(MI->getOperand(I + 1).getReg()));
562  }
563  // Skip to one before the next operand descriptor, if it exists.
565  }
566  }
567 
568  if (!RestrRegs.empty()) {
569  unsigned BufNum = addInlineAsmDiagBuffer(OS.str(), LocMD);
570  auto &SrcMgr = DiagInfo->SrcMgr;
572  SrcMgr.getMemoryBuffer(BufNum)->getBuffer().begin());
573 
574  std::string Msg = "inline asm clobber list contains reserved registers: ";
575  for (auto I = RestrRegs.begin(), E = RestrRegs.end(); I != E; I++) {
576  if(I != RestrRegs.begin())
577  Msg += ", ";
578  Msg += *I;
579  }
580  std::string Note = "Reserved registers on the clobber list may not be "
581  "preserved across the asm statement, and clobbering them may "
582  "lead to undefined behaviour.";
583  SrcMgr.PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
584  SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note, Note);
585  }
586 
587  EmitInlineAsm(OS.str(), getSubtargetInfo(), TM.Options.MCOptions, LocMD,
588  MI->getInlineAsmDialect());
589 
590  // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
591  // enabled, so we use emitRawComment.
592  OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
593 }
594 
595 
596 /// PrintSpecial - Print information related to the specified machine instr
597 /// that is independent of the operand, and may be independent of the instr
598 /// itself. This can be useful for portably encoding the comment character
599 /// or other bits of target-specific knowledge into the asmstrings. The
600 /// syntax used is ${:comment}. Targets can override this to add support
601 /// for their own strange codes.
603  const char *Code) const {
604  if (!strcmp(Code, "private")) {
605  const DataLayout &DL = MF->getDataLayout();
606  OS << DL.getPrivateGlobalPrefix();
607  } else if (!strcmp(Code, "comment")) {
608  OS << MAI->getCommentString();
609  } else if (!strcmp(Code, "uid")) {
610  // Comparing the address of MI isn't sufficient, because machineinstrs may
611  // be allocated to the same address across functions.
612 
613  // If this is a new LastFn instruction, bump the counter.
614  if (LastMI != MI || LastFn != getFunctionNumber()) {
615  ++Counter;
616  LastMI = MI;
617  LastFn = getFunctionNumber();
618  }
619  OS << Counter;
620  } else {
621  std::string msg;
622  raw_string_ostream Msg(msg);
623  Msg << "Unknown special formatter '" << Code
624  << "' for machine instr: " << *MI;
625  report_fatal_error(Msg.str());
626  }
627 }
628 
630  assert(MO.isGlobal() && "caller should check MO.isGlobal");
631  getSymbol(MO.getGlobal())->print(OS, MAI);
632  printOffset(MO.getOffset(), OS);
633 }
634 
635 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
636 /// instruction, using the specified assembler variant. Targets should
637 /// override this to format as appropriate for machine specific ExtraCodes
638 /// or when the arch-independent handling would be too complex otherwise.
639 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
640  const char *ExtraCode, raw_ostream &O) {
641  // Does this asm operand have a single letter operand modifier?
642  if (ExtraCode && ExtraCode[0]) {
643  if (ExtraCode[1] != 0) return true; // Unknown modifier.
644 
645  // https://gcc.gnu.org/onlinedocs/gccint/Output-Template.html
646  const MachineOperand &MO = MI->getOperand(OpNo);
647  switch (ExtraCode[0]) {
648  default:
649  return true; // Unknown modifier.
650  case 'a': // Print as memory address.
651  if (MO.isReg()) {
652  PrintAsmMemoryOperand(MI, OpNo, nullptr, O);
653  return false;
654  }
655  LLVM_FALLTHROUGH; // GCC allows '%a' to behave like '%c' with immediates.
656  case 'c': // Substitute immediate value without immediate syntax
657  if (MO.isImm()) {
658  O << MO.getImm();
659  return false;
660  }
661  if (MO.isGlobal()) {
662  PrintSymbolOperand(MO, O);
663  return false;
664  }
665  return true;
666  case 'n': // Negate the immediate constant.
667  if (!MO.isImm())
668  return true;
669  O << -MO.getImm();
670  return false;
671  case 's': // The GCC deprecated s modifier
672  if (!MO.isImm())
673  return true;
674  O << ((32 - MO.getImm()) & 31);
675  return false;
676  }
677  }
678  return true;
679 }
680 
681 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
682  const char *ExtraCode, raw_ostream &O) {
683  // Target doesn't support this yet!
684  return true;
685 }
686 
688 
690  const MCSubtargetInfo *EndInfo) const {}
virtual void emitInlineAsmStart() const
Let the target do anything it needs to do before emitting inlineasm.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
const char * getInlineAsmStart() const
Definition: MCAsmInfo.h:528
unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition: SourceMgr.cpp:61
LLVMContext & Context
MachineBasicBlock * getMBB() const
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:95
MCTargetOptions MCOptions
Machine level options.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
SMLoc getLoc() const
Definition: SourceMgr.h:287
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:320
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
std::vector< std::string > IASSearchPaths
Additional paths to search for .include directives when using the integrated assembler.
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:90
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:228
SourceMgr SrcMgr
Definition: Error.cpp:23
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
bool isInlineAsm() const
void * getInlineAsmDiagnosticContext() const
getInlineAsmDiagnosticContext - Return the diagnostic context set by setInlineAsmDiagnosticHandler.
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:543
bool isMetadata() const
isMetadata - Tests if this is a MO_Metadata operand.
unsigned const TargetRegisterInfo * TRI
Metadata node.
Definition: Metadata.h:872
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:98
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1077
const char * getInlineAsmEnd() const
Definition: MCAsmInfo.h:529
LLVMContext::InlineAsmDiagHandlerTy DiagHandler
Definition: AsmPrinter.h:177
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI, MachineModuleInfo *MMI, int AsmPrinterVariant, AsmPrinter *AP, unsigned LocCookie, raw_ostream &OS)
MCAsmParser * createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &, const MCAsmInfo &, unsigned CB=0)
Create an MCAsmParser instance.
Definition: AsmParser.cpp:6108
The address of a basic block.
Definition: Constants.h:840
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:429
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:245
int getLineNo() const
Definition: SourceMgr.h:289
static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI, MachineModuleInfo *MMI, AsmPrinter *AP, unsigned LocCookie, raw_ostream &OS)
const char * getSymbolName() const
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:600
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
Context object for machine code objects.
Definition: MCContext.h:65
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
const MCContext & getContext() const
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:153
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:151
void printOffset(int64_t Offset, raw_ostream &OS) const
This is just convenient handler for printing offsets.
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:101
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
void setInlineSourceManager(SourceMgr *SM)
Definition: MCContext.h:316
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:86
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:533
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const GlobalValue * getGlobal() const
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:83
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:80
static unsigned getNumOperandRegisters(unsigned Flag)
getNumOperandRegisters - Extract the number of registers field from the inline asm operand flag...
Definition: InlineAsm.h:336
StringRef getCommentString() const
Definition: MCAsmInfo.h:510
static unsigned getKind(unsigned Flags)
Definition: InlineAsm.h:325
static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo)
srcMgrDiagHandler - This callback is invoked when the SourceMgr for an inline asm has an error in it...
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:41
const Target & getTarget() const
static bool isMemKind(unsigned Flag)
Definition: InlineAsm.h:277
MCTargetAsmParser * createMCAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser, const MCInstrInfo &MII, const MCTargetOptions &Options) const
createMCAsmParser - Create a target specific assembly parser.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_NODISCARD char back() const
back - Get the last character in the string.
Definition: StringRef.h:162
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:532
raw_ostream & write(unsigned char C)
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:499
void registerInlineAsmLabel(MCSymbol *Sym)
registerInlineAsmLabel - Records that the name is a label referenced in inline assembly.
Definition: MCContext.cpp:278
unsigned getFunctionNumber() const
Return a unique ID for the current function.
Definition: AsmPrinter.cpp:210
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
InlineAsm::AsmDialect getInlineAsmDialect() const
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:449
MachineOperand class - Representation of each machine instruction operand.
Module.h This file contains the declarations for the Module class.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, const MCSubtargetInfo *EndInfo) const
Let the target do anything it needs to do after emitting inlineasm.
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:568
int64_t getImm() const
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it...
const char * getName(MCRegister RegNo) const
Return the human-readable symbolic target-specific name for the specified physical register...
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
bool useIntegratedAssembler() const
Return true if assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:640
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
Representation of each machine instruction.
Definition: MachineInstr.h:63
TargetOptions Options
int64_t getOffset() const
Return the offset from the symbol in this operand.
const BlockAddress * getBlockAddress() const
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
#define I(x, y, z)
Definition: MD5.cpp:58
Generic base class for all target subtargets.
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:128
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const
getInlineAsmDiagnosticHandler - Return the diagnostic handler set by setInlineAsmDiagnosticHandler.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
const Module * getModule() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:516
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:279
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
Register getReg() const
getReg - Returns the register number.
virtual bool isAsmClobberable(const MachineFunction &MF, unsigned PhysReg) const
Returns false if we can&#39;t guarantee that Physreg, specified as an IR asm clobber constraint, will be preserved across the statement.
std::vector< const MDNode * > LocInfos
Definition: AsmPrinter.h:176
Represents a location in source code.
Definition: SMLoc.h:23
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1083
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS, const char *Code) const
Print information related to the specified machine instr that is independent of the operand...
const MDNode * getMetadata() const
This class contains meta information specific to a module.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:261
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:59