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 
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  // If we have ${:foo}, then this is not a real operand reference, it is a
211  // "magic" string reference, just like in .td files. Arrange to call
212  // PrintSpecial.
213  if (LastEmitted[0] == '{' && LastEmitted[1] == ':') {
214  LastEmitted += 2;
215  const char *StrStart = LastEmitted;
216  const char *StrEnd = strchr(StrStart, '}');
217  if (!StrEnd)
218  report_fatal_error("Unterminated ${:foo} operand in inline asm"
219  " string: '" + Twine(AsmStr) + "'");
220 
221  std::string Val(StrStart, StrEnd);
222  AP->PrintSpecial(MI, OS, Val.c_str());
223  LastEmitted = StrEnd+1;
224  break;
225  }
226 
227  const char *IDStart = LastEmitted;
228  const char *IDEnd = IDStart;
229  while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
230 
231  unsigned Val;
232  if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
233  report_fatal_error("Bad $ operand number in inline asm string: '" +
234  Twine(AsmStr) + "'");
235  LastEmitted = IDEnd;
236 
237  if (Val >= NumOperands-1)
238  report_fatal_error("Invalid $ operand number in inline asm string: '" +
239  Twine(AsmStr) + "'");
240 
241  // Okay, we finally have a value number. Ask the target to print this
242  // operand!
243  unsigned OpNo = InlineAsm::MIOp_FirstOperand;
244 
245  bool Error = false;
246 
247  // Scan to find the machine operand number for the operand.
248  for (; Val; --Val) {
249  if (OpNo >= MI->getNumOperands()) break;
250  unsigned OpFlags = MI->getOperand(OpNo).getImm();
251  OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
252  }
253 
254  // We may have a location metadata attached to the end of the
255  // instruction, and at no point should see metadata at any
256  // other point while processing. It's an error if so.
257  if (OpNo >= MI->getNumOperands() ||
258  MI->getOperand(OpNo).isMetadata()) {
259  Error = true;
260  } else {
261  unsigned OpFlags = MI->getOperand(OpNo).getImm();
262  ++OpNo; // Skip over the ID number.
263 
264  if (InlineAsm::isMemKind(OpFlags)) {
265  Error = AP->PrintAsmMemoryOperand(MI, OpNo, /*Modifier*/ nullptr, OS);
266  } else {
267  Error = AP->PrintAsmOperand(MI, OpNo, /*Modifier*/ nullptr, OS);
268  }
269  }
270  if (Error) {
271  std::string msg;
272  raw_string_ostream Msg(msg);
273  Msg << "invalid operand in inline asm: '" << AsmStr << "'";
274  MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
275  }
276  break;
277  }
278  }
279  }
280  OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
281 }
282 
283 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
284  MachineModuleInfo *MMI, int AsmPrinterVariant,
285  AsmPrinter *AP, unsigned LocCookie,
286  raw_ostream &OS) {
287  int CurVariant = -1; // The number of the {.|.|.} region we are in.
288  const char *LastEmitted = AsmStr; // One past the last character emitted.
289  unsigned NumOperands = MI->getNumOperands();
290 
291  OS << '\t';
292 
293  while (*LastEmitted) {
294  switch (*LastEmitted) {
295  default: {
296  // Not a special case, emit the string section literally.
297  const char *LiteralEnd = LastEmitted+1;
298  while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
299  *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
300  ++LiteralEnd;
301  if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
302  OS.write(LastEmitted, LiteralEnd-LastEmitted);
303  LastEmitted = LiteralEnd;
304  break;
305  }
306  case '\n':
307  ++LastEmitted; // Consume newline character.
308  OS << '\n'; // Indent code with newline.
309  break;
310  case '$': {
311  ++LastEmitted; // Consume '$' character.
312  bool Done = true;
313 
314  // Handle escapes.
315  switch (*LastEmitted) {
316  default: Done = false; break;
317  case '$': // $$ -> $
318  if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
319  OS << '$';
320  ++LastEmitted; // Consume second '$' character.
321  break;
322  case '(': // $( -> same as GCC's { character.
323  ++LastEmitted; // Consume '(' character.
324  if (CurVariant != -1)
325  report_fatal_error("Nested variants found in inline asm string: '" +
326  Twine(AsmStr) + "'");
327  CurVariant = 0; // We're in the first variant now.
328  break;
329  case '|':
330  ++LastEmitted; // consume '|' character.
331  if (CurVariant == -1)
332  OS << '|'; // this is gcc's behavior for | outside a variant
333  else
334  ++CurVariant; // We're in the next variant.
335  break;
336  case ')': // $) -> same as GCC's } char.
337  ++LastEmitted; // consume ')' character.
338  if (CurVariant == -1)
339  OS << '}'; // this is gcc's behavior for } outside a variant
340  else
341  CurVariant = -1;
342  break;
343  }
344  if (Done) break;
345 
346  bool HasCurlyBraces = false;
347  if (*LastEmitted == '{') { // ${variable}
348  ++LastEmitted; // Consume '{' character.
349  HasCurlyBraces = true;
350  }
351 
352  // If we have ${:foo}, then this is not a real operand reference, it is a
353  // "magic" string reference, just like in .td files. Arrange to call
354  // PrintSpecial.
355  if (HasCurlyBraces && *LastEmitted == ':') {
356  ++LastEmitted;
357  const char *StrStart = LastEmitted;
358  const char *StrEnd = strchr(StrStart, '}');
359  if (!StrEnd)
360  report_fatal_error("Unterminated ${:foo} operand in inline asm"
361  " string: '" + Twine(AsmStr) + "'");
362 
363  std::string Val(StrStart, StrEnd);
364  AP->PrintSpecial(MI, OS, Val.c_str());
365  LastEmitted = StrEnd+1;
366  break;
367  }
368 
369  const char *IDStart = LastEmitted;
370  const char *IDEnd = IDStart;
371  while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
372 
373  unsigned Val;
374  if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
375  report_fatal_error("Bad $ operand number in inline asm string: '" +
376  Twine(AsmStr) + "'");
377  LastEmitted = IDEnd;
378 
379  char Modifier[2] = { 0, 0 };
380 
381  if (HasCurlyBraces) {
382  // If we have curly braces, check for a modifier character. This
383  // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
384  if (*LastEmitted == ':') {
385  ++LastEmitted; // Consume ':' character.
386  if (*LastEmitted == 0)
387  report_fatal_error("Bad ${:} expression in inline asm string: '" +
388  Twine(AsmStr) + "'");
389 
390  Modifier[0] = *LastEmitted;
391  ++LastEmitted; // Consume modifier character.
392  }
393 
394  if (*LastEmitted != '}')
395  report_fatal_error("Bad ${} expression in inline asm string: '" +
396  Twine(AsmStr) + "'");
397  ++LastEmitted; // Consume '}' character.
398  }
399 
400  if (Val >= NumOperands-1)
401  report_fatal_error("Invalid $ operand number in inline asm string: '" +
402  Twine(AsmStr) + "'");
403 
404  // Okay, we finally have a value number. Ask the target to print this
405  // operand!
406  if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
407  unsigned OpNo = InlineAsm::MIOp_FirstOperand;
408 
409  bool Error = false;
410 
411  // Scan to find the machine operand number for the operand.
412  for (; Val; --Val) {
413  if (OpNo >= MI->getNumOperands()) break;
414  unsigned OpFlags = MI->getOperand(OpNo).getImm();
415  OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
416  }
417 
418  // We may have a location metadata attached to the end of the
419  // instruction, and at no point should see metadata at any
420  // other point while processing. It's an error if so.
421  if (OpNo >= MI->getNumOperands() ||
422  MI->getOperand(OpNo).isMetadata()) {
423  Error = true;
424  } else {
425  unsigned OpFlags = MI->getOperand(OpNo).getImm();
426  ++OpNo; // Skip over the ID number.
427 
428  // FIXME: Shouldn't arch-independent output template handling go into
429  // PrintAsmOperand?
430  if (Modifier[0] == 'l') { // Labels are target independent.
431  if (MI->getOperand(OpNo).isBlockAddress()) {
432  const BlockAddress *BA = MI->getOperand(OpNo).getBlockAddress();
433  MCSymbol *Sym = AP->GetBlockAddressSymbol(BA);
434  Sym->print(OS, AP->MAI);
435  } else if (MI->getOperand(OpNo).isMBB()) {
436  const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
437  Sym->print(OS, AP->MAI);
438  } else {
439  Error = true;
440  }
441  } else {
442  if (InlineAsm::isMemKind(OpFlags)) {
443  Error = AP->PrintAsmMemoryOperand(
444  MI, OpNo, Modifier[0] ? Modifier : nullptr, OS);
445  } else {
446  Error = AP->PrintAsmOperand(MI, OpNo,
447  Modifier[0] ? Modifier : nullptr, OS);
448  }
449  }
450  }
451  if (Error) {
452  std::string msg;
453  raw_string_ostream Msg(msg);
454  Msg << "invalid operand in inline asm: '" << AsmStr << "'";
455  MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
456  }
457  }
458  break;
459  }
460  }
461  }
462  OS << '\n' << (char)0; // null terminate string.
463 }
464 
465 /// EmitInlineAsm - This method formats and emits the specified machine
466 /// instruction that is an inline asm.
467 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
468  assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
469 
470  // Count the number of register definitions to find the asm string.
471  unsigned NumDefs = 0;
472  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
473  ++NumDefs)
474  assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
475 
476  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
477 
478  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
479  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
480 
481  // If this asmstr is empty, just print the #APP/#NOAPP markers.
482  // These are useful to see where empty asm's wound up.
483  if (AsmStr[0] == 0) {
484  OutStreamer->emitRawComment(MAI->getInlineAsmStart());
485  OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
486  return;
487  }
488 
489  // Emit the #APP start marker. This has to happen even if verbose-asm isn't
490  // enabled, so we use emitRawComment.
491  OutStreamer->emitRawComment(MAI->getInlineAsmStart());
492 
493  // Get the !srcloc metadata node if we have it, and decode the loc cookie from
494  // it.
495  unsigned LocCookie = 0;
496  const MDNode *LocMD = nullptr;
497  for (unsigned i = MI->getNumOperands(); i != 0; --i) {
498  if (MI->getOperand(i-1).isMetadata() &&
499  (LocMD = MI->getOperand(i-1).getMetadata()) &&
500  LocMD->getNumOperands() != 0) {
501  if (const ConstantInt *CI =
502  mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
503  LocCookie = CI->getZExtValue();
504  break;
505  }
506  }
507  }
508 
509  // Emit the inline asm to a temporary string so we can emit it through
510  // EmitInlineAsm.
511  SmallString<256> StringData;
512  raw_svector_ostream OS(StringData);
513 
514  // The variant of the current asmprinter.
515  int AsmPrinterVariant = MAI->getAssemblerDialect();
516  AsmPrinter *AP = const_cast<AsmPrinter*>(this);
518  EmitGCCInlineAsmStr(AsmStr, MI, MMI, AsmPrinterVariant, AP, LocCookie, OS);
519  else
520  EmitMSInlineAsmStr(AsmStr, MI, MMI, AP, LocCookie, OS);
521 
522  // Emit warnings if we use reserved registers on the clobber list, as
523  // that might give surprising results.
524  std::vector<std::string> RestrRegs;
525  // Start with the first operand descriptor, and iterate over them.
526  for (unsigned I = InlineAsm::MIOp_FirstOperand, NumOps = MI->getNumOperands();
527  I < NumOps; ++I) {
528  const MachineOperand &MO = MI->getOperand(I);
529  if (MO.isImm()) {
530  unsigned Flags = MO.getImm();
533  !TRI->isAsmClobberable(*MF, MI->getOperand(I + 1).getReg())) {
534  RestrRegs.push_back(TRI->getName(MI->getOperand(I + 1).getReg()));
535  }
536  // Skip to one before the next operand descriptor, if it exists.
538  }
539  }
540 
541  if (!RestrRegs.empty()) {
542  unsigned BufNum = addInlineAsmDiagBuffer(OS.str(), LocMD);
543  auto &SrcMgr = DiagInfo->SrcMgr;
545  SrcMgr.getMemoryBuffer(BufNum)->getBuffer().begin());
546 
547  std::string Msg = "inline asm clobber list contains reserved registers: ";
548  for (auto I = RestrRegs.begin(), E = RestrRegs.end(); I != E; I++) {
549  if(I != RestrRegs.begin())
550  Msg += ", ";
551  Msg += *I;
552  }
553  std::string Note = "Reserved registers on the clobber list may not be "
554  "preserved across the asm statement, and clobbering them may "
555  "lead to undefined behaviour.";
556  SrcMgr.PrintMessage(Loc, SourceMgr::DK_Warning, Msg);
557  SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note, Note);
558  }
559 
560  EmitInlineAsm(OS.str(), getSubtargetInfo(), TM.Options.MCOptions, LocMD,
561  MI->getInlineAsmDialect());
562 
563  // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
564  // enabled, so we use emitRawComment.
565  OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
566 }
567 
568 
569 /// PrintSpecial - Print information related to the specified machine instr
570 /// that is independent of the operand, and may be independent of the instr
571 /// itself. This can be useful for portably encoding the comment character
572 /// or other bits of target-specific knowledge into the asmstrings. The
573 /// syntax used is ${:comment}. Targets can override this to add support
574 /// for their own strange codes.
576  const char *Code) const {
577  if (!strcmp(Code, "private")) {
578  const DataLayout &DL = MF->getDataLayout();
579  OS << DL.getPrivateGlobalPrefix();
580  } else if (!strcmp(Code, "comment")) {
581  OS << MAI->getCommentString();
582  } else if (!strcmp(Code, "uid")) {
583  // Comparing the address of MI isn't sufficient, because machineinstrs may
584  // be allocated to the same address across functions.
585 
586  // If this is a new LastFn instruction, bump the counter.
587  if (LastMI != MI || LastFn != getFunctionNumber()) {
588  ++Counter;
589  LastMI = MI;
590  LastFn = getFunctionNumber();
591  }
592  OS << Counter;
593  } else {
594  std::string msg;
595  raw_string_ostream Msg(msg);
596  Msg << "Unknown special formatter '" << Code
597  << "' for machine instr: " << *MI;
598  report_fatal_error(Msg.str());
599  }
600 }
601 
603  assert(MO.isGlobal() && "caller should check MO.isGlobal");
604  getSymbol(MO.getGlobal())->print(OS, MAI);
605  printOffset(MO.getOffset(), OS);
606 }
607 
608 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
609 /// instruction, using the specified assembler variant. Targets should
610 /// override this to format as appropriate for machine specific ExtraCodes
611 /// or when the arch-independent handling would be too complex otherwise.
612 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
613  const char *ExtraCode, raw_ostream &O) {
614  // Does this asm operand have a single letter operand modifier?
615  if (ExtraCode && ExtraCode[0]) {
616  if (ExtraCode[1] != 0) return true; // Unknown modifier.
617 
618  // https://gcc.gnu.org/onlinedocs/gccint/Output-Template.html
619  const MachineOperand &MO = MI->getOperand(OpNo);
620  switch (ExtraCode[0]) {
621  default:
622  return true; // Unknown modifier.
623  case 'a': // Print as memory address.
624  if (MO.isReg()) {
625  PrintAsmMemoryOperand(MI, OpNo, nullptr, O);
626  return false;
627  }
628  LLVM_FALLTHROUGH; // GCC allows '%a' to behave like '%c' with immediates.
629  case 'c': // Substitute immediate value without immediate syntax
630  if (MO.isImm()) {
631  O << MO.getImm();
632  return false;
633  }
634  if (MO.isGlobal()) {
635  PrintSymbolOperand(MO, O);
636  return false;
637  }
638  return true;
639  case 'n': // Negate the immediate constant.
640  if (!MO.isImm())
641  return true;
642  O << -MO.getImm();
643  return false;
644  case 's': // The GCC deprecated s modifier
645  if (!MO.isImm())
646  return true;
647  O << ((32 - MO.getImm()) & 31);
648  return false;
649  }
650  }
651  return true;
652 }
653 
654 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
655  const char *ExtraCode, raw_ostream &O) {
656  // Target doesn't support this yet!
657  return true;
658 }
659 
661 
663  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:316
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:226
unsigned getReg() const
getReg - Returns the register number.
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: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.
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:5957
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:244
int getLineNo() const
Definition: SourceMgr.h:287
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: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
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
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: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:64
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...
const GlobalValue * getGlobal() const
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:208
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:441
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:534
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...
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:607
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:482
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:250
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.
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
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