LLVM  9.0.0svn
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 = 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  if (MF) {
162  TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
163  }
164 
166  // Don't implicitly switch to the text section before the asm.
167  int Res = Parser->Run(/*NoInitialTextSection*/ true,
168  /*NoFinalize*/ true);
169  emitInlineAsmEnd(STI, &TAP->getSTI());
170 
171  if (Res && !DiagInfo->DiagHandler)
172  report_fatal_error("Error parsing inline asm\n");
173 }
174 
175 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
176  MachineModuleInfo *MMI, int InlineAsmVariant,
177  AsmPrinter *AP, unsigned LocCookie,
178  raw_ostream &OS) {
179  // Switch to the inline assembly variant.
180  OS << "\t.intel_syntax\n\t";
181 
182  const char *LastEmitted = AsmStr; // One past the last character emitted.
183  unsigned NumOperands = MI->getNumOperands();
184 
185  while (*LastEmitted) {
186  switch (*LastEmitted) {
187  default: {
188  // Not a special case, emit the string section literally.
189  const char *LiteralEnd = LastEmitted+1;
190  while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
191  *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
192  ++LiteralEnd;
193 
194  OS.write(LastEmitted, LiteralEnd-LastEmitted);
195  LastEmitted = LiteralEnd;
196  break;
197  }
198  case '\n':
199  ++LastEmitted; // Consume newline character.
200  OS << '\n'; // Indent code with newline.
201  break;
202  case '$': {
203  ++LastEmitted; // Consume '$' character.
204  bool Done = true;
205 
206  // Handle escapes.
207  switch (*LastEmitted) {
208  default: Done = false; break;
209  case '$':
210  ++LastEmitted; // Consume second '$' character.
211  break;
212  }
213  if (Done) break;
214 
215  // If we have ${:foo}, then this is not a real operand reference, it is a
216  // "magic" string reference, just like in .td files. Arrange to call
217  // PrintSpecial.
218  if (LastEmitted[0] == '{' && LastEmitted[1] == ':') {
219  LastEmitted += 2;
220  const char *StrStart = LastEmitted;
221  const char *StrEnd = strchr(StrStart, '}');
222  if (!StrEnd)
223  report_fatal_error("Unterminated ${:foo} operand in inline asm"
224  " string: '" + Twine(AsmStr) + "'");
225 
226  std::string Val(StrStart, StrEnd);
227  AP->PrintSpecial(MI, OS, Val.c_str());
228  LastEmitted = StrEnd+1;
229  break;
230  }
231 
232  const char *IDStart = LastEmitted;
233  const char *IDEnd = IDStart;
234  while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
235 
236  unsigned Val;
237  if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
238  report_fatal_error("Bad $ operand number in inline asm string: '" +
239  Twine(AsmStr) + "'");
240  LastEmitted = IDEnd;
241 
242  if (Val >= NumOperands-1)
243  report_fatal_error("Invalid $ operand number in inline asm string: '" +
244  Twine(AsmStr) + "'");
245 
246  // Okay, we finally have a value number. Ask the target to print this
247  // operand!
248  unsigned OpNo = InlineAsm::MIOp_FirstOperand;
249 
250  bool Error = false;
251 
252  // Scan to find the machine operand number for the operand.
253  for (; Val; --Val) {
254  if (OpNo >= MI->getNumOperands()) break;
255  unsigned OpFlags = MI->getOperand(OpNo).getImm();
256  OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
257  }
258 
259  // We may have a location metadata attached to the end of the
260  // instruction, and at no point should see metadata at any
261  // other point while processing. It's an error if so.
262  if (OpNo >= MI->getNumOperands() ||
263  MI->getOperand(OpNo).isMetadata()) {
264  Error = true;
265  } else {
266  unsigned OpFlags = MI->getOperand(OpNo).getImm();
267  ++OpNo; // Skip over the ID number.
268 
269  if (InlineAsm::isMemKind(OpFlags)) {
270  Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
271  /*Modifier*/ nullptr, OS);
272  } else {
273  Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
274  /*Modifier*/ nullptr, OS);
275  }
276  }
277  if (Error) {
278  std::string msg;
279  raw_string_ostream Msg(msg);
280  Msg << "invalid operand in inline asm: '" << AsmStr << "'";
281  MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
282  }
283  break;
284  }
285  }
286  }
287  OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
288 }
289 
290 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
291  MachineModuleInfo *MMI, int InlineAsmVariant,
292  int AsmPrinterVariant, AsmPrinter *AP,
293  unsigned LocCookie, raw_ostream &OS) {
294  int CurVariant = -1; // The number of the {.|.|.} region we are in.
295  const char *LastEmitted = AsmStr; // One past the last character emitted.
296  unsigned NumOperands = MI->getNumOperands();
297 
298  OS << '\t';
299 
300  while (*LastEmitted) {
301  switch (*LastEmitted) {
302  default: {
303  // Not a special case, emit the string section literally.
304  const char *LiteralEnd = LastEmitted+1;
305  while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
306  *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
307  ++LiteralEnd;
308  if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
309  OS.write(LastEmitted, LiteralEnd-LastEmitted);
310  LastEmitted = LiteralEnd;
311  break;
312  }
313  case '\n':
314  ++LastEmitted; // Consume newline character.
315  OS << '\n'; // Indent code with newline.
316  break;
317  case '$': {
318  ++LastEmitted; // Consume '$' character.
319  bool Done = true;
320 
321  // Handle escapes.
322  switch (*LastEmitted) {
323  default: Done = false; break;
324  case '$': // $$ -> $
325  if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
326  OS << '$';
327  ++LastEmitted; // Consume second '$' character.
328  break;
329  case '(': // $( -> same as GCC's { character.
330  ++LastEmitted; // Consume '(' character.
331  if (CurVariant != -1)
332  report_fatal_error("Nested variants found in inline asm string: '" +
333  Twine(AsmStr) + "'");
334  CurVariant = 0; // We're in the first variant now.
335  break;
336  case '|':
337  ++LastEmitted; // consume '|' character.
338  if (CurVariant == -1)
339  OS << '|'; // this is gcc's behavior for | outside a variant
340  else
341  ++CurVariant; // We're in the next variant.
342  break;
343  case ')': // $) -> same as GCC's } char.
344  ++LastEmitted; // consume ')' character.
345  if (CurVariant == -1)
346  OS << '}'; // this is gcc's behavior for } outside a variant
347  else
348  CurVariant = -1;
349  break;
350  }
351  if (Done) break;
352 
353  bool HasCurlyBraces = false;
354  if (*LastEmitted == '{') { // ${variable}
355  ++LastEmitted; // Consume '{' character.
356  HasCurlyBraces = true;
357  }
358 
359  // If we have ${:foo}, then this is not a real operand reference, it is a
360  // "magic" string reference, just like in .td files. Arrange to call
361  // PrintSpecial.
362  if (HasCurlyBraces && *LastEmitted == ':') {
363  ++LastEmitted;
364  const char *StrStart = LastEmitted;
365  const char *StrEnd = strchr(StrStart, '}');
366  if (!StrEnd)
367  report_fatal_error("Unterminated ${:foo} operand in inline asm"
368  " string: '" + Twine(AsmStr) + "'");
369 
370  std::string Val(StrStart, StrEnd);
371  AP->PrintSpecial(MI, OS, Val.c_str());
372  LastEmitted = StrEnd+1;
373  break;
374  }
375 
376  const char *IDStart = LastEmitted;
377  const char *IDEnd = IDStart;
378  while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
379 
380  unsigned Val;
381  if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
382  report_fatal_error("Bad $ operand number in inline asm string: '" +
383  Twine(AsmStr) + "'");
384  LastEmitted = IDEnd;
385 
386  char Modifier[2] = { 0, 0 };
387 
388  if (HasCurlyBraces) {
389  // If we have curly braces, check for a modifier character. This
390  // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
391  if (*LastEmitted == ':') {
392  ++LastEmitted; // Consume ':' character.
393  if (*LastEmitted == 0)
394  report_fatal_error("Bad ${:} expression in inline asm string: '" +
395  Twine(AsmStr) + "'");
396 
397  Modifier[0] = *LastEmitted;
398  ++LastEmitted; // Consume modifier character.
399  }
400 
401  if (*LastEmitted != '}')
402  report_fatal_error("Bad ${} expression in inline asm string: '" +
403  Twine(AsmStr) + "'");
404  ++LastEmitted; // Consume '}' character.
405  }
406 
407  if (Val >= NumOperands-1)
408  report_fatal_error("Invalid $ operand number in inline asm string: '" +
409  Twine(AsmStr) + "'");
410 
411  // Okay, we finally have a value number. Ask the target to print this
412  // operand!
413  if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
414  unsigned OpNo = InlineAsm::MIOp_FirstOperand;
415 
416  bool Error = false;
417 
418  // Scan to find the machine operand number for the operand.
419  for (; Val; --Val) {
420  if (OpNo >= MI->getNumOperands()) break;
421  unsigned OpFlags = MI->getOperand(OpNo).getImm();
422  OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
423  }
424 
425  // We may have a location metadata attached to the end of the
426  // instruction, and at no point should see metadata at any
427  // other point while processing. It's an error if so.
428  if (OpNo >= MI->getNumOperands() ||
429  MI->getOperand(OpNo).isMetadata()) {
430  Error = true;
431  } else {
432  unsigned OpFlags = MI->getOperand(OpNo).getImm();
433  ++OpNo; // Skip over the ID number.
434 
435  if (Modifier[0] == 'l') { // Labels are target independent.
436  if (MI->getOperand(OpNo).isBlockAddress()) {
437  const BlockAddress *BA = MI->getOperand(OpNo).getBlockAddress();
438  MCSymbol *Sym = AP->GetBlockAddressSymbol(BA);
439  Sym->print(OS, AP->MAI);
440  } else if (MI->getOperand(OpNo).isMBB()) {
441  const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
442  Sym->print(OS, AP->MAI);
443  } else {
444  Error = true;
445  }
446  } else {
447  if (InlineAsm::isMemKind(OpFlags)) {
448  Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
449  Modifier[0] ? Modifier : nullptr,
450  OS);
451  } else {
452  Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
453  Modifier[0] ? Modifier : nullptr, OS);
454  }
455  }
456  }
457  if (Error) {
458  std::string msg;
459  raw_string_ostream Msg(msg);
460  Msg << "invalid operand in inline asm: '" << AsmStr << "'";
461  MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
462  }
463  }
464  break;
465  }
466  }
467  }
468  OS << '\n' << (char)0; // null terminate string.
469 }
470 
471 /// EmitInlineAsm - This method formats and emits the specified machine
472 /// instruction that is an inline asm.
473 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
474  assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
475 
476  // Count the number of register definitions to find the asm string.
477  unsigned NumDefs = 0;
478  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
479  ++NumDefs)
480  assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
481 
482  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
483 
484  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
485  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
486 
487  // If this asmstr is empty, just print the #APP/#NOAPP markers.
488  // These are useful to see where empty asm's wound up.
489  if (AsmStr[0] == 0) {
490  OutStreamer->emitRawComment(MAI->getInlineAsmStart());
491  OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
492  return;
493  }
494 
495  // Emit the #APP start marker. This has to happen even if verbose-asm isn't
496  // enabled, so we use emitRawComment.
497  OutStreamer->emitRawComment(MAI->getInlineAsmStart());
498 
499  // Get the !srcloc metadata node if we have it, and decode the loc cookie from
500  // it.
501  unsigned LocCookie = 0;
502  const MDNode *LocMD = nullptr;
503  for (unsigned i = MI->getNumOperands(); i != 0; --i) {
504  if (MI->getOperand(i-1).isMetadata() &&
505  (LocMD = MI->getOperand(i-1).getMetadata()) &&
506  LocMD->getNumOperands() != 0) {
507  if (const ConstantInt *CI =
508  mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
509  LocCookie = CI->getZExtValue();
510  break;
511  }
512  }
513  }
514 
515  // Emit the inline asm to a temporary string so we can emit it through
516  // EmitInlineAsm.
517  SmallString<256> StringData;
518  raw_svector_ostream OS(StringData);
519 
520  // The variant of the current asmprinter.
521  int AsmPrinterVariant = MAI->getAssemblerDialect();
522  InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
523  AsmPrinter *AP = const_cast<AsmPrinter*>(this);
524  if (InlineAsmVariant == InlineAsm::AD_ATT)
525  EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
526  AP, LocCookie, OS);
527  else
528  EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
529 
530  // Reset SanitizeAddress based on the function's attribute.
531  MCTargetOptions MCOptions = TM.Options.MCOptions;
532  MCOptions.SanitizeAddress =
533  MF->getFunction().hasFnAttribute(Attribute::SanitizeAddress);
534 
535  // Emit warnings if we use reserved registers on the clobber list, as
536  // that might give surprising results.
537  std::vector<std::string> RestrRegs;
538  // Start with the first operand descriptor, and iterate over them.
539  for (unsigned I = InlineAsm::MIOp_FirstOperand, NumOps = MI->getNumOperands();
540  I < NumOps; ++I) {
541  const MachineOperand &MO = MI->getOperand(I);
542  if (MO.isImm()) {
543  unsigned Flags = MO.getImm();
546  !TRI->isAsmClobberable(*MF, MI->getOperand(I + 1).getReg())) {
547  RestrRegs.push_back(TRI->getName(MI->getOperand(I + 1).getReg()));
548  }
549  // Skip to one before the next operand descriptor, if it exists.
551  }
552  }
553 
554  if (!RestrRegs.empty()) {
555  unsigned BufNum = addInlineAsmDiagBuffer(OS.str(), LocMD);
556  auto &SrcMgr = DiagInfo->SrcMgr;
558  SrcMgr.getMemoryBuffer(BufNum)->getBuffer().begin());
559 
560  std::string Msg = "inline asm clobber list contains reserved registers: ";
561  for (auto I = RestrRegs.begin(), E = RestrRegs.end(); I != E; I++) {
562  if(I != RestrRegs.begin())
563  Msg += ", ";
564  Msg += *I;
565  }
566  std::string Note = "Reserved registers on the clobber list may not be "
567  "preserved across the asm statement, and clobbering them may "
568  "lead to undefined behaviour.";
569  SrcMgr.PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
570  SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note, Note);
571  }
572 
573  EmitInlineAsm(OS.str(), getSubtargetInfo(), MCOptions, LocMD,
574  MI->getInlineAsmDialect());
575 
576  // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
577  // enabled, so we use emitRawComment.
578  OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
579 }
580 
581 
582 /// PrintSpecial - Print information related to the specified machine instr
583 /// that is independent of the operand, and may be independent of the instr
584 /// itself. This can be useful for portably encoding the comment character
585 /// or other bits of target-specific knowledge into the asmstrings. The
586 /// syntax used is ${:comment}. Targets can override this to add support
587 /// for their own strange codes.
589  const char *Code) const {
590  if (!strcmp(Code, "private")) {
591  const DataLayout &DL = MF->getDataLayout();
592  OS << DL.getPrivateGlobalPrefix();
593  } else if (!strcmp(Code, "comment")) {
594  OS << MAI->getCommentString();
595  } else if (!strcmp(Code, "uid")) {
596  // Comparing the address of MI isn't sufficient, because machineinstrs may
597  // be allocated to the same address across functions.
598 
599  // If this is a new LastFn instruction, bump the counter.
600  if (LastMI != MI || LastFn != getFunctionNumber()) {
601  ++Counter;
602  LastMI = MI;
603  LastFn = getFunctionNumber();
604  }
605  OS << Counter;
606  } else {
607  std::string msg;
608  raw_string_ostream Msg(msg);
609  Msg << "Unknown special formatter '" << Code
610  << "' for machine instr: " << *MI;
611  report_fatal_error(Msg.str());
612  }
613 }
614 
615 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
616 /// instruction, using the specified assembler variant. Targets should
617 /// override this to format as appropriate.
618 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
619  unsigned AsmVariant, const char *ExtraCode,
620  raw_ostream &O) {
621  // Does this asm operand have a single letter operand modifier?
622  if (ExtraCode && ExtraCode[0]) {
623  if (ExtraCode[1] != 0) return true; // Unknown modifier.
624 
625  const MachineOperand &MO = MI->getOperand(OpNo);
626  switch (ExtraCode[0]) {
627  default:
628  return true; // Unknown modifier.
629  case 'c': // Substitute immediate value without immediate syntax
631  return true;
632  O << MO.getImm();
633  return false;
634  case 'n': // Negate the immediate constant.
636  return true;
637  O << -MO.getImm();
638  return false;
639  case 's': // The GCC deprecated s modifier
641  return true;
642  O << ((32 - MO.getImm()) & 31);
643  return false;
644  }
645  }
646  return true;
647 }
648 
649 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
650  unsigned AsmVariant,
651  const char *ExtraCode, raw_ostream &O) {
652  // Target doesn't support this yet!
653  return true;
654 }
655 
657 
659  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:110
const char * getInlineAsmStart() const
Definition: MCAsmInfo.h:503
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:93
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:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
SMLoc getLoc() const
Definition: SourceMgr.h:285
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:293
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:88
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
Definition: AsmPrinter.cpp:220
unsigned getReg() const
getReg - Returns the register number.
SourceMgr SrcMgr
Definition: Error.cpp:23
bool SanitizeAddress
Enables AddressSanitizer instrumentation at machine level.
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
bool isInlineAsm() const
void * getInlineAsmDiagnosticContext() const
getInlineAsmDiagnosticContext - Return the diagnostic context set by setInlineAsmDiagnosticHandler.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:320
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:509
bool isMetadata() const
isMetadata - Tests if this is a MO_Metadata operand.
unsigned const TargetRegisterInfo * TRI
Metadata node.
Definition: Metadata.h:863
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
const char * getInlineAsmEnd() const
Definition: MCAsmInfo.h:504
LLVMContext::InlineAsmDiagHandlerTy DiagHandler
Definition: AsmPrinter.h:163
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
MCAsmParser * createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &, const MCAsmInfo &, unsigned CB=0)
Create an MCAsmParser instance.
Definition: AsmParser.cpp:5939
The address of a basic block.
Definition: Constants.h:839
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:411
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:243
int getLineNo() const
Definition: SourceMgr.h:287
const char * getSymbolName() const
virtual unsigned getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
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:578
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
Context object for machine code objects.
Definition: MCContext.h:62
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:151
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:99
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
const char * getName(unsigned RegNo) const
Return the human-readable symbolic target-specific name for the specified physical register...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:55
void setInlineSourceManager(SourceMgr *SM)
Definition: MCContext.h:290
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:84
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:68
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:508
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:81
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:78
static unsigned getNumOperandRegisters(unsigned Flag)
getNumOperandRegisters - Extract the number of registers field from the inline asm operand flag...
Definition: InlineAsm.h:335
StringRef getCommentString() const
Definition: MCAsmInfo.h:485
static unsigned getKind(unsigned Flags)
Definition: InlineAsm.h:324
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:276
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:141
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:498
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:478
unsigned getFunctionNumber() const
Return a unique ID for the current function.
Definition: AsmPrinter.cpp:202
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
MachineOperand class - Representation of each machine instruction operand.
Module.h This file contains the declarations for the Module class.
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:534
int64_t getImm() const
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
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...
bool useIntegratedAssembler() const
Return true if assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:609
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
Representation of each machine instruction.
Definition: MachineInstr.h:63
TargetOptions Options
Definition: TargetMachine.h:96
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.
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:482
static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI, MachineModuleInfo *MMI, int InlineAsmVariant, int AsmPrinterVariant, AsmPrinter *AP, unsigned LocCookie, raw_ostream &OS)
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:45
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI, MachineModuleInfo *MMI, int InlineAsmVariant, AsmPrinter *AP, unsigned LocCookie, raw_ostream &OS)
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:162
Represents a location in source code.
Definition: SMLoc.h:23
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
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:259
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:59