blob: 38f9c449147da157196ece2085445e0c8b7dedc7 [file] [log] [blame]
Chad Rosier3d45a772012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier4b5e48d2012-08-17 21:19:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for inline asm statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Scope.h"
16#include "clang/Sema/ScopeInfo.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
Chad Rosier6e97be72012-08-22 23:42:09 +000027#include "llvm/MC/MCExpr.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000028#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstPrinter.h"
30#include "llvm/MC/MCInstrInfo.h"
31#include "llvm/MC/MCObjectFileInfo.h"
32#include "llvm/MC/MCRegisterInfo.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSubtargetInfo.h"
Chad Rosier6e97be72012-08-22 23:42:09 +000035#include "llvm/MC/MCSymbol.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000036#include "llvm/MC/MCTargetAsmParser.h"
37#include "llvm/MC/MCParser/MCAsmLexer.h"
38#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosierfb700262012-09-11 23:13:15 +000039#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Chad Rosier4b5e48d2012-08-17 21:19:40 +000040#include "llvm/Support/SourceMgr.h"
41#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/TargetSelect.h"
43using namespace clang;
44using namespace sema;
45
46/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
47/// ignore "noop" casts in places where an lvalue is required by an inline asm.
48/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
49/// provide a strong guidance to not use it.
50///
51/// This method checks to see if the argument is an acceptable l-value and
52/// returns false if it is a case we can handle.
53static bool CheckAsmLValue(const Expr *E, Sema &S) {
54 // Type dependent expressions will be checked during instantiation.
55 if (E->isTypeDependent())
56 return false;
57
58 if (E->isLValue())
59 return false; // Cool, this is an lvalue.
60
61 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
62 // are supposed to allow.
63 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
64 if (E != E2 && E2->isLValue()) {
65 if (!S.getLangOpts().HeinousExtensions)
66 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
67 << E->getSourceRange();
68 else
69 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
70 << E->getSourceRange();
71 // Accept, even if we emitted an error diagnostic.
72 return false;
73 }
74
75 // None of the above, just randomly invalid non-lvalue.
76 return true;
77}
78
79/// isOperandMentioned - Return true if the specified operand # is mentioned
80/// anywhere in the decomposed asm string.
81static bool isOperandMentioned(unsigned OpNo,
Chad Rosierdf5faf52012-08-25 00:11:56 +000082 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +000083 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierdf5faf52012-08-25 00:11:56 +000084 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier4b5e48d2012-08-17 21:19:40 +000085 if (!Piece.isOperand()) continue;
86
87 // If this is a reference to the input and if the input was the smaller
88 // one, then we have to reject this asm.
89 if (Piece.getOperandNo() == OpNo)
90 return true;
91 }
92 return false;
93}
94
Chad Rosierdf5faf52012-08-25 00:11:56 +000095StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
96 bool IsVolatile, unsigned NumOutputs,
97 unsigned NumInputs, IdentifierInfo **Names,
98 MultiExprArg constraints, MultiExprArg exprs,
99 Expr *asmString, MultiExprArg clobbers,
100 SourceLocation RParenLoc) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000101 unsigned NumClobbers = clobbers.size();
102 StringLiteral **Constraints =
Benjamin Kramer5354e772012-08-23 23:38:35 +0000103 reinterpret_cast<StringLiteral**>(constraints.data());
104 Expr **Exprs = exprs.data();
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000105 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000106 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000107
108 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
109
110 // The parser verifies that there is a string literal here.
111 if (!AsmString->isAscii())
112 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
113 << AsmString->getSourceRange());
114
115 for (unsigned i = 0; i != NumOutputs; i++) {
116 StringLiteral *Literal = Constraints[i];
117 if (!Literal->isAscii())
118 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
119 << Literal->getSourceRange());
120
121 StringRef OutputName;
122 if (Names[i])
123 OutputName = Names[i]->getName();
124
125 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
126 if (!Context.getTargetInfo().validateOutputConstraint(Info))
127 return StmtError(Diag(Literal->getLocStart(),
128 diag::err_asm_invalid_output_constraint)
129 << Info.getConstraintStr());
130
131 // Check that the output exprs are valid lvalues.
132 Expr *OutputExpr = Exprs[i];
133 if (CheckAsmLValue(OutputExpr, *this)) {
134 return StmtError(Diag(OutputExpr->getLocStart(),
135 diag::err_asm_invalid_lvalue_in_output)
136 << OutputExpr->getSourceRange());
137 }
138
139 OutputConstraintInfos.push_back(Info);
140 }
141
142 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
143
144 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
145 StringLiteral *Literal = Constraints[i];
146 if (!Literal->isAscii())
147 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
148 << Literal->getSourceRange());
149
150 StringRef InputName;
151 if (Names[i])
152 InputName = Names[i]->getName();
153
154 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
155 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
156 NumOutputs, Info)) {
157 return StmtError(Diag(Literal->getLocStart(),
158 diag::err_asm_invalid_input_constraint)
159 << Info.getConstraintStr());
160 }
161
162 Expr *InputExpr = Exprs[i];
163
164 // Only allow void types for memory constraints.
165 if (Info.allowsMemory() && !Info.allowsRegister()) {
166 if (CheckAsmLValue(InputExpr, *this))
167 return StmtError(Diag(InputExpr->getLocStart(),
168 diag::err_asm_invalid_lvalue_in_input)
169 << Info.getConstraintStr()
170 << InputExpr->getSourceRange());
171 }
172
173 if (Info.allowsRegister()) {
174 if (InputExpr->getType()->isVoidType()) {
175 return StmtError(Diag(InputExpr->getLocStart(),
176 diag::err_asm_invalid_type_in_input)
177 << InputExpr->getType() << Info.getConstraintStr()
178 << InputExpr->getSourceRange());
179 }
180 }
181
182 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
183 if (Result.isInvalid())
184 return StmtError();
185
186 Exprs[i] = Result.take();
187 InputConstraintInfos.push_back(Info);
188 }
189
190 // Check that the clobbers are valid.
191 for (unsigned i = 0; i != NumClobbers; i++) {
192 StringLiteral *Literal = Clobbers[i];
193 if (!Literal->isAscii())
194 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
195 << Literal->getSourceRange());
196
197 StringRef Clobber = Literal->getString();
198
199 if (!Context.getTargetInfo().isValidClobber(Clobber))
200 return StmtError(Diag(Literal->getLocStart(),
201 diag::err_asm_unknown_register_name) << Clobber);
202 }
203
Chad Rosierdf5faf52012-08-25 00:11:56 +0000204 GCCAsmStmt *NS =
205 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
206 NumInputs, Names, Constraints, Exprs, AsmString,
207 NumClobbers, Clobbers, RParenLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000208 // Validate the asm string, ensuring it makes sense given the operands we
209 // have.
Chad Rosierdf5faf52012-08-25 00:11:56 +0000210 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000211 unsigned DiagOffs;
212 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
213 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
214 << AsmString->getSourceRange();
215 return StmtError();
216 }
217
218 // Validate tied input operands for type mismatches.
219 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
220 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
221
222 // If this is a tied constraint, verify that the output and input have
223 // either exactly the same type, or that they are int/ptr operands with the
224 // same size (int/long, int*/long, are ok etc).
225 if (!Info.hasTiedOperand()) continue;
226
227 unsigned TiedTo = Info.getTiedOperand();
228 unsigned InputOpNo = i+NumOutputs;
229 Expr *OutputExpr = Exprs[TiedTo];
230 Expr *InputExpr = Exprs[InputOpNo];
231
232 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
233 continue;
234
235 QualType InTy = InputExpr->getType();
236 QualType OutTy = OutputExpr->getType();
237 if (Context.hasSameType(InTy, OutTy))
238 continue; // All types can be tied to themselves.
239
240 // Decide if the input and output are in the same domain (integer/ptr or
241 // floating point.
242 enum AsmDomain {
243 AD_Int, AD_FP, AD_Other
244 } InputDomain, OutputDomain;
245
246 if (InTy->isIntegerType() || InTy->isPointerType())
247 InputDomain = AD_Int;
248 else if (InTy->isRealFloatingType())
249 InputDomain = AD_FP;
250 else
251 InputDomain = AD_Other;
252
253 if (OutTy->isIntegerType() || OutTy->isPointerType())
254 OutputDomain = AD_Int;
255 else if (OutTy->isRealFloatingType())
256 OutputDomain = AD_FP;
257 else
258 OutputDomain = AD_Other;
259
260 // They are ok if they are the same size and in the same domain. This
261 // allows tying things like:
262 // void* to int*
263 // void* to int if they are the same size.
264 // double to long double if they are the same size.
265 //
266 uint64_t OutSize = Context.getTypeSize(OutTy);
267 uint64_t InSize = Context.getTypeSize(InTy);
268 if (OutSize == InSize && InputDomain == OutputDomain &&
269 InputDomain != AD_Other)
270 continue;
271
272 // If the smaller input/output operand is not mentioned in the asm string,
273 // then we can promote the smaller one to a larger input and the asm string
274 // won't notice.
275 bool SmallerValueMentioned = false;
276
277 // If this is a reference to the input and if the input was the smaller
278 // one, then we have to reject this asm.
279 if (isOperandMentioned(InputOpNo, Pieces)) {
280 // This is a use in the asm string of the smaller operand. Since we
281 // codegen this by promoting to a wider value, the asm will get printed
282 // "wrong".
283 SmallerValueMentioned |= InSize < OutSize;
284 }
285 if (isOperandMentioned(TiedTo, Pieces)) {
286 // If this is a reference to the output, and if the output is the larger
287 // value, then it's ok because we'll promote the input to the larger type.
288 SmallerValueMentioned |= OutSize < InSize;
289 }
290
291 // If the smaller value wasn't mentioned in the asm string, and if the
292 // output was a register, just extend the shorter one to the size of the
293 // larger one.
294 if (!SmallerValueMentioned && InputDomain != AD_Other &&
295 OutputConstraintInfos[TiedTo].allowsRegister())
296 continue;
297
298 // Either both of the operands were mentioned or the smaller one was
299 // mentioned. One more special case that we'll allow: if the tied input is
300 // integer, unmentioned, and is a constant, then we'll allow truncating it
301 // down to the size of the destination.
302 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
303 !isOperandMentioned(InputOpNo, Pieces) &&
304 InputExpr->isEvaluatable(Context)) {
305 CastKind castKind =
306 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
307 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
308 Exprs[InputOpNo] = InputExpr;
309 NS->setInputExpr(i, InputExpr);
310 continue;
311 }
312
313 Diag(InputExpr->getLocStart(),
314 diag::err_asm_tying_incompatible_types)
315 << InTy << OutTy << OutputExpr->getSourceRange()
316 << InputExpr->getSourceRange();
317 return StmtError();
318 }
319
320 return Owned(NS);
321}
322
323// isMSAsmKeyword - Return true if this is an MS-style inline asm keyword. These
324// require special handling.
325static bool isMSAsmKeyword(StringRef Name) {
326 bool Ret = llvm::StringSwitch<bool>(Name)
327 .Cases("EVEN", "ALIGN", true) // Alignment directives.
328 .Cases("LENGTH", "SIZE", "TYPE", true) // Type and variable sizes.
329 .Case("_emit", true) // _emit Pseudoinstruction.
330 .Default(false);
331 return Ret;
332}
333
Chad Rosier358ab762012-08-22 21:08:06 +0000334// getSpelling - Get the spelling of the AsmTok token.
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000335static StringRef getSpelling(Sema &SemaRef, Token AsmTok) {
336 StringRef Asm;
337 SmallString<512> TokenBuf;
338 TokenBuf.resize(512);
339 bool StringInvalid = false;
340 Asm = SemaRef.PP.getSpelling(AsmTok, TokenBuf, &StringInvalid);
341 assert (!StringInvalid && "Expected valid string!");
342 return Asm;
343}
344
Chad Rosier358ab762012-08-22 21:08:06 +0000345// Determine if we should bail on this MSAsm instruction.
Chad Rosier2735df22012-08-22 19:18:30 +0000346static bool bailOnMSAsm(std::vector<StringRef> Piece) {
347 for (unsigned i = 0, e = Piece.size(); i != e; ++i)
348 if (isMSAsmKeyword(Piece[i]))
349 return true;
350 return false;
351}
352
Chad Rosier358ab762012-08-22 21:08:06 +0000353// Determine if we should bail on this MSAsm block.
Chad Rosier2735df22012-08-22 19:18:30 +0000354static bool bailOnMSAsm(std::vector<std::vector<StringRef> > Pieces) {
355 for (unsigned i = 0, e = Pieces.size(); i != e; ++i)
356 if (bailOnMSAsm(Pieces[i]))
357 return true;
358 return false;
359}
360
Chad Rosier358ab762012-08-22 21:08:06 +0000361// Determine if this is a simple MSAsm instruction.
Chad Rosier98ac6082012-08-21 23:09:21 +0000362static bool isSimpleMSAsm(std::vector<StringRef> &Pieces,
363 const TargetInfo &TI) {
364 if (isMSAsmKeyword(Pieces[0]))
365 return false;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000366
Chad Rosier180d9d92012-10-02 18:51:05 +0000367 for (unsigned i = 1, e = Pieces.size(); i != e; ++i) {
Chad Rosier90a76e52012-10-11 21:44:41 +0000368 if (!TI.isValidGCCRegisterName(Pieces[i]))
Chad Rosier98ac6082012-08-21 23:09:21 +0000369 return false;
Chad Rosier180d9d92012-10-02 18:51:05 +0000370 }
Chad Rosier153f8ec2012-08-22 19:50:28 +0000371 return true;
372}
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000373
Chad Rosier358ab762012-08-22 21:08:06 +0000374// Determine if this is a simple MSAsm block.
Chad Rosier153f8ec2012-08-22 19:50:28 +0000375static bool isSimpleMSAsm(std::vector<std::vector<StringRef> > Pieces,
376 const TargetInfo &TI) {
377 for (unsigned i = 0, e = Pieces.size(); i != e; ++i)
378 if (!isSimpleMSAsm(Pieces[i], TI))
379 return false;
Chad Rosier98ac6082012-08-21 23:09:21 +0000380 return true;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000381}
382
Bob Wilson40d39e32012-09-24 19:57:55 +0000383// Break the AsmString into pieces (i.e., mnemonic and operands).
Chad Rosier38c71d32012-08-21 21:56:39 +0000384static void buildMSAsmPieces(StringRef Asm, std::vector<StringRef> &Pieces) {
385 std::pair<StringRef,StringRef> Split = Asm.split(' ');
386
387 // Mnemonic
388 Pieces.push_back(Split.first);
389 Asm = Split.second;
390
391 // Operands
392 while (!Asm.empty()) {
393 Split = Asm.split(", ");
394 Pieces.push_back(Split.first);
395 Asm = Split.second;
396 }
397}
398
Chad Rosierf0fbd772012-08-22 21:04:07 +0000399static void buildMSAsmPieces(std::vector<std::string> &AsmStrings,
400 std::vector<std::vector<StringRef> > &Pieces) {
401 for (unsigned i = 0, e = AsmStrings.size(); i != e; ++i)
402 buildMSAsmPieces(AsmStrings[i], Pieces[i]);
403}
404
Chad Rosierb55e6022012-09-13 00:06:55 +0000405// Build the individual assembly instruction(s) and place them in the AsmStrings
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000406// vector. These strings are fed to the AsmParser. Returns true on error.
407static bool buildMSAsmStrings(Sema &SemaRef,
408 SourceLocation AsmLoc,
409 ArrayRef<Token> AsmToks,
Chad Rosier6ec69c32012-10-12 00:02:48 +0000410 std::vector<std::string> &AsmStrings) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000411 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000412
413 SmallString<512> Asm;
Chad Rosier9072a022012-08-22 20:30:58 +0000414 unsigned startTok = 0;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000415 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
Bob Wilson40d39e32012-09-24 19:57:55 +0000416 bool isNewAsm = ((i == 0) ||
417 AsmToks[i].isAtStartOfLine() ||
418 AsmToks[i].is(tok::kw_asm));
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000419
420 if (isNewAsm) {
Chad Rosier38c71d32012-08-21 21:56:39 +0000421 if (i) {
Benjamin Kramer32f3acc2012-08-24 20:43:21 +0000422 AsmStrings.push_back(Asm.str());
Chad Rosier9072a022012-08-22 20:30:58 +0000423 startTok = i;
Chad Rosier38c71d32012-08-21 21:56:39 +0000424 Asm.clear();
Chad Rosier38c71d32012-08-21 21:56:39 +0000425 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000426 if (AsmToks[i].is(tok::kw_asm)) {
427 i++; // Skip __asm
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000428 if (i == e) {
429 SemaRef.Diag(AsmLoc, diag::err_asm_empty);
430 return true;
431 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000432 }
433 }
434
Chad Rosierb55e6022012-09-13 00:06:55 +0000435 if (i && AsmToks[i].hasLeadingSpace() && !isNewAsm)
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000436 Asm += ' ';
Chad Rosier4de97162012-09-11 00:51:28 +0000437
438 StringRef Spelling = getSpelling(SemaRef, AsmToks[i]);
439 Asm += Spelling;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000440 }
Benjamin Kramer32f3acc2012-08-24 20:43:21 +0000441 AsmStrings.push_back(Asm.str());
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000442
443 return false;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000444}
445
Chad Rosierc6916492012-09-06 19:56:25 +0000446#define DEF_SIMPLE_MSASM(STR) \
Chad Rosier89fb6d72012-08-28 20:28:20 +0000447 MSAsmStmt *NS = \
448 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true, \
449 /*IsVolatile*/ true, AsmToks, Inputs, Outputs, \
Chad Rosierc6916492012-09-06 19:56:25 +0000450 InputExprs, OutputExprs, STR, Constraints, \
Chad Rosier89fb6d72012-08-28 20:28:20 +0000451 Clobbers, EndLoc);
Chad Rosier2735df22012-08-22 19:18:30 +0000452
Chad Rosierb55e6022012-09-13 00:06:55 +0000453StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
454 ArrayRef<Token> AsmToks,SourceLocation EndLoc) {
Chad Rosier89fb6d72012-08-28 20:28:20 +0000455 SmallVector<StringRef, 4> Constraints;
456 std::vector<std::string> InputConstraints;
457 std::vector<std::string> OutputConstraints;
Chad Rosier4112a4c2012-08-28 20:35:06 +0000458 SmallVector<StringRef, 4> Clobbers;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000459 std::set<std::string> ClobberRegs;
Chad Rosierb55e6022012-09-13 00:06:55 +0000460
461 // FIXME: Use a struct to hold the various expression information.
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000462 SmallVector<IdentifierInfo*, 4> Inputs;
463 SmallVector<IdentifierInfo*, 4> Outputs;
Chad Rosier633abb02012-08-24 00:07:09 +0000464 SmallVector<Expr*, 4> InputExprs;
465 SmallVector<Expr*, 4> OutputExprs;
Chad Rosieracc22b62012-09-06 19:35:00 +0000466 SmallVector<std::string, 4> InputExprNames;
467 SmallVector<std::string, 4> OutputExprNames;
Chad Rosierb55e6022012-09-13 00:06:55 +0000468 SmallVector<unsigned, 4> InputExprStrIdx;
469 SmallVector<unsigned, 4> OutputExprStrIdx;
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000470
471 // Empty asm statements don't need to instantiate the AsmParser, etc.
Chad Rosierc6916492012-09-06 19:56:25 +0000472 StringRef EmptyAsmStr;
473 if (AsmToks.empty()) { DEF_SIMPLE_MSASM(EmptyAsmStr); return Owned(NS); }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000474
Chad Rosier38c71d32012-08-21 21:56:39 +0000475 std::vector<std::string> AsmStrings;
Chad Rosier6ec69c32012-10-12 00:02:48 +0000476 if (buildMSAsmStrings(*this, AsmLoc, AsmToks, AsmStrings))
Bob Wilsonb0f6b9c2012-09-24 19:57:59 +0000477 return StmtError();
Chad Rosier38c71d32012-08-21 21:56:39 +0000478
Chad Rosiere78460f2012-08-22 20:57:07 +0000479 std::vector<std::vector<StringRef> > Pieces(AsmStrings.size());
Chad Rosierf0fbd772012-08-22 21:04:07 +0000480 buildMSAsmPieces(AsmStrings, Pieces);
Chad Rosier153f8ec2012-08-22 19:50:28 +0000481
482 bool IsSimple = isSimpleMSAsm(Pieces, Context.getTargetInfo());
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000483
Chad Rosier2735df22012-08-22 19:18:30 +0000484 // AsmParser doesn't fully support these asm statements.
Chad Rosierc6916492012-09-06 19:56:25 +0000485 if (bailOnMSAsm(Pieces)) { DEF_SIMPLE_MSASM(EmptyAsmStr); return Owned(NS); }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000486
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000487 // Get the target specific parser.
488 std::string Error;
489 const std::string &TT = Context.getTargetInfo().getTriple().getTriple();
490 const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
491
492 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
493 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
494 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
495 OwningPtr<llvm::MCSubtargetInfo>
496 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
497
Chad Rosier25bd2982012-08-23 15:44:35 +0000498 for (unsigned StrIdx = 0, e = AsmStrings.size(); StrIdx != e; ++StrIdx) {
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000499 llvm::SourceMgr SrcMgr;
500 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
501 llvm::MemoryBuffer *Buffer =
Chad Rosier25bd2982012-08-23 15:44:35 +0000502 llvm::MemoryBuffer::getMemBuffer(AsmStrings[StrIdx], "<inline asm>");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000503
504 // Tell SrcMgr about this buffer, which is what the parser will pick up.
505 SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
506
507 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
508 OwningPtr<llvm::MCAsmParser>
509 Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
510 OwningPtr<llvm::MCTargetAsmParser>
511 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
512 // Change to the Intel dialect.
513 Parser->setAssemblerDialect(1);
514 Parser->setTargetParser(*TargetParser.get());
515
516 // Prime the lexer.
517 Parser->Lex();
518
519 // Parse the opcode.
520 StringRef IDVal;
521 Parser->ParseIdentifier(IDVal);
522
523 // Canonicalize the opcode to lower case.
Chad Rosierbe5c3fb2012-09-03 02:30:13 +0000524 SmallString<128> OpcodeStr;
Chad Rosierb706d902012-08-28 22:08:58 +0000525 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosierbe5c3fb2012-09-03 02:30:13 +0000526 OpcodeStr.push_back(tolower(IDVal[i]));
Chad Rosier3d442192012-09-21 22:22:39 +0000527 // FIXME: Convert to a StmtError.
528 assert(TargetParser->mnemonicIsValid(OpcodeStr) && "Invalid mnemonic!");
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000529
530 // Parse the operands.
531 llvm::SMLoc IDLoc;
532 SmallVector<llvm::MCParsedAsmOperand*, 8> Operands;
Chad Rosierbe5c3fb2012-09-03 02:30:13 +0000533 bool HadError = TargetParser->ParseInstruction(OpcodeStr.str(), IDLoc,
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000534 Operands);
Chad Rosier2735df22012-08-22 19:18:30 +0000535 // If we had an error parsing the operands, fail gracefully.
Chad Rosierc6916492012-09-06 19:56:25 +0000536 if (HadError) { DEF_SIMPLE_MSASM(EmptyAsmStr); return Owned(NS); }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000537
538 // Match the MCInstr.
Chad Rosierbe5c3fb2012-09-03 02:30:13 +0000539 unsigned Kind;
Chad Rosier3034d882012-10-01 23:45:59 +0000540 unsigned Opcode;
Chad Rosier83591b62012-08-21 18:15:08 +0000541 unsigned ErrorInfo;
Chad Rosier3034d882012-10-01 23:45:59 +0000542 SmallVector<std::pair< unsigned, std::string >, 4> MapAndConstraints;
543 HadError = TargetParser->MatchInstruction(IDLoc, Operands, *Str.get(), Kind,
544 Opcode, MapAndConstraints,
Chad Rosier7065c522012-09-03 03:16:15 +0000545 ErrorInfo,
Chad Rosier51a6b3f2012-08-21 19:37:55 +0000546 /*matchingInlineAsm*/ true);
Chad Rosier2735df22012-08-22 19:18:30 +0000547 // If we had an error parsing the operands, fail gracefully.
Chad Rosierc6916492012-09-06 19:56:25 +0000548 if (HadError) { DEF_SIMPLE_MSASM(EmptyAsmStr); return Owned(NS); }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000549
550 // Get the instruction descriptor.
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000551 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
Chad Rosier3034d882012-10-01 23:45:59 +0000552 const llvm::MCInstrDesc &Desc = MII->get(Opcode);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000553 llvm::MCInstPrinter *IP =
554 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
555
Chad Rosier6e97be72012-08-22 23:42:09 +0000556 // Build the list of clobbers, outputs and inputs.
Chad Rosierfd5e56e2012-08-22 22:10:51 +0000557 unsigned NumDefs = Desc.getNumDefs();
Chad Rosier1b497f22012-09-03 20:40:52 +0000558 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
Chad Rosier3034d882012-10-01 23:45:59 +0000559 // Skip immediates.
560 if (Operands[i]->isImm())
Chad Rosierfb700262012-09-11 23:13:15 +0000561 continue;
562
Chad Rosier3034d882012-10-01 23:45:59 +0000563 // Register.
564 if (Operands[i]->isReg()) {
565 // Clobber.
566 if (NumDefs && (MapAndConstraints[i-1].first < NumDefs)) {
Chad Rosier7f9678b2012-09-12 18:14:25 +0000567 std::string Reg;
568 llvm::raw_string_ostream OS(Reg);
Chad Rosier3034d882012-10-01 23:45:59 +0000569 IP->printRegName(OS, Operands[i]->getReg());
Chad Rosier7f9678b2012-09-12 18:14:25 +0000570 StringRef Clobber(OS.str());
571 if (!Context.getTargetInfo().isValidClobber(Clobber))
572 return StmtError(
573 Diag(AsmLoc, diag::err_asm_unknown_register_name) << Clobber);
574 ClobberRegs.insert(Reg);
Chad Rosier1b497f22012-09-03 20:40:52 +0000575 }
Chad Rosier3034d882012-10-01 23:45:59 +0000576 continue;
577 }
578
579 // Expr/Input or Output.
Chad Rosier90a76e52012-10-11 21:44:41 +0000580 StringRef Name = Pieces[StrIdx][i];
Chad Rosier34404152012-10-11 21:28:29 +0000581 if (IdentifierInfo *II = &Context.Idents.get(Name)) {
Chad Rosier3034d882012-10-01 23:45:59 +0000582 CXXScopeSpec SS;
583 UnqualifiedId Id;
584 SourceLocation Loc;
585 Id.setIdentifier(II, AsmLoc);
586 ExprResult Result = ActOnIdExpression(getCurScope(), SS, Loc, Id,
587 false, false);
588 if (!Result.isInvalid()) {
589 // FIXME: Determine the proper constraints.
590 bool isMemDef = (i == 1) && Desc.mayStore();
591 if (isMemDef) {
592 Outputs.push_back(II);
593 OutputExprs.push_back(Result.take());
594 OutputExprNames.push_back(Name.str());
595 OutputExprStrIdx.push_back(StrIdx);
596
597 std::string Constraint = "=" + MapAndConstraints[i-1].second;
598 OutputConstraints.push_back(Constraint);
599 } else {
600 Inputs.push_back(II);
601 InputExprs.push_back(Result.take());
602 InputExprNames.push_back(Name.str());
603 InputExprStrIdx.push_back(StrIdx);
604 InputConstraints.push_back(MapAndConstraints[i-1].second);
Chad Rosier633abb02012-08-24 00:07:09 +0000605 }
Chad Rosier6e97be72012-08-22 23:42:09 +0000606 }
Chad Rosierfd5e56e2012-08-22 22:10:51 +0000607 }
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000608 }
609 }
610 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
611 E = ClobberRegs.end(); I != E; ++I)
612 Clobbers.push_back(*I);
613
Chad Rosier89fb6d72012-08-28 20:28:20 +0000614 // Merge the output and input constraints. Output constraints are expected
615 // first.
616 for (std::vector<std::string>::iterator I = OutputConstraints.begin(),
617 E = OutputConstraints.end(); I != E; ++I)
618 Constraints.push_back(*I);
619
620 for (std::vector<std::string>::iterator I = InputConstraints.begin(),
621 E = InputConstraints.end(); I != E; ++I)
622 Constraints.push_back(*I);
623
Chad Rosieracc22b62012-09-06 19:35:00 +0000624 // Enumerate the AsmString expressions.
Chad Rosieracc22b62012-09-06 19:35:00 +0000625 unsigned OpNum = 0;
626 for (unsigned i = 0, e = OutputExprNames.size(); i != e; ++i, ++OpNum) {
Chad Rosierb55e6022012-09-13 00:06:55 +0000627 unsigned StrIdx = OutputExprStrIdx[i];
628 // Iterate over the assembly instruction pieces, skipping the mnemonic.
629 for (unsigned j = 1, f = Pieces[StrIdx].size(); j != f; ++j) {
630 // If the operand and the expression name match, then rewrite the operand.
631 if (OutputExprNames[i] == Pieces[StrIdx][j]) {
632 SmallString<32> Res;
633 llvm::raw_svector_ostream OS(Res);
634 OS << '$' << OpNum;
635 OutputExprNames[i] = OS.str();
636 Pieces[StrIdx][j] = OutputExprNames[i];
637 break;
638 }
Chad Rosierb55e6022012-09-13 00:06:55 +0000639 }
Chad Rosieracc22b62012-09-06 19:35:00 +0000640 }
641 for (unsigned i = 0, e = InputExprNames.size(); i != e; ++i, ++OpNum) {
Chad Rosierb55e6022012-09-13 00:06:55 +0000642 unsigned StrIdx = InputExprStrIdx[i];
643 // Iterate over the assembly instruction pieces, skipping the mnemonic.
644 for (unsigned j = 1, f = Pieces[StrIdx].size(); j != f; ++j) {
645 // If the operand and the expression name match, then rewrite the operand.
646 if (InputExprNames[i] == Pieces[StrIdx][j]) {
647 SmallString<32> Res;
648 llvm::raw_svector_ostream OS(Res);
649 OS << '$' << OpNum;
650 InputExprNames[i] = OS.str();
651 Pieces[StrIdx][j] = InputExprNames[i];
652 break;
653 }
Chad Rosierb55e6022012-09-13 00:06:55 +0000654 }
655 }
656
657 // Emit the IR assembly string.
658 std::string AsmString;
659 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
660 // Skip empty asm stmts.
661 if (Pieces[i].empty()) continue;
662
663 if (i > 0)
664 AsmString += "\n\t";
665
666 // Emit the mnemonic.
667 AsmString += Pieces[i][0];
668 if (Pieces[i].size() > 1)
669 AsmString += ' ';
670
671 // Emit the operands adding $$ to constants.
672 for (unsigned j = 1, f = Pieces[i].size(); j != f; ++j) {
673 if (j > 1) AsmString += ", ";
674 unsigned Val;
675 if (!Pieces[i][j].getAsInteger(0, Val))
676 AsmString += "$$";
677
678 AsmString += Pieces[i][j];
679 }
Chad Rosieracc22b62012-09-06 19:35:00 +0000680 }
681
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000682 MSAsmStmt *NS =
683 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
684 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
Chad Rosier89fb6d72012-08-28 20:28:20 +0000685 InputExprs, OutputExprs, AsmString, Constraints,
686 Clobbers, EndLoc);
Chad Rosier4b5e48d2012-08-17 21:19:40 +0000687 return Owned(NS);
688}