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/SmallVector.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/TargetInstrInfo.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/TargetRegistry.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "asm-printer"
42 
43 unsigned AsmPrinter::addInlineAsmDiagBuffer(StringRef AsmStr,
44                                             const MDNode *LocMDNode) const {
45   MCContext &Context = MMI->getContext();
46   Context.initInlineSourceManager();
47   SourceMgr &SrcMgr = *Context.getInlineSourceManager();
48   std::vector<const MDNode *> &LocInfos = Context.getLocInfos();
49 
50   std::unique_ptr<MemoryBuffer> Buffer;
51   // The inline asm source manager will outlive AsmStr, so make a copy of the
52   // string for SourceMgr to own.
53   Buffer = MemoryBuffer::getMemBufferCopy(AsmStr, "<inline asm>");
54 
55   // Tell SrcMgr about this buffer, it takes ownership of the buffer.
56   unsigned BufNum = SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
57 
58   // Store LocMDNode in DiagInfo, using BufNum as an identifier.
59   if (LocMDNode) {
60     LocInfos.resize(BufNum);
61     LocInfos[BufNum - 1] = LocMDNode;
62   }
63 
64   return BufNum;
65 }
66 
67 
68 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
69 void AsmPrinter::emitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
70                                const MCTargetOptions &MCOptions,
71                                const MDNode *LocMDNode,
72                                InlineAsm::AsmDialect Dialect) const {
73   assert(!Str.empty() && "Can't emit empty inline asm block");
74 
75   // Remember if the buffer is nul terminated or not so we can avoid a copy.
76   bool isNullTerminated = Str.back() == 0;
77   if (isNullTerminated)
78     Str = Str.substr(0, Str.size()-1);
79 
80   // If the output streamer does not have mature MC support or the integrated
81   // assembler has been disabled or not required, just emit the blob textually.
82   // Otherwise parse the asm and emit it via MC support.
83   // This is useful in case the asm parser doesn't handle something but the
84   // system assembler does.
85   const MCAsmInfo *MCAI = TM.getMCAsmInfo();
86   assert(MCAI && "No MCAsmInfo");
87   if (!MCAI->useIntegratedAssembler() &&
88       !MCAI->parseInlineAsmUsingAsmParser() &&
89       !OutStreamer->isIntegratedAssemblerRequired()) {
90     emitInlineAsmStart();
91     OutStreamer->emitRawText(Str);
92     emitInlineAsmEnd(STI, nullptr);
93     return;
94   }
95 
96   unsigned BufNum = addInlineAsmDiagBuffer(Str, LocMDNode);
97   SourceMgr &SrcMgr = *MMI->getContext().getInlineSourceManager();
98   SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths);
99 
100   std::unique_ptr<MCAsmParser> Parser(
101       createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI, BufNum));
102 
103   // Do not use assembler-level information for parsing inline assembly.
104   OutStreamer->setUseAssemblerInfoForParsing(false);
105 
106   // We create a new MCInstrInfo here since we might be at the module level
107   // and not have a MachineFunction to initialize the TargetInstrInfo from and
108   // we only need MCInstrInfo for asm parsing. We create one unconditionally
109   // because it's not subtarget dependent.
110   std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
111   assert(MII && "Failed to create instruction info");
112   std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
113       STI, *Parser, *MII, MCOptions));
114   if (!TAP)
115     report_fatal_error("Inline asm not supported by this streamer because"
116                        " we don't have an asm parser for this target\n");
117   Parser->setAssemblerDialect(Dialect);
118   Parser->setTargetParser(*TAP.get());
119   // Enable lexing Masm binary and hex integer literals in intel inline
120   // assembly.
121   if (Dialect == InlineAsm::AD_Intel)
122     Parser->getLexer().setLexMasmIntegers(true);
123 
124   emitInlineAsmStart();
125   // Don't implicitly switch to the text section before the asm.
126   (void)Parser->Run(/*NoInitialTextSection*/ true,
127                     /*NoFinalize*/ true);
128   emitInlineAsmEnd(STI, &TAP->getSTI());
129 }
130 
131 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
132                                MachineModuleInfo *MMI, const MCAsmInfo *MAI,
133                                AsmPrinter *AP, uint64_t LocCookie,
134                                raw_ostream &OS) {
135   // Switch to the inline assembly variant.
136   OS << "\t.intel_syntax\n\t";
137 
138   int CurVariant = -1; // The number of the {.|.|.} region we are in.
139   const char *LastEmitted = AsmStr; // One past the last character emitted.
140   unsigned NumOperands = MI->getNumOperands();
141   int AsmPrinterVariant = 1; // X86MCAsmInfo.cpp's AsmWriterFlavorTy::Intel.
142 
143   while (*LastEmitted) {
144     switch (*LastEmitted) {
145     default: {
146       // Not a special case, emit the string section literally.
147       const char *LiteralEnd = LastEmitted+1;
148       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
149              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
150         ++LiteralEnd;
151       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
152         OS.write(LastEmitted, LiteralEnd - LastEmitted);
153       LastEmitted = LiteralEnd;
154       break;
155     }
156     case '\n':
157       ++LastEmitted;   // Consume newline character.
158       OS << '\n';      // Indent code with newline.
159       break;
160     case '$': {
161       ++LastEmitted;   // Consume '$' character.
162       bool Done = true;
163 
164       // Handle escapes.
165       switch (*LastEmitted) {
166       default: Done = false; break;
167       case '$':
168         ++LastEmitted;  // Consume second '$' character.
169         break;
170       case '(':        // $( -> same as GCC's { character.
171         ++LastEmitted; // Consume '(' character.
172         if (CurVariant != -1)
173           report_fatal_error("Nested variants found in inline asm string: '" +
174                              Twine(AsmStr) + "'");
175         CurVariant = 0; // We're in the first variant now.
176         break;
177       case '|':
178         ++LastEmitted; // Consume '|' character.
179         if (CurVariant == -1)
180           OS << '|'; // This is gcc's behavior for | outside a variant.
181         else
182           ++CurVariant; // We're in the next variant.
183         break;
184       case ')':        // $) -> same as GCC's } char.
185         ++LastEmitted; // Consume ')' character.
186         if (CurVariant == -1)
187           OS << '}'; // This is gcc's behavior for } outside a variant.
188         else
189           CurVariant = -1;
190         break;
191       }
192       if (Done) break;
193 
194       bool HasCurlyBraces = false;
195       if (*LastEmitted == '{') {     // ${variable}
196         ++LastEmitted;               // Consume '{' character.
197         HasCurlyBraces = true;
198       }
199 
200       // If we have ${:foo}, then this is not a real operand reference, it is a
201       // "magic" string reference, just like in .td files.  Arrange to call
202       // PrintSpecial.
203       if (HasCurlyBraces && *LastEmitted == ':') {
204         ++LastEmitted;
205         const char *StrStart = LastEmitted;
206         const char *StrEnd = strchr(StrStart, '}');
207         if (!StrEnd)
208           report_fatal_error("Unterminated ${:foo} operand in inline asm"
209                              " string: '" + Twine(AsmStr) + "'");
210         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
211           AP->PrintSpecial(MI, OS, StringRef(StrStart, StrEnd - StrStart));
212         LastEmitted = StrEnd+1;
213         break;
214       }
215 
216       const char *IDStart = LastEmitted;
217       const char *IDEnd = IDStart;
218       while (isDigit(*IDEnd))
219         ++IDEnd;
220 
221       unsigned Val;
222       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
223         report_fatal_error("Bad $ operand number in inline asm string: '" +
224                            Twine(AsmStr) + "'");
225       LastEmitted = IDEnd;
226 
227       if (Val >= NumOperands - 1)
228         report_fatal_error("Invalid $ operand number in inline asm string: '" +
229                            Twine(AsmStr) + "'");
230 
231       char Modifier[2] = { 0, 0 };
232 
233       if (HasCurlyBraces) {
234         // If we have curly braces, check for a modifier character.  This
235         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
236         if (*LastEmitted == ':') {
237           ++LastEmitted;    // Consume ':' character.
238           if (*LastEmitted == 0)
239             report_fatal_error("Bad ${:} expression in inline asm string: '" +
240                                Twine(AsmStr) + "'");
241 
242           Modifier[0] = *LastEmitted;
243           ++LastEmitted;    // Consume modifier character.
244         }
245 
246         if (*LastEmitted != '}')
247           report_fatal_error("Bad ${} expression in inline asm string: '" +
248                              Twine(AsmStr) + "'");
249         ++LastEmitted;    // Consume '}' character.
250       }
251 
252       // Okay, we finally have a value number.  Ask the target to print this
253       // operand!
254       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
255         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
256 
257         bool Error = false;
258 
259         // Scan to find the machine operand number for the operand.
260         for (; Val; --Val) {
261           if (OpNo >= MI->getNumOperands())
262             break;
263           unsigned OpFlags = MI->getOperand(OpNo).getImm();
264           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
265         }
266 
267         // We may have a location metadata attached to the end of the
268         // instruction, and at no point should see metadata at any
269         // other point while processing. It's an error if so.
270         if (OpNo >= MI->getNumOperands() || MI->getOperand(OpNo).isMetadata()) {
271           Error = true;
272         } else {
273           unsigned OpFlags = MI->getOperand(OpNo).getImm();
274           ++OpNo; // Skip over the ID number.
275 
276           // FIXME: Shouldn't arch-independent output template handling go into
277           // PrintAsmOperand?
278           // Labels are target independent.
279           if (MI->getOperand(OpNo).isBlockAddress()) {
280             const BlockAddress *BA = MI->getOperand(OpNo).getBlockAddress();
281             MCSymbol *Sym = AP->GetBlockAddressSymbol(BA);
282             Sym->print(OS, AP->MAI);
283             MMI->getContext().registerInlineAsmLabel(Sym);
284           } else if (InlineAsm::isMemKind(OpFlags)) {
285             Error = AP->PrintAsmMemoryOperand(
286                 MI, OpNo, Modifier[0] ? Modifier : nullptr, OS);
287           } else {
288             Error = AP->PrintAsmOperand(MI, OpNo,
289                                         Modifier[0] ? Modifier : nullptr, OS);
290           }
291         }
292         if (Error) {
293           std::string msg;
294           raw_string_ostream Msg(msg);
295           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
296           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
297         }
298       }
299       break;
300     }
301     }
302   }
303   OS << "\n\t.att_syntax\n" << (char)0;  // null terminate string.
304 }
305 
306 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
307                                 MachineModuleInfo *MMI, const MCAsmInfo *MAI,
308                                 AsmPrinter *AP, uint64_t LocCookie,
309                                 raw_ostream &OS) {
310   int CurVariant = -1; // The number of the {.|.|.} region we are in.
311   const char *LastEmitted = AsmStr; // One past the last character emitted.
312   unsigned NumOperands = MI->getNumOperands();
313   int AsmPrinterVariant = MMI->getTarget().unqualifiedInlineAsmVariant();
314 
315   if (MAI->getEmitGNUAsmStartIndentationMarker())
316     OS << '\t';
317 
318   while (*LastEmitted) {
319     switch (*LastEmitted) {
320     default: {
321       // Not a special case, emit the string section literally.
322       const char *LiteralEnd = LastEmitted+1;
323       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
324              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
325         ++LiteralEnd;
326       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
327         OS.write(LastEmitted, LiteralEnd - LastEmitted);
328       LastEmitted = LiteralEnd;
329       break;
330     }
331     case '\n':
332       ++LastEmitted;   // Consume newline character.
333       OS << '\n';      // Indent code with newline.
334       break;
335     case '$': {
336       ++LastEmitted;   // Consume '$' character.
337       bool Done = true;
338 
339       // Handle escapes.
340       switch (*LastEmitted) {
341       default: Done = false; break;
342       case '$':     // $$ -> $
343         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
344           OS << '$';
345         ++LastEmitted;  // Consume second '$' character.
346         break;
347       case '(':        // $( -> same as GCC's { character.
348         ++LastEmitted; // Consume '(' character.
349         if (CurVariant != -1)
350           report_fatal_error("Nested variants found in inline asm string: '" +
351                              Twine(AsmStr) + "'");
352         CurVariant = 0; // We're in the first variant now.
353         break;
354       case '|':
355         ++LastEmitted; // Consume '|' character.
356         if (CurVariant == -1)
357           OS << '|'; // This is gcc's behavior for | outside a variant.
358         else
359           ++CurVariant; // We're in the next variant.
360         break;
361       case ')':        // $) -> same as GCC's } char.
362         ++LastEmitted; // Consume ')' character.
363         if (CurVariant == -1)
364           OS << '}'; // This is gcc's behavior for } outside a variant.
365         else
366           CurVariant = -1;
367         break;
368       }
369       if (Done) break;
370 
371       bool HasCurlyBraces = false;
372       if (*LastEmitted == '{') {     // ${variable}
373         ++LastEmitted;               // Consume '{' character.
374         HasCurlyBraces = true;
375       }
376 
377       // If we have ${:foo}, then this is not a real operand reference, it is a
378       // "magic" string reference, just like in .td files.  Arrange to call
379       // PrintSpecial.
380       if (HasCurlyBraces && *LastEmitted == ':') {
381         ++LastEmitted;
382         const char *StrStart = LastEmitted;
383         const char *StrEnd = strchr(StrStart, '}');
384         if (!StrEnd)
385           report_fatal_error("Unterminated ${:foo} operand in inline asm"
386                              " string: '" + Twine(AsmStr) + "'");
387         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
388           AP->PrintSpecial(MI, OS, StringRef(StrStart, StrEnd - StrStart));
389         LastEmitted = StrEnd+1;
390         break;
391       }
392 
393       const char *IDStart = LastEmitted;
394       const char *IDEnd = IDStart;
395       while (isDigit(*IDEnd))
396         ++IDEnd;
397 
398       unsigned Val;
399       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
400         report_fatal_error("Bad $ operand number in inline asm string: '" +
401                            Twine(AsmStr) + "'");
402       LastEmitted = IDEnd;
403 
404       if (Val >= NumOperands - 1)
405         report_fatal_error("Invalid $ operand number in inline asm string: '" +
406                            Twine(AsmStr) + "'");
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       // Okay, we finally have a value number.  Ask the target to print this
430       // operand!
431       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
432         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
433 
434         bool Error = false;
435 
436         // Scan to find the machine operand number for the operand.
437         for (; Val; --Val) {
438           if (OpNo >= MI->getNumOperands())
439             break;
440           unsigned OpFlags = MI->getOperand(OpNo).getImm();
441           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
442         }
443 
444         // We may have a location metadata attached to the end of the
445         // instruction, and at no point should see metadata at any
446         // other point while processing. It's an error if so.
447         if (OpNo >= MI->getNumOperands() || MI->getOperand(OpNo).isMetadata()) {
448           Error = true;
449         } else {
450           unsigned OpFlags = MI->getOperand(OpNo).getImm();
451           ++OpNo; // Skip over the ID number.
452 
453           // FIXME: Shouldn't arch-independent output template handling go into
454           // PrintAsmOperand?
455           // Labels are target independent.
456           if (MI->getOperand(OpNo).isBlockAddress()) {
457             const BlockAddress *BA = MI->getOperand(OpNo).getBlockAddress();
458             MCSymbol *Sym = AP->GetBlockAddressSymbol(BA);
459             Sym->print(OS, AP->MAI);
460             MMI->getContext().registerInlineAsmLabel(Sym);
461           } else if (MI->getOperand(OpNo).isMBB()) {
462             const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
463             Sym->print(OS, AP->MAI);
464           } else if (InlineAsm::isMemKind(OpFlags)) {
465             Error = AP->PrintAsmMemoryOperand(
466                 MI, OpNo, Modifier[0] ? Modifier : nullptr, OS);
467           } else {
468             Error = AP->PrintAsmOperand(MI, OpNo,
469                                         Modifier[0] ? Modifier : nullptr, OS);
470           }
471         }
472         if (Error) {
473           std::string msg;
474           raw_string_ostream Msg(msg);
475           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
476           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
477         }
478       }
479       break;
480     }
481     }
482   }
483   OS << '\n' << (char)0;  // null terminate string.
484 }
485 
486 /// This method formats and emits the specified machine instruction that is an
487 /// inline asm.
488 void AsmPrinter::emitInlineAsm(const MachineInstr *MI) const {
489   assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
490 
491   // Count the number of register definitions to find the asm string.
492   unsigned NumDefs = 0;
493   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
494        ++NumDefs)
495     assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
496 
497   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
498 
499   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
500   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
501 
502   // If this asmstr is empty, just print the #APP/#NOAPP markers.
503   // These are useful to see where empty asm's wound up.
504   if (AsmStr[0] == 0) {
505     OutStreamer->emitRawComment(MAI->getInlineAsmStart());
506     OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
507     return;
508   }
509 
510   // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
511   // enabled, so we use emitRawComment.
512   OutStreamer->emitRawComment(MAI->getInlineAsmStart());
513 
514   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
515   // it.
516   uint64_t LocCookie = 0;
517   const MDNode *LocMD = nullptr;
518   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
519     if (MI->getOperand(i-1).isMetadata() &&
520         (LocMD = MI->getOperand(i-1).getMetadata()) &&
521         LocMD->getNumOperands() != 0) {
522       if (const ConstantInt *CI =
523               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
524         LocCookie = CI->getZExtValue();
525         break;
526       }
527     }
528   }
529 
530   // Emit the inline asm to a temporary string so we can emit it through
531   // EmitInlineAsm.
532   SmallString<256> StringData;
533   raw_svector_ostream OS(StringData);
534 
535   AsmPrinter *AP = const_cast<AsmPrinter*>(this);
536   if (MI->getInlineAsmDialect() == InlineAsm::AD_ATT)
537     EmitGCCInlineAsmStr(AsmStr, MI, MMI, MAI, AP, LocCookie, OS);
538   else
539     EmitMSInlineAsmStr(AsmStr, MI, MMI, MAI, AP, LocCookie, OS);
540 
541   // Emit warnings if we use reserved registers on the clobber list, as
542   // that might lead to undefined behaviour.
543   SmallVector<Register, 8> RestrRegs;
544   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
545   // Start with the first operand descriptor, and iterate over them.
546   for (unsigned I = InlineAsm::MIOp_FirstOperand, NumOps = MI->getNumOperands();
547        I < NumOps; ++I) {
548     const MachineOperand &MO = MI->getOperand(I);
549     if (!MO.isImm())
550       continue;
551     unsigned Flags = MO.getImm();
552     if (InlineAsm::getKind(Flags) == InlineAsm::Kind_Clobber) {
553       Register Reg = MI->getOperand(I + 1).getReg();
554       if (!TRI->isAsmClobberable(*MF, Reg))
555         RestrRegs.push_back(Reg);
556     }
557     // Skip to one before the next operand descriptor, if it exists.
558     I += InlineAsm::getNumOperandRegisters(Flags);
559   }
560 
561   if (!RestrRegs.empty()) {
562     std::string Msg = "inline asm clobber list contains reserved registers: ";
563     ListSeparator LS;
564     for (const Register &RR : RestrRegs) {
565       Msg += LS;
566       Msg += TRI->getName(RR);
567     }
568     const char *Note =
569         "Reserved registers on the clobber list may not be "
570         "preserved across the asm statement, and clobbering them may "
571         "lead to undefined behaviour.";
572     MMI->getModule()->getContext().diagnose(DiagnosticInfoInlineAsm(
573         LocCookie, Msg, DiagnosticSeverity::DS_Warning));
574     MMI->getModule()->getContext().diagnose(
575         DiagnosticInfoInlineAsm(LocCookie, Note, DiagnosticSeverity::DS_Note));
576   }
577 
578   emitInlineAsm(OS.str(), getSubtargetInfo(), TM.Options.MCOptions, LocMD,
579                 MI->getInlineAsmDialect());
580 
581   // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
582   // enabled, so we use emitRawComment.
583   OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
584 }
585 
586 /// PrintSpecial - Print information related to the specified machine instr
587 /// that is independent of the operand, and may be independent of the instr
588 /// itself.  This can be useful for portably encoding the comment character
589 /// or other bits of target-specific knowledge into the asmstrings.  The
590 /// syntax used is ${:comment}.  Targets can override this to add support
591 /// for their own strange codes.
592 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
593                               StringRef Code) const {
594   if (Code == "private") {
595     const DataLayout &DL = MF->getDataLayout();
596     OS << DL.getPrivateGlobalPrefix();
597   } else if (Code == "comment") {
598     OS << MAI->getCommentString();
599   } else if (Code == "uid") {
600     // Comparing the address of MI isn't sufficient, because machineinstrs may
601     // be allocated to the same address across functions.
602 
603     // If this is a new LastFn instruction, bump the counter.
604     if (LastMI != MI || LastFn != getFunctionNumber()) {
605       ++Counter;
606       LastMI = MI;
607       LastFn = getFunctionNumber();
608     }
609     OS << Counter;
610   } else {
611     std::string msg;
612     raw_string_ostream Msg(msg);
613     Msg << "Unknown special formatter '" << Code
614          << "' for machine instr: " << *MI;
615     report_fatal_error(Twine(Msg.str()));
616   }
617 }
618 
619 void AsmPrinter::PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS) {
620   assert(MO.isGlobal() && "caller should check MO.isGlobal");
621   getSymbolPreferLocal(*MO.getGlobal())->print(OS, MAI);
622   printOffset(MO.getOffset(), OS);
623 }
624 
625 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
626 /// instruction, using the specified assembler variant.  Targets should
627 /// override this to format as appropriate for machine specific ExtraCodes
628 /// or when the arch-independent handling would be too complex otherwise.
629 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
630                                  const char *ExtraCode, raw_ostream &O) {
631   // Does this asm operand have a single letter operand modifier?
632   if (ExtraCode && ExtraCode[0]) {
633     if (ExtraCode[1] != 0) return true; // Unknown modifier.
634 
635     // https://gcc.gnu.org/onlinedocs/gccint/Output-Template.html
636     const MachineOperand &MO = MI->getOperand(OpNo);
637     switch (ExtraCode[0]) {
638     default:
639       return true;  // Unknown modifier.
640     case 'a': // Print as memory address.
641       if (MO.isReg()) {
642         PrintAsmMemoryOperand(MI, OpNo, nullptr, O);
643         return false;
644       }
645       LLVM_FALLTHROUGH; // GCC allows '%a' to behave like '%c' with immediates.
646     case 'c': // Substitute immediate value without immediate syntax
647       if (MO.isImm()) {
648         O << MO.getImm();
649         return false;
650       }
651       if (MO.isGlobal()) {
652         PrintSymbolOperand(MO, O);
653         return false;
654       }
655       return true;
656     case 'n':  // Negate the immediate constant.
657       if (!MO.isImm())
658         return true;
659       O << -MO.getImm();
660       return false;
661     case 's':  // The GCC deprecated s modifier
662       if (!MO.isImm())
663         return true;
664       O << ((32 - MO.getImm()) & 31);
665       return false;
666     }
667   }
668   return true;
669 }
670 
671 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
672                                        const char *ExtraCode, raw_ostream &O) {
673   // Target doesn't support this yet!
674   return true;
675 }
676 
677 void AsmPrinter::emitInlineAsmStart() const {}
678 
679 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
680                                   const MCSubtargetInfo *EndInfo) const {}
681