1f4a2713aSLionel Sambuc //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file implements the inline assembler pieces of the AsmPrinter class.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc 
14f4a2713aSLionel Sambuc #include "llvm/CodeGen/AsmPrinter.h"
15f4a2713aSLionel Sambuc #include "llvm/ADT/SmallString.h"
16f4a2713aSLionel Sambuc #include "llvm/ADT/Twine.h"
17f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineBasicBlock.h"
18*0a6a1f1dSLionel Sambuc #include "llvm/CodeGen/MachineFunction.h"
19f4a2713aSLionel Sambuc #include "llvm/CodeGen/MachineModuleInfo.h"
20f4a2713aSLionel Sambuc #include "llvm/IR/Constants.h"
21*0a6a1f1dSLionel Sambuc #include "llvm/IR/DataLayout.h"
22f4a2713aSLionel Sambuc #include "llvm/IR/InlineAsm.h"
23f4a2713aSLionel Sambuc #include "llvm/IR/LLVMContext.h"
24f4a2713aSLionel Sambuc #include "llvm/IR/Module.h"
25f4a2713aSLionel Sambuc #include "llvm/MC/MCAsmInfo.h"
26f4a2713aSLionel Sambuc #include "llvm/MC/MCStreamer.h"
27f4a2713aSLionel Sambuc #include "llvm/MC/MCSubtargetInfo.h"
28f4a2713aSLionel Sambuc #include "llvm/MC/MCSymbol.h"
29f4a2713aSLionel Sambuc #include "llvm/MC/MCTargetAsmParser.h"
30f4a2713aSLionel Sambuc #include "llvm/Support/ErrorHandling.h"
31f4a2713aSLionel Sambuc #include "llvm/Support/MemoryBuffer.h"
32f4a2713aSLionel Sambuc #include "llvm/Support/SourceMgr.h"
33f4a2713aSLionel Sambuc #include "llvm/Support/TargetRegistry.h"
34f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
35f4a2713aSLionel Sambuc #include "llvm/Target/TargetMachine.h"
36*0a6a1f1dSLionel Sambuc #include "llvm/Target/TargetRegisterInfo.h"
37*0a6a1f1dSLionel Sambuc #include "llvm/Target/TargetSubtargetInfo.h"
38f4a2713aSLionel Sambuc using namespace llvm;
39f4a2713aSLionel Sambuc 
40*0a6a1f1dSLionel Sambuc #define DEBUG_TYPE "asm-printer"
41*0a6a1f1dSLionel Sambuc 
42f4a2713aSLionel Sambuc namespace {
43f4a2713aSLionel Sambuc   struct SrcMgrDiagInfo {
44f4a2713aSLionel Sambuc     const MDNode *LocInfo;
45f4a2713aSLionel Sambuc     LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
46f4a2713aSLionel Sambuc     void *DiagContext;
47f4a2713aSLionel Sambuc   };
48f4a2713aSLionel Sambuc }
49f4a2713aSLionel Sambuc 
50f4a2713aSLionel Sambuc /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
51f4a2713aSLionel Sambuc /// inline asm has an error in it.  diagInfo is a pointer to the SrcMgrDiagInfo
52f4a2713aSLionel Sambuc /// struct above.
srcMgrDiagHandler(const SMDiagnostic & Diag,void * diagInfo)53f4a2713aSLionel Sambuc static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
54f4a2713aSLionel Sambuc   SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
55f4a2713aSLionel Sambuc   assert(DiagInfo && "Diagnostic context not passed down?");
56f4a2713aSLionel Sambuc 
57f4a2713aSLionel Sambuc   // If the inline asm had metadata associated with it, pull out a location
58f4a2713aSLionel Sambuc   // cookie corresponding to which line the error occurred on.
59f4a2713aSLionel Sambuc   unsigned LocCookie = 0;
60f4a2713aSLionel Sambuc   if (const MDNode *LocInfo = DiagInfo->LocInfo) {
61f4a2713aSLionel Sambuc     unsigned ErrorLine = Diag.getLineNo()-1;
62f4a2713aSLionel Sambuc     if (ErrorLine >= LocInfo->getNumOperands())
63f4a2713aSLionel Sambuc       ErrorLine = 0;
64f4a2713aSLionel Sambuc 
65f4a2713aSLionel Sambuc     if (LocInfo->getNumOperands() != 0)
66f4a2713aSLionel Sambuc       if (const ConstantInt *CI =
67*0a6a1f1dSLionel Sambuc               mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
68f4a2713aSLionel Sambuc         LocCookie = CI->getZExtValue();
69f4a2713aSLionel Sambuc   }
70f4a2713aSLionel Sambuc 
71f4a2713aSLionel Sambuc   DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
72f4a2713aSLionel Sambuc }
73f4a2713aSLionel Sambuc 
74f4a2713aSLionel Sambuc /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
EmitInlineAsm(StringRef Str,const MDNode * LocMDNode,InlineAsm::AsmDialect Dialect) const75f4a2713aSLionel Sambuc void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
76f4a2713aSLionel Sambuc                                InlineAsm::AsmDialect Dialect) const {
77f4a2713aSLionel Sambuc   assert(!Str.empty() && "Can't emit empty inline asm block");
78f4a2713aSLionel Sambuc 
79f4a2713aSLionel Sambuc   // Remember if the buffer is nul terminated or not so we can avoid a copy.
80f4a2713aSLionel Sambuc   bool isNullTerminated = Str.back() == 0;
81f4a2713aSLionel Sambuc   if (isNullTerminated)
82f4a2713aSLionel Sambuc     Str = Str.substr(0, Str.size()-1);
83f4a2713aSLionel Sambuc 
84*0a6a1f1dSLionel Sambuc   // If the output streamer does not have mature MC support or the integrated
85*0a6a1f1dSLionel Sambuc   // assembler has been disabled, just emit the blob textually.
86*0a6a1f1dSLionel Sambuc   // Otherwise parse the asm and emit it via MC support.
87f4a2713aSLionel Sambuc   // This is useful in case the asm parser doesn't handle something but the
88f4a2713aSLionel Sambuc   // system assembler does.
89*0a6a1f1dSLionel Sambuc   const MCAsmInfo *MCAI = TM.getMCAsmInfo();
90*0a6a1f1dSLionel Sambuc   assert(MCAI && "No MCAsmInfo");
91*0a6a1f1dSLionel Sambuc   if (!MCAI->useIntegratedAssembler() &&
92*0a6a1f1dSLionel Sambuc       !OutStreamer.isIntegratedAssemblerRequired()) {
93*0a6a1f1dSLionel Sambuc     emitInlineAsmStart(TM.getSubtarget<MCSubtargetInfo>());
94f4a2713aSLionel Sambuc     OutStreamer.EmitRawText(Str);
95*0a6a1f1dSLionel Sambuc     emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), nullptr);
96f4a2713aSLionel Sambuc     return;
97f4a2713aSLionel Sambuc   }
98f4a2713aSLionel Sambuc 
99f4a2713aSLionel Sambuc   SourceMgr SrcMgr;
100f4a2713aSLionel Sambuc   SrcMgrDiagInfo DiagInfo;
101f4a2713aSLionel Sambuc 
102f4a2713aSLionel Sambuc   // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
103f4a2713aSLionel Sambuc   LLVMContext &LLVMCtx = MMI->getModule()->getContext();
104f4a2713aSLionel Sambuc   bool HasDiagHandler = false;
105*0a6a1f1dSLionel Sambuc   if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
106f4a2713aSLionel Sambuc     // If the source manager has an issue, we arrange for srcMgrDiagHandler
107f4a2713aSLionel Sambuc     // to be invoked, getting DiagInfo passed into it.
108f4a2713aSLionel Sambuc     DiagInfo.LocInfo = LocMDNode;
109f4a2713aSLionel Sambuc     DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
110f4a2713aSLionel Sambuc     DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
111f4a2713aSLionel Sambuc     SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
112f4a2713aSLionel Sambuc     HasDiagHandler = true;
113f4a2713aSLionel Sambuc   }
114f4a2713aSLionel Sambuc 
115*0a6a1f1dSLionel Sambuc   std::unique_ptr<MemoryBuffer> Buffer;
116f4a2713aSLionel Sambuc   if (isNullTerminated)
117f4a2713aSLionel Sambuc     Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
118f4a2713aSLionel Sambuc   else
119f4a2713aSLionel Sambuc     Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
120f4a2713aSLionel Sambuc 
121f4a2713aSLionel Sambuc   // Tell SrcMgr about this buffer, it takes ownership of the buffer.
122*0a6a1f1dSLionel Sambuc   SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
123f4a2713aSLionel Sambuc 
124*0a6a1f1dSLionel Sambuc   std::unique_ptr<MCAsmParser> Parser(
125*0a6a1f1dSLionel Sambuc       createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
126f4a2713aSLionel Sambuc 
127*0a6a1f1dSLionel Sambuc   // Initialize the parser with a fresh subtarget info. It is better to use a
128*0a6a1f1dSLionel Sambuc   // new STI here because the parser may modify it and we do not want those
129*0a6a1f1dSLionel Sambuc   // modifications to persist after parsing the inlineasm. The modifications
130*0a6a1f1dSLionel Sambuc   // made by the parser will be seen by the code emitters because it passes
131*0a6a1f1dSLionel Sambuc   // the current STI down to the EncodeInstruction() method.
132*0a6a1f1dSLionel Sambuc   std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
133*0a6a1f1dSLionel Sambuc       TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
134*0a6a1f1dSLionel Sambuc 
135*0a6a1f1dSLionel Sambuc   // Preserve a copy of the original STI because the parser may modify it.  For
136*0a6a1f1dSLionel Sambuc   // example, when switching between arm and thumb mode. If the target needs to
137*0a6a1f1dSLionel Sambuc   // emit code to return to the original state it can do so in
138*0a6a1f1dSLionel Sambuc   // emitInlineAsmEnd().
139*0a6a1f1dSLionel Sambuc   MCSubtargetInfo STIOrig = *STI;
140*0a6a1f1dSLionel Sambuc 
141*0a6a1f1dSLionel Sambuc   MCTargetOptions MCOptions;
142*0a6a1f1dSLionel Sambuc   if (MF)
143*0a6a1f1dSLionel Sambuc     MCOptions = MF->getTarget().Options.MCOptions;
144*0a6a1f1dSLionel Sambuc   std::unique_ptr<MCTargetAsmParser> TAP(
145*0a6a1f1dSLionel Sambuc       TM.getTarget().createMCAsmParser(*STI, *Parser, *MII, MCOptions));
146f4a2713aSLionel Sambuc   if (!TAP)
147f4a2713aSLionel Sambuc     report_fatal_error("Inline asm not supported by this streamer because"
148f4a2713aSLionel Sambuc                        " we don't have an asm parser for this target\n");
149f4a2713aSLionel Sambuc   Parser->setAssemblerDialect(Dialect);
150f4a2713aSLionel Sambuc   Parser->setTargetParser(*TAP.get());
151*0a6a1f1dSLionel Sambuc   if (MF) {
152*0a6a1f1dSLionel Sambuc     const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
153*0a6a1f1dSLionel Sambuc     TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
154*0a6a1f1dSLionel Sambuc   }
155f4a2713aSLionel Sambuc 
156*0a6a1f1dSLionel Sambuc   emitInlineAsmStart(STIOrig);
157f4a2713aSLionel Sambuc   // Don't implicitly switch to the text section before the asm.
158f4a2713aSLionel Sambuc   int Res = Parser->Run(/*NoInitialTextSection*/ true,
159f4a2713aSLionel Sambuc                         /*NoFinalize*/ true);
160*0a6a1f1dSLionel Sambuc   emitInlineAsmEnd(STIOrig, STI.get());
161f4a2713aSLionel Sambuc   if (Res && !HasDiagHandler)
162f4a2713aSLionel Sambuc     report_fatal_error("Error parsing inline asm\n");
163f4a2713aSLionel Sambuc }
164f4a2713aSLionel Sambuc 
EmitMSInlineAsmStr(const char * AsmStr,const MachineInstr * MI,MachineModuleInfo * MMI,int InlineAsmVariant,AsmPrinter * AP,unsigned LocCookie,raw_ostream & OS)165f4a2713aSLionel Sambuc static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
166f4a2713aSLionel Sambuc                                MachineModuleInfo *MMI, int InlineAsmVariant,
167f4a2713aSLionel Sambuc                                AsmPrinter *AP, unsigned LocCookie,
168f4a2713aSLionel Sambuc                                raw_ostream &OS) {
169f4a2713aSLionel Sambuc   // Switch to the inline assembly variant.
170f4a2713aSLionel Sambuc   OS << "\t.intel_syntax\n\t";
171f4a2713aSLionel Sambuc 
172f4a2713aSLionel Sambuc   const char *LastEmitted = AsmStr; // One past the last character emitted.
173f4a2713aSLionel Sambuc   unsigned NumOperands = MI->getNumOperands();
174f4a2713aSLionel Sambuc 
175f4a2713aSLionel Sambuc   while (*LastEmitted) {
176f4a2713aSLionel Sambuc     switch (*LastEmitted) {
177f4a2713aSLionel Sambuc     default: {
178f4a2713aSLionel Sambuc       // Not a special case, emit the string section literally.
179f4a2713aSLionel Sambuc       const char *LiteralEnd = LastEmitted+1;
180f4a2713aSLionel Sambuc       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
181f4a2713aSLionel Sambuc              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
182f4a2713aSLionel Sambuc         ++LiteralEnd;
183f4a2713aSLionel Sambuc 
184f4a2713aSLionel Sambuc       OS.write(LastEmitted, LiteralEnd-LastEmitted);
185f4a2713aSLionel Sambuc       LastEmitted = LiteralEnd;
186f4a2713aSLionel Sambuc       break;
187f4a2713aSLionel Sambuc     }
188f4a2713aSLionel Sambuc     case '\n':
189f4a2713aSLionel Sambuc       ++LastEmitted;   // Consume newline character.
190f4a2713aSLionel Sambuc       OS << '\n';      // Indent code with newline.
191f4a2713aSLionel Sambuc       break;
192f4a2713aSLionel Sambuc     case '$': {
193f4a2713aSLionel Sambuc       ++LastEmitted;   // Consume '$' character.
194f4a2713aSLionel Sambuc       bool Done = true;
195f4a2713aSLionel Sambuc 
196f4a2713aSLionel Sambuc       // Handle escapes.
197f4a2713aSLionel Sambuc       switch (*LastEmitted) {
198f4a2713aSLionel Sambuc       default: Done = false; break;
199f4a2713aSLionel Sambuc       case '$':
200f4a2713aSLionel Sambuc         ++LastEmitted;  // Consume second '$' character.
201f4a2713aSLionel Sambuc         break;
202f4a2713aSLionel Sambuc       }
203f4a2713aSLionel Sambuc       if (Done) break;
204f4a2713aSLionel Sambuc 
205f4a2713aSLionel Sambuc       const char *IDStart = LastEmitted;
206f4a2713aSLionel Sambuc       const char *IDEnd = IDStart;
207f4a2713aSLionel Sambuc       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
208f4a2713aSLionel Sambuc 
209f4a2713aSLionel Sambuc       unsigned Val;
210f4a2713aSLionel Sambuc       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
211f4a2713aSLionel Sambuc         report_fatal_error("Bad $ operand number in inline asm string: '" +
212f4a2713aSLionel Sambuc                            Twine(AsmStr) + "'");
213f4a2713aSLionel Sambuc       LastEmitted = IDEnd;
214f4a2713aSLionel Sambuc 
215f4a2713aSLionel Sambuc       if (Val >= NumOperands-1)
216f4a2713aSLionel Sambuc         report_fatal_error("Invalid $ operand number in inline asm string: '" +
217f4a2713aSLionel Sambuc                            Twine(AsmStr) + "'");
218f4a2713aSLionel Sambuc 
219f4a2713aSLionel Sambuc       // Okay, we finally have a value number.  Ask the target to print this
220f4a2713aSLionel Sambuc       // operand!
221f4a2713aSLionel Sambuc       unsigned OpNo = InlineAsm::MIOp_FirstOperand;
222f4a2713aSLionel Sambuc 
223f4a2713aSLionel Sambuc       bool Error = false;
224f4a2713aSLionel Sambuc 
225f4a2713aSLionel Sambuc       // Scan to find the machine operand number for the operand.
226f4a2713aSLionel Sambuc       for (; Val; --Val) {
227f4a2713aSLionel Sambuc         if (OpNo >= MI->getNumOperands()) break;
228f4a2713aSLionel Sambuc         unsigned OpFlags = MI->getOperand(OpNo).getImm();
229f4a2713aSLionel Sambuc         OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
230f4a2713aSLionel Sambuc       }
231f4a2713aSLionel Sambuc 
232f4a2713aSLionel Sambuc       // We may have a location metadata attached to the end of the
233f4a2713aSLionel Sambuc       // instruction, and at no point should see metadata at any
234f4a2713aSLionel Sambuc       // other point while processing. It's an error if so.
235f4a2713aSLionel Sambuc       if (OpNo >= MI->getNumOperands() ||
236f4a2713aSLionel Sambuc           MI->getOperand(OpNo).isMetadata()) {
237f4a2713aSLionel Sambuc         Error = true;
238f4a2713aSLionel Sambuc       } else {
239f4a2713aSLionel Sambuc         unsigned OpFlags = MI->getOperand(OpNo).getImm();
240f4a2713aSLionel Sambuc         ++OpNo;  // Skip over the ID number.
241f4a2713aSLionel Sambuc 
242f4a2713aSLionel Sambuc         if (InlineAsm::isMemKind(OpFlags)) {
243f4a2713aSLionel Sambuc           Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
244*0a6a1f1dSLionel Sambuc                                             /*Modifier*/ nullptr, OS);
245f4a2713aSLionel Sambuc         } else {
246f4a2713aSLionel Sambuc           Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
247*0a6a1f1dSLionel Sambuc                                       /*Modifier*/ nullptr, OS);
248f4a2713aSLionel Sambuc         }
249f4a2713aSLionel Sambuc       }
250f4a2713aSLionel Sambuc       if (Error) {
251f4a2713aSLionel Sambuc         std::string msg;
252f4a2713aSLionel Sambuc         raw_string_ostream Msg(msg);
253f4a2713aSLionel Sambuc         Msg << "invalid operand in inline asm: '" << AsmStr << "'";
254f4a2713aSLionel Sambuc         MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
255f4a2713aSLionel Sambuc       }
256f4a2713aSLionel Sambuc       break;
257f4a2713aSLionel Sambuc     }
258f4a2713aSLionel Sambuc     }
259f4a2713aSLionel Sambuc   }
260f4a2713aSLionel Sambuc   OS << "\n\t.att_syntax\n" << (char)0;  // null terminate string.
261f4a2713aSLionel Sambuc }
262f4a2713aSLionel Sambuc 
EmitGCCInlineAsmStr(const char * AsmStr,const MachineInstr * MI,MachineModuleInfo * MMI,int InlineAsmVariant,int AsmPrinterVariant,AsmPrinter * AP,unsigned LocCookie,raw_ostream & OS)263f4a2713aSLionel Sambuc static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
264f4a2713aSLionel Sambuc                                 MachineModuleInfo *MMI, int InlineAsmVariant,
265f4a2713aSLionel Sambuc                                 int AsmPrinterVariant, AsmPrinter *AP,
266f4a2713aSLionel Sambuc                                 unsigned LocCookie, raw_ostream &OS) {
267f4a2713aSLionel Sambuc   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
268f4a2713aSLionel Sambuc   const char *LastEmitted = AsmStr; // One past the last character emitted.
269f4a2713aSLionel Sambuc   unsigned NumOperands = MI->getNumOperands();
270f4a2713aSLionel Sambuc 
271f4a2713aSLionel Sambuc   OS << '\t';
272f4a2713aSLionel Sambuc 
273f4a2713aSLionel Sambuc   while (*LastEmitted) {
274f4a2713aSLionel Sambuc     switch (*LastEmitted) {
275f4a2713aSLionel Sambuc     default: {
276f4a2713aSLionel Sambuc       // Not a special case, emit the string section literally.
277f4a2713aSLionel Sambuc       const char *LiteralEnd = LastEmitted+1;
278f4a2713aSLionel Sambuc       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
279f4a2713aSLionel Sambuc              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
280f4a2713aSLionel Sambuc         ++LiteralEnd;
281f4a2713aSLionel Sambuc       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
282f4a2713aSLionel Sambuc         OS.write(LastEmitted, LiteralEnd-LastEmitted);
283f4a2713aSLionel Sambuc       LastEmitted = LiteralEnd;
284f4a2713aSLionel Sambuc       break;
285f4a2713aSLionel Sambuc     }
286f4a2713aSLionel Sambuc     case '\n':
287f4a2713aSLionel Sambuc       ++LastEmitted;   // Consume newline character.
288f4a2713aSLionel Sambuc       OS << '\n';      // Indent code with newline.
289f4a2713aSLionel Sambuc       break;
290f4a2713aSLionel Sambuc     case '$': {
291f4a2713aSLionel Sambuc       ++LastEmitted;   // Consume '$' character.
292f4a2713aSLionel Sambuc       bool Done = true;
293f4a2713aSLionel Sambuc 
294f4a2713aSLionel Sambuc       // Handle escapes.
295f4a2713aSLionel Sambuc       switch (*LastEmitted) {
296f4a2713aSLionel Sambuc       default: Done = false; break;
297f4a2713aSLionel Sambuc       case '$':     // $$ -> $
298f4a2713aSLionel Sambuc         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
299f4a2713aSLionel Sambuc           OS << '$';
300f4a2713aSLionel Sambuc         ++LastEmitted;  // Consume second '$' character.
301f4a2713aSLionel Sambuc         break;
302f4a2713aSLionel Sambuc       case '(':             // $( -> same as GCC's { character.
303f4a2713aSLionel Sambuc         ++LastEmitted;      // Consume '(' character.
304f4a2713aSLionel Sambuc         if (CurVariant != -1)
305f4a2713aSLionel Sambuc           report_fatal_error("Nested variants found in inline asm string: '" +
306f4a2713aSLionel Sambuc                              Twine(AsmStr) + "'");
307f4a2713aSLionel Sambuc         CurVariant = 0;     // We're in the first variant now.
308f4a2713aSLionel Sambuc         break;
309f4a2713aSLionel Sambuc       case '|':
310f4a2713aSLionel Sambuc         ++LastEmitted;  // consume '|' character.
311f4a2713aSLionel Sambuc         if (CurVariant == -1)
312f4a2713aSLionel Sambuc           OS << '|';       // this is gcc's behavior for | outside a variant
313f4a2713aSLionel Sambuc         else
314f4a2713aSLionel Sambuc           ++CurVariant;   // We're in the next variant.
315f4a2713aSLionel Sambuc         break;
316f4a2713aSLionel Sambuc       case ')':         // $) -> same as GCC's } char.
317f4a2713aSLionel Sambuc         ++LastEmitted;  // consume ')' character.
318f4a2713aSLionel Sambuc         if (CurVariant == -1)
319f4a2713aSLionel Sambuc           OS << '}';     // this is gcc's behavior for } outside a variant
320f4a2713aSLionel Sambuc         else
321f4a2713aSLionel Sambuc           CurVariant = -1;
322f4a2713aSLionel Sambuc         break;
323f4a2713aSLionel Sambuc       }
324f4a2713aSLionel Sambuc       if (Done) break;
325f4a2713aSLionel Sambuc 
326f4a2713aSLionel Sambuc       bool HasCurlyBraces = false;
327f4a2713aSLionel Sambuc       if (*LastEmitted == '{') {     // ${variable}
328f4a2713aSLionel Sambuc         ++LastEmitted;               // Consume '{' character.
329f4a2713aSLionel Sambuc         HasCurlyBraces = true;
330f4a2713aSLionel Sambuc       }
331f4a2713aSLionel Sambuc 
332f4a2713aSLionel Sambuc       // If we have ${:foo}, then this is not a real operand reference, it is a
333f4a2713aSLionel Sambuc       // "magic" string reference, just like in .td files.  Arrange to call
334f4a2713aSLionel Sambuc       // PrintSpecial.
335f4a2713aSLionel Sambuc       if (HasCurlyBraces && *LastEmitted == ':') {
336f4a2713aSLionel Sambuc         ++LastEmitted;
337f4a2713aSLionel Sambuc         const char *StrStart = LastEmitted;
338f4a2713aSLionel Sambuc         const char *StrEnd = strchr(StrStart, '}');
339*0a6a1f1dSLionel Sambuc         if (!StrEnd)
340f4a2713aSLionel Sambuc           report_fatal_error("Unterminated ${:foo} operand in inline asm"
341f4a2713aSLionel Sambuc                              " string: '" + Twine(AsmStr) + "'");
342f4a2713aSLionel Sambuc 
343f4a2713aSLionel Sambuc         std::string Val(StrStart, StrEnd);
344f4a2713aSLionel Sambuc         AP->PrintSpecial(MI, OS, Val.c_str());
345f4a2713aSLionel Sambuc         LastEmitted = StrEnd+1;
346f4a2713aSLionel Sambuc         break;
347f4a2713aSLionel Sambuc       }
348f4a2713aSLionel Sambuc 
349f4a2713aSLionel Sambuc       const char *IDStart = LastEmitted;
350f4a2713aSLionel Sambuc       const char *IDEnd = IDStart;
351f4a2713aSLionel Sambuc       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
352f4a2713aSLionel Sambuc 
353f4a2713aSLionel Sambuc       unsigned Val;
354f4a2713aSLionel Sambuc       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
355f4a2713aSLionel Sambuc         report_fatal_error("Bad $ operand number in inline asm string: '" +
356f4a2713aSLionel Sambuc                            Twine(AsmStr) + "'");
357f4a2713aSLionel Sambuc       LastEmitted = IDEnd;
358f4a2713aSLionel Sambuc 
359f4a2713aSLionel Sambuc       char Modifier[2] = { 0, 0 };
360f4a2713aSLionel Sambuc 
361f4a2713aSLionel Sambuc       if (HasCurlyBraces) {
362f4a2713aSLionel Sambuc         // If we have curly braces, check for a modifier character.  This
363f4a2713aSLionel Sambuc         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
364f4a2713aSLionel Sambuc         if (*LastEmitted == ':') {
365f4a2713aSLionel Sambuc           ++LastEmitted;    // Consume ':' character.
366f4a2713aSLionel Sambuc           if (*LastEmitted == 0)
367f4a2713aSLionel Sambuc             report_fatal_error("Bad ${:} expression in inline asm string: '" +
368f4a2713aSLionel Sambuc                                Twine(AsmStr) + "'");
369f4a2713aSLionel Sambuc 
370f4a2713aSLionel Sambuc           Modifier[0] = *LastEmitted;
371f4a2713aSLionel Sambuc           ++LastEmitted;    // Consume modifier character.
372f4a2713aSLionel Sambuc         }
373f4a2713aSLionel Sambuc 
374f4a2713aSLionel Sambuc         if (*LastEmitted != '}')
375f4a2713aSLionel Sambuc           report_fatal_error("Bad ${} expression in inline asm string: '" +
376f4a2713aSLionel Sambuc                              Twine(AsmStr) + "'");
377f4a2713aSLionel Sambuc         ++LastEmitted;    // Consume '}' character.
378f4a2713aSLionel Sambuc       }
379f4a2713aSLionel Sambuc 
380f4a2713aSLionel Sambuc       if (Val >= NumOperands-1)
381f4a2713aSLionel Sambuc         report_fatal_error("Invalid $ operand number in inline asm string: '" +
382f4a2713aSLionel Sambuc                            Twine(AsmStr) + "'");
383f4a2713aSLionel Sambuc 
384f4a2713aSLionel Sambuc       // Okay, we finally have a value number.  Ask the target to print this
385f4a2713aSLionel Sambuc       // operand!
386f4a2713aSLionel Sambuc       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
387f4a2713aSLionel Sambuc         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
388f4a2713aSLionel Sambuc 
389f4a2713aSLionel Sambuc         bool Error = false;
390f4a2713aSLionel Sambuc 
391f4a2713aSLionel Sambuc         // Scan to find the machine operand number for the operand.
392f4a2713aSLionel Sambuc         for (; Val; --Val) {
393f4a2713aSLionel Sambuc           if (OpNo >= MI->getNumOperands()) break;
394f4a2713aSLionel Sambuc           unsigned OpFlags = MI->getOperand(OpNo).getImm();
395f4a2713aSLionel Sambuc           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
396f4a2713aSLionel Sambuc         }
397f4a2713aSLionel Sambuc 
398f4a2713aSLionel Sambuc         // We may have a location metadata attached to the end of the
399f4a2713aSLionel Sambuc         // instruction, and at no point should see metadata at any
400f4a2713aSLionel Sambuc         // other point while processing. It's an error if so.
401f4a2713aSLionel Sambuc         if (OpNo >= MI->getNumOperands() ||
402f4a2713aSLionel Sambuc             MI->getOperand(OpNo).isMetadata()) {
403f4a2713aSLionel Sambuc           Error = true;
404f4a2713aSLionel Sambuc         } else {
405f4a2713aSLionel Sambuc           unsigned OpFlags = MI->getOperand(OpNo).getImm();
406f4a2713aSLionel Sambuc           ++OpNo;  // Skip over the ID number.
407f4a2713aSLionel Sambuc 
408f4a2713aSLionel Sambuc           if (Modifier[0] == 'l')  // labels are target independent
409f4a2713aSLionel Sambuc             // FIXME: What if the operand isn't an MBB, report error?
410f4a2713aSLionel Sambuc             OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
411f4a2713aSLionel Sambuc           else {
412f4a2713aSLionel Sambuc             if (InlineAsm::isMemKind(OpFlags)) {
413f4a2713aSLionel Sambuc               Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
414*0a6a1f1dSLionel Sambuc                                                 Modifier[0] ? Modifier : nullptr,
415f4a2713aSLionel Sambuc                                                 OS);
416f4a2713aSLionel Sambuc             } else {
417f4a2713aSLionel Sambuc               Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
418*0a6a1f1dSLionel Sambuc                                           Modifier[0] ? Modifier : nullptr, OS);
419f4a2713aSLionel Sambuc             }
420f4a2713aSLionel Sambuc           }
421f4a2713aSLionel Sambuc         }
422f4a2713aSLionel Sambuc         if (Error) {
423f4a2713aSLionel Sambuc           std::string msg;
424f4a2713aSLionel Sambuc           raw_string_ostream Msg(msg);
425f4a2713aSLionel Sambuc           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
426f4a2713aSLionel Sambuc           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
427f4a2713aSLionel Sambuc         }
428f4a2713aSLionel Sambuc       }
429f4a2713aSLionel Sambuc       break;
430f4a2713aSLionel Sambuc     }
431f4a2713aSLionel Sambuc     }
432f4a2713aSLionel Sambuc   }
433f4a2713aSLionel Sambuc   OS << '\n' << (char)0;  // null terminate string.
434f4a2713aSLionel Sambuc }
435f4a2713aSLionel Sambuc 
436f4a2713aSLionel Sambuc /// EmitInlineAsm - This method formats and emits the specified machine
437f4a2713aSLionel Sambuc /// instruction that is an inline asm.
EmitInlineAsm(const MachineInstr * MI) const438f4a2713aSLionel Sambuc void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
439f4a2713aSLionel Sambuc   assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
440f4a2713aSLionel Sambuc 
441f4a2713aSLionel Sambuc   // Count the number of register definitions to find the asm string.
442f4a2713aSLionel Sambuc   unsigned NumDefs = 0;
443f4a2713aSLionel Sambuc   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
444f4a2713aSLionel Sambuc        ++NumDefs)
445f4a2713aSLionel Sambuc     assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
446f4a2713aSLionel Sambuc 
447f4a2713aSLionel Sambuc   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
448f4a2713aSLionel Sambuc 
449f4a2713aSLionel Sambuc   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
450f4a2713aSLionel Sambuc   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
451f4a2713aSLionel Sambuc 
452f4a2713aSLionel Sambuc   // If this asmstr is empty, just print the #APP/#NOAPP markers.
453f4a2713aSLionel Sambuc   // These are useful to see where empty asm's wound up.
454f4a2713aSLionel Sambuc   if (AsmStr[0] == 0) {
455*0a6a1f1dSLionel Sambuc     OutStreamer.emitRawComment(MAI->getInlineAsmStart());
456*0a6a1f1dSLionel Sambuc     OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
457f4a2713aSLionel Sambuc     return;
458f4a2713aSLionel Sambuc   }
459f4a2713aSLionel Sambuc 
460f4a2713aSLionel Sambuc   // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
461*0a6a1f1dSLionel Sambuc   // enabled, so we use emitRawComment.
462*0a6a1f1dSLionel Sambuc   OutStreamer.emitRawComment(MAI->getInlineAsmStart());
463f4a2713aSLionel Sambuc 
464f4a2713aSLionel Sambuc   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
465f4a2713aSLionel Sambuc   // it.
466f4a2713aSLionel Sambuc   unsigned LocCookie = 0;
467*0a6a1f1dSLionel Sambuc   const MDNode *LocMD = nullptr;
468f4a2713aSLionel Sambuc   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
469f4a2713aSLionel Sambuc     if (MI->getOperand(i-1).isMetadata() &&
470f4a2713aSLionel Sambuc         (LocMD = MI->getOperand(i-1).getMetadata()) &&
471f4a2713aSLionel Sambuc         LocMD->getNumOperands() != 0) {
472*0a6a1f1dSLionel Sambuc       if (const ConstantInt *CI =
473*0a6a1f1dSLionel Sambuc               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
474f4a2713aSLionel Sambuc         LocCookie = CI->getZExtValue();
475f4a2713aSLionel Sambuc         break;
476f4a2713aSLionel Sambuc       }
477f4a2713aSLionel Sambuc     }
478f4a2713aSLionel Sambuc   }
479f4a2713aSLionel Sambuc 
480f4a2713aSLionel Sambuc   // Emit the inline asm to a temporary string so we can emit it through
481f4a2713aSLionel Sambuc   // EmitInlineAsm.
482f4a2713aSLionel Sambuc   SmallString<256> StringData;
483f4a2713aSLionel Sambuc   raw_svector_ostream OS(StringData);
484f4a2713aSLionel Sambuc 
485f4a2713aSLionel Sambuc   // The variant of the current asmprinter.
486f4a2713aSLionel Sambuc   int AsmPrinterVariant = MAI->getAssemblerDialect();
487f4a2713aSLionel Sambuc   InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
488f4a2713aSLionel Sambuc   AsmPrinter *AP = const_cast<AsmPrinter*>(this);
489f4a2713aSLionel Sambuc   if (InlineAsmVariant == InlineAsm::AD_ATT)
490f4a2713aSLionel Sambuc     EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
491f4a2713aSLionel Sambuc                         AP, LocCookie, OS);
492f4a2713aSLionel Sambuc   else
493f4a2713aSLionel Sambuc     EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
494f4a2713aSLionel Sambuc 
495f4a2713aSLionel Sambuc   EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
496f4a2713aSLionel Sambuc 
497f4a2713aSLionel Sambuc   // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
498*0a6a1f1dSLionel Sambuc   // enabled, so we use emitRawComment.
499*0a6a1f1dSLionel Sambuc   OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
500f4a2713aSLionel Sambuc }
501f4a2713aSLionel Sambuc 
502f4a2713aSLionel Sambuc 
503f4a2713aSLionel Sambuc /// PrintSpecial - Print information related to the specified machine instr
504f4a2713aSLionel Sambuc /// that is independent of the operand, and may be independent of the instr
505f4a2713aSLionel Sambuc /// itself.  This can be useful for portably encoding the comment character
506f4a2713aSLionel Sambuc /// or other bits of target-specific knowledge into the asmstrings.  The
507f4a2713aSLionel Sambuc /// syntax used is ${:comment}.  Targets can override this to add support
508f4a2713aSLionel Sambuc /// for their own strange codes.
PrintSpecial(const MachineInstr * MI,raw_ostream & OS,const char * Code) const509f4a2713aSLionel Sambuc void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
510f4a2713aSLionel Sambuc                               const char *Code) const {
511*0a6a1f1dSLionel Sambuc   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
512f4a2713aSLionel Sambuc   if (!strcmp(Code, "private")) {
513*0a6a1f1dSLionel Sambuc     OS << DL->getPrivateGlobalPrefix();
514f4a2713aSLionel Sambuc   } else if (!strcmp(Code, "comment")) {
515f4a2713aSLionel Sambuc     OS << MAI->getCommentString();
516f4a2713aSLionel Sambuc   } else if (!strcmp(Code, "uid")) {
517f4a2713aSLionel Sambuc     // Comparing the address of MI isn't sufficient, because machineinstrs may
518f4a2713aSLionel Sambuc     // be allocated to the same address across functions.
519f4a2713aSLionel Sambuc 
520f4a2713aSLionel Sambuc     // If this is a new LastFn instruction, bump the counter.
521f4a2713aSLionel Sambuc     if (LastMI != MI || LastFn != getFunctionNumber()) {
522f4a2713aSLionel Sambuc       ++Counter;
523f4a2713aSLionel Sambuc       LastMI = MI;
524f4a2713aSLionel Sambuc       LastFn = getFunctionNumber();
525f4a2713aSLionel Sambuc     }
526f4a2713aSLionel Sambuc     OS << Counter;
527f4a2713aSLionel Sambuc   } else {
528f4a2713aSLionel Sambuc     std::string msg;
529f4a2713aSLionel Sambuc     raw_string_ostream Msg(msg);
530f4a2713aSLionel Sambuc     Msg << "Unknown special formatter '" << Code
531f4a2713aSLionel Sambuc          << "' for machine instr: " << *MI;
532f4a2713aSLionel Sambuc     report_fatal_error(Msg.str());
533f4a2713aSLionel Sambuc   }
534f4a2713aSLionel Sambuc }
535f4a2713aSLionel Sambuc 
536f4a2713aSLionel Sambuc /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
537f4a2713aSLionel Sambuc /// instruction, using the specified assembler variant.  Targets should
538f4a2713aSLionel Sambuc /// override this to format as appropriate.
PrintAsmOperand(const MachineInstr * MI,unsigned OpNo,unsigned AsmVariant,const char * ExtraCode,raw_ostream & O)539f4a2713aSLionel Sambuc bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
540f4a2713aSLionel Sambuc                                  unsigned AsmVariant, const char *ExtraCode,
541f4a2713aSLionel Sambuc                                  raw_ostream &O) {
542f4a2713aSLionel Sambuc   // Does this asm operand have a single letter operand modifier?
543f4a2713aSLionel Sambuc   if (ExtraCode && ExtraCode[0]) {
544f4a2713aSLionel Sambuc     if (ExtraCode[1] != 0) return true; // Unknown modifier.
545f4a2713aSLionel Sambuc 
546f4a2713aSLionel Sambuc     const MachineOperand &MO = MI->getOperand(OpNo);
547f4a2713aSLionel Sambuc     switch (ExtraCode[0]) {
548f4a2713aSLionel Sambuc     default:
549f4a2713aSLionel Sambuc       return true;  // Unknown modifier.
550f4a2713aSLionel Sambuc     case 'c': // Substitute immediate value without immediate syntax
551f4a2713aSLionel Sambuc       if (MO.getType() != MachineOperand::MO_Immediate)
552f4a2713aSLionel Sambuc         return true;
553f4a2713aSLionel Sambuc       O << MO.getImm();
554f4a2713aSLionel Sambuc       return false;
555f4a2713aSLionel Sambuc     case 'n':  // Negate the immediate constant.
556f4a2713aSLionel Sambuc       if (MO.getType() != MachineOperand::MO_Immediate)
557f4a2713aSLionel Sambuc         return true;
558f4a2713aSLionel Sambuc       O << -MO.getImm();
559f4a2713aSLionel Sambuc       return false;
560f4a2713aSLionel Sambuc     }
561f4a2713aSLionel Sambuc   }
562f4a2713aSLionel Sambuc   return true;
563f4a2713aSLionel Sambuc }
564f4a2713aSLionel Sambuc 
PrintAsmMemoryOperand(const MachineInstr * MI,unsigned OpNo,unsigned AsmVariant,const char * ExtraCode,raw_ostream & O)565f4a2713aSLionel Sambuc bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
566f4a2713aSLionel Sambuc                                        unsigned AsmVariant,
567f4a2713aSLionel Sambuc                                        const char *ExtraCode, raw_ostream &O) {
568f4a2713aSLionel Sambuc   // Target doesn't support this yet!
569f4a2713aSLionel Sambuc   return true;
570f4a2713aSLionel Sambuc }
571f4a2713aSLionel Sambuc 
emitInlineAsmStart(const MCSubtargetInfo & StartInfo) const572*0a6a1f1dSLionel Sambuc void AsmPrinter::emitInlineAsmStart(const MCSubtargetInfo &StartInfo) const {}
573*0a6a1f1dSLionel Sambuc 
emitInlineAsmEnd(const MCSubtargetInfo & StartInfo,const MCSubtargetInfo * EndInfo) const574*0a6a1f1dSLionel Sambuc void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
575*0a6a1f1dSLionel Sambuc                                   const MCSubtargetInfo *EndInfo) const {}
576