blob: d19d8819d8e234b40bd352391c20dd55dde1a633 [file] [log] [blame]
Chad Rosier571c5e92012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier0731aff2012-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"
Weiming Zhao71ac2402015-02-03 22:35:58 +000015#include "clang/AST/ExprCXX.h"
Chad Rosier5c563642012-10-25 21:49:22 +000016#include "clang/AST/RecordLayout.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000017#include "clang/AST/TypeLoc.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000018#include "clang/Basic/TargetInfo.h"
Ehsan Akhgari31097582014-09-22 02:21:54 +000019#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Initialization.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000024#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/BitVector.h"
Alp Toker10399272014-06-08 05:11:37 +000026#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000027using namespace clang;
28using namespace sema;
29
30/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
31/// ignore "noop" casts in places where an lvalue is required by an inline asm.
32/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
33/// provide a strong guidance to not use it.
34///
35/// This method checks to see if the argument is an acceptable l-value and
36/// returns false if it is a case we can handle.
37static bool CheckAsmLValue(const Expr *E, Sema &S) {
38 // Type dependent expressions will be checked during instantiation.
39 if (E->isTypeDependent())
40 return false;
41
42 if (E->isLValue())
43 return false; // Cool, this is an lvalue.
44
45 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
46 // are supposed to allow.
47 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
48 if (E != E2 && E2->isLValue()) {
49 if (!S.getLangOpts().HeinousExtensions)
50 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
51 << E->getSourceRange();
52 else
53 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
54 << E->getSourceRange();
55 // Accept, even if we emitted an error diagnostic.
56 return false;
57 }
58
59 // None of the above, just randomly invalid non-lvalue.
60 return true;
61}
62
63/// isOperandMentioned - Return true if the specified operand # is mentioned
64/// anywhere in the decomposed asm string.
65static bool isOperandMentioned(unsigned OpNo,
Chad Rosierde70e0e2012-08-25 00:11:56 +000066 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +000067 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +000068 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier0731aff2012-08-17 21:19:40 +000069 if (!Piece.isOperand()) continue;
70
71 // If this is a reference to the input and if the input was the smaller
72 // one, then we have to reject this asm.
73 if (Piece.getOperandNo() == OpNo)
74 return true;
75 }
76 return false;
77}
78
Hans Wennborge9d240a2014-10-08 01:58:02 +000079static bool CheckNakedParmReference(Expr *E, Sema &S) {
80 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
81 if (!Func)
82 return false;
83 if (!Func->hasAttr<NakedAttr>())
84 return false;
85
86 SmallVector<Expr*, 4> WorkList;
87 WorkList.push_back(E);
88 while (WorkList.size()) {
89 Expr *E = WorkList.pop_back_val();
Weiming Zhao71ac2402015-02-03 22:35:58 +000090 if (isa<CXXThisExpr>(E)) {
91 S.Diag(E->getLocStart(), diag::err_asm_naked_this_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
93 return true;
94 }
Hans Wennborge9d240a2014-10-08 01:58:02 +000095 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
96 if (isa<ParmVarDecl>(DRE->getDecl())) {
97 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
98 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
99 return true;
100 }
101 }
102 for (Stmt *Child : E->children()) {
103 if (Expr *E = dyn_cast_or_null<Expr>(Child))
104 WorkList.push_back(E);
105 }
106 }
107 return false;
108}
109
Chad Rosierde70e0e2012-08-25 00:11:56 +0000110StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
111 bool IsVolatile, unsigned NumOutputs,
112 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000113 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000114 Expr *asmString, MultiExprArg clobbers,
115 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000116 unsigned NumClobbers = clobbers.size();
117 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000118 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000119 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000120 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000121
122 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
123
124 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000125 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000126
Artem Belevichfa62ad42015-04-27 19:37:53 +0000127 bool ValidateConstraints =
128 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl());
Artem Belevich5196fe72015-03-19 18:40:25 +0000129
Chad Rosier0731aff2012-08-17 21:19:40 +0000130 for (unsigned i = 0; i != NumOutputs; i++) {
131 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000132 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000133
134 StringRef OutputName;
135 if (Names[i])
136 OutputName = Names[i]->getName();
137
138 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Artem Belevich5196fe72015-03-19 18:40:25 +0000139 if (ValidateConstraints &&
140 !Context.getTargetInfo().validateOutputConstraint(Info))
Chad Rosier0731aff2012-08-17 21:19:40 +0000141 return StmtError(Diag(Literal->getLocStart(),
142 diag::err_asm_invalid_output_constraint)
143 << Info.getConstraintStr());
144
David Majnemer0f4d6412014-12-29 09:30:33 +0000145 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
146 if (ER.isInvalid())
147 return StmtError();
148 Exprs[i] = ER.get();
149
Chad Rosier0731aff2012-08-17 21:19:40 +0000150 // Check that the output exprs are valid lvalues.
151 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000152
Hans Wennborge9d240a2014-10-08 01:58:02 +0000153 // Referring to parameters is not allowed in naked functions.
154 if (CheckNakedParmReference(OutputExpr, *this))
155 return StmtError();
156
Alexander Musmaneae29e22015-06-05 13:40:59 +0000157 // Bitfield can't be referenced with a pointer.
158 if (Info.allowsMemory() && OutputExpr->refersToBitField())
159 return StmtError(Diag(OutputExpr->getLocStart(),
160 diag::err_asm_bitfield_in_memory_constraint)
161 << 1
162 << Info.getConstraintStr()
163 << OutputExpr->getSourceRange());
164
Chad Rosier0731aff2012-08-17 21:19:40 +0000165 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000166
David Majnemer0f4d6412014-12-29 09:30:33 +0000167 // If this is dependent, just continue.
168 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000169 continue;
170
David Majnemer0f4d6412014-12-29 09:30:33 +0000171 Expr::isModifiableLvalueResult IsLV =
172 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
173 switch (IsLV) {
174 case Expr::MLV_Valid:
175 // Cool, this is an lvalue.
176 break;
David Majnemer04b78412014-12-29 10:29:53 +0000177 case Expr::MLV_ArrayType:
178 // This is OK too.
179 break;
David Majnemer0f4d6412014-12-29 09:30:33 +0000180 case Expr::MLV_LValueCast: {
181 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
182 if (!getLangOpts().HeinousExtensions) {
183 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
184 << OutputExpr->getSourceRange();
185 } else {
186 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
187 << OutputExpr->getSourceRange();
188 }
189 // Accept, even if we emitted an error diagnostic.
190 break;
191 }
192 case Expr::MLV_IncompleteType:
193 case Expr::MLV_IncompleteVoidType:
194 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
195 diag::err_dereference_incomplete_type))
196 return StmtError();
197 default:
198 return StmtError(Diag(OutputExpr->getLocStart(),
199 diag::err_asm_invalid_lvalue_in_output)
200 << OutputExpr->getSourceRange());
201 }
202
203 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Akira Hatanaka974131e2014-09-18 18:17:18 +0000204 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
205 Size))
206 return StmtError(Diag(OutputExpr->getLocStart(),
207 diag::err_asm_invalid_output_size)
208 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000209 }
210
211 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
212
213 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
214 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000215 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000216
217 StringRef InputName;
218 if (Names[i])
219 InputName = Names[i]->getName();
220
221 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Artem Belevich5196fe72015-03-19 18:40:25 +0000222 if (ValidateConstraints &&
223 !Context.getTargetInfo().validateInputConstraint(
224 OutputConstraintInfos.data(), NumOutputs, Info)) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000225 return StmtError(Diag(Literal->getLocStart(),
226 diag::err_asm_invalid_input_constraint)
227 << Info.getConstraintStr());
228 }
229
David Majnemer0f4d6412014-12-29 09:30:33 +0000230 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
231 if (ER.isInvalid())
232 return StmtError();
233 Exprs[i] = ER.get();
234
Chad Rosier0731aff2012-08-17 21:19:40 +0000235 Expr *InputExpr = Exprs[i];
236
Hans Wennborge9d240a2014-10-08 01:58:02 +0000237 // Referring to parameters is not allowed in naked functions.
238 if (CheckNakedParmReference(InputExpr, *this))
239 return StmtError();
240
Alexander Musmaneae29e22015-06-05 13:40:59 +0000241 // Bitfield can't be referenced with a pointer.
242 if (Info.allowsMemory() && InputExpr->refersToBitField())
243 return StmtError(Diag(InputExpr->getLocStart(),
244 diag::err_asm_bitfield_in_memory_constraint)
245 << 0
246 << Info.getConstraintStr()
247 << InputExpr->getSourceRange());
248
Chad Rosier0731aff2012-08-17 21:19:40 +0000249 // Only allow void types for memory constraints.
250 if (Info.allowsMemory() && !Info.allowsRegister()) {
251 if (CheckAsmLValue(InputExpr, *this))
252 return StmtError(Diag(InputExpr->getLocStart(),
253 diag::err_asm_invalid_lvalue_in_input)
254 << Info.getConstraintStr()
255 << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000256 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
257 llvm::APSInt Result;
258 if (!InputExpr->EvaluateAsInt(Result, Context))
259 return StmtError(
Joerg Sonnenbergera43872c2015-01-22 21:01:00 +0000260 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
261 << Info.getConstraintStr() << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000262 if (Result.slt(Info.getImmConstantMin()) ||
263 Result.sgt(Info.getImmConstantMax()))
264 return StmtError(Diag(InputExpr->getLocStart(),
265 diag::err_invalid_asm_value_for_constraint)
266 << Result.toString(10) << Info.getConstraintStr()
267 << InputExpr->getSourceRange());
268
David Majnemerade4bee2014-07-14 16:27:53 +0000269 } else {
270 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
271 if (Result.isInvalid())
272 return StmtError();
273
274 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000275 }
276
277 if (Info.allowsRegister()) {
278 if (InputExpr->getType()->isVoidType()) {
279 return StmtError(Diag(InputExpr->getLocStart(),
280 diag::err_asm_invalid_type_in_input)
281 << InputExpr->getType() << Info.getConstraintStr()
282 << InputExpr->getSourceRange());
283 }
284 }
285
Chad Rosier0731aff2012-08-17 21:19:40 +0000286 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000287
288 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000289 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000290 continue;
291
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000292 if (!Ty->isVoidType() || !Info.allowsMemory())
Bill Wendlingb68b7572013-03-27 06:06:26 +0000293 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
294 diag::err_dereference_incomplete_type))
295 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000296
Bill Wendling887b4852012-11-12 06:42:51 +0000297 unsigned Size = Context.getTypeSize(Ty);
298 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
299 Size))
300 return StmtError(Diag(InputExpr->getLocStart(),
301 diag::err_asm_invalid_input_size)
302 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000303 }
304
305 // Check that the clobbers are valid.
306 for (unsigned i = 0; i != NumClobbers; i++) {
307 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000308 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000309
310 StringRef Clobber = Literal->getString();
311
312 if (!Context.getTargetInfo().isValidClobber(Clobber))
313 return StmtError(Diag(Literal->getLocStart(),
314 diag::err_asm_unknown_register_name) << Clobber);
315 }
316
Chad Rosierde70e0e2012-08-25 00:11:56 +0000317 GCCAsmStmt *NS =
318 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000319 NumInputs, Names, Constraints, Exprs.data(),
320 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000321 // Validate the asm string, ensuring it makes sense given the operands we
322 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000323 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000324 unsigned DiagOffs;
325 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
326 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
327 << AsmString->getSourceRange();
328 return StmtError();
329 }
330
Bill Wendling9d1ee112012-10-25 23:28:48 +0000331 // Validate constraints and modifiers.
332 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
333 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
334 if (!Piece.isOperand()) continue;
335
336 // Look for the correct constraint index.
Akira Hatanaka96a36012015-02-04 00:27:13 +0000337 unsigned ConstraintIdx = Piece.getOperandNo();
338 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
Bill Wendling9d1ee112012-10-25 23:28:48 +0000339
Akira Hatanaka96a36012015-02-04 00:27:13 +0000340 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
341 // modifier '+'.
342 if (ConstraintIdx >= NumOperands) {
343 unsigned I = 0, E = NS->getNumOutputs();
344
345 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
346 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
347 ConstraintIdx = I;
Bill Wendling9d1ee112012-10-25 23:28:48 +0000348 break;
Akira Hatanaka96a36012015-02-04 00:27:13 +0000349 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000350
Akira Hatanaka96a36012015-02-04 00:27:13 +0000351 assert(I != E && "Invalid operand number should have been caught in "
352 " AnalyzeAsmString");
Bill Wendling9d1ee112012-10-25 23:28:48 +0000353 }
354
355 // Now that we have the right indexes go ahead and check.
356 StringLiteral *Literal = Constraints[ConstraintIdx];
357 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
358 if (Ty->isDependentType() || Ty->isIncompleteType())
359 continue;
360
361 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000362 std::string SuggestedModifier;
363 if (!Context.getTargetInfo().validateConstraintModifier(
364 Literal->getString(), Piece.getModifier(), Size,
365 SuggestedModifier)) {
Bill Wendling9d1ee112012-10-25 23:28:48 +0000366 Diag(Exprs[ConstraintIdx]->getLocStart(),
367 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000368
369 if (!SuggestedModifier.empty()) {
370 auto B = Diag(Piece.getRange().getBegin(),
371 diag::note_asm_missing_constraint_modifier)
372 << SuggestedModifier;
373 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
374 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
375 SuggestedModifier));
376 }
377 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000378 }
379
Chad Rosier0731aff2012-08-17 21:19:40 +0000380 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000381 unsigned NumAlternatives = ~0U;
382 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
383 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
384 StringRef ConstraintStr = Info.getConstraintStr();
385 unsigned AltCount = ConstraintStr.count(',') + 1;
386 if (NumAlternatives == ~0U)
387 NumAlternatives = AltCount;
388 else if (NumAlternatives != AltCount)
389 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
390 diag::err_asm_unexpected_constraint_alternatives)
391 << NumAlternatives << AltCount);
392 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000393 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
394 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000395 StringRef ConstraintStr = Info.getConstraintStr();
396 unsigned AltCount = ConstraintStr.count(',') + 1;
397 if (NumAlternatives == ~0U)
398 NumAlternatives = AltCount;
399 else if (NumAlternatives != AltCount)
400 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
401 diag::err_asm_unexpected_constraint_alternatives)
402 << NumAlternatives << AltCount);
Chad Rosier0731aff2012-08-17 21:19:40 +0000403
404 // If this is a tied constraint, verify that the output and input have
405 // either exactly the same type, or that they are int/ptr operands with the
406 // same size (int/long, int*/long, are ok etc).
407 if (!Info.hasTiedOperand()) continue;
408
409 unsigned TiedTo = Info.getTiedOperand();
410 unsigned InputOpNo = i+NumOutputs;
411 Expr *OutputExpr = Exprs[TiedTo];
412 Expr *InputExpr = Exprs[InputOpNo];
413
414 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
415 continue;
416
417 QualType InTy = InputExpr->getType();
418 QualType OutTy = OutputExpr->getType();
419 if (Context.hasSameType(InTy, OutTy))
420 continue; // All types can be tied to themselves.
421
422 // Decide if the input and output are in the same domain (integer/ptr or
423 // floating point.
424 enum AsmDomain {
425 AD_Int, AD_FP, AD_Other
426 } InputDomain, OutputDomain;
427
428 if (InTy->isIntegerType() || InTy->isPointerType())
429 InputDomain = AD_Int;
430 else if (InTy->isRealFloatingType())
431 InputDomain = AD_FP;
432 else
433 InputDomain = AD_Other;
434
435 if (OutTy->isIntegerType() || OutTy->isPointerType())
436 OutputDomain = AD_Int;
437 else if (OutTy->isRealFloatingType())
438 OutputDomain = AD_FP;
439 else
440 OutputDomain = AD_Other;
441
442 // They are ok if they are the same size and in the same domain. This
443 // allows tying things like:
444 // void* to int*
445 // void* to int if they are the same size.
446 // double to long double if they are the same size.
447 //
448 uint64_t OutSize = Context.getTypeSize(OutTy);
449 uint64_t InSize = Context.getTypeSize(InTy);
450 if (OutSize == InSize && InputDomain == OutputDomain &&
451 InputDomain != AD_Other)
452 continue;
453
454 // If the smaller input/output operand is not mentioned in the asm string,
455 // then we can promote the smaller one to a larger input and the asm string
456 // won't notice.
457 bool SmallerValueMentioned = false;
458
459 // If this is a reference to the input and if the input was the smaller
460 // one, then we have to reject this asm.
461 if (isOperandMentioned(InputOpNo, Pieces)) {
462 // This is a use in the asm string of the smaller operand. Since we
463 // codegen this by promoting to a wider value, the asm will get printed
464 // "wrong".
465 SmallerValueMentioned |= InSize < OutSize;
466 }
467 if (isOperandMentioned(TiedTo, Pieces)) {
468 // If this is a reference to the output, and if the output is the larger
469 // value, then it's ok because we'll promote the input to the larger type.
470 SmallerValueMentioned |= OutSize < InSize;
471 }
472
473 // If the smaller value wasn't mentioned in the asm string, and if the
474 // output was a register, just extend the shorter one to the size of the
475 // larger one.
476 if (!SmallerValueMentioned && InputDomain != AD_Other &&
477 OutputConstraintInfos[TiedTo].allowsRegister())
478 continue;
479
480 // Either both of the operands were mentioned or the smaller one was
481 // mentioned. One more special case that we'll allow: if the tied input is
482 // integer, unmentioned, and is a constant, then we'll allow truncating it
483 // down to the size of the destination.
484 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
485 !isOperandMentioned(InputOpNo, Pieces) &&
486 InputExpr->isEvaluatable(Context)) {
487 CastKind castKind =
488 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000489 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000490 Exprs[InputOpNo] = InputExpr;
491 NS->setInputExpr(i, InputExpr);
492 continue;
493 }
494
495 Diag(InputExpr->getLocStart(),
496 diag::err_asm_tying_incompatible_types)
497 << InTy << OutTy << OutputExpr->getSourceRange()
498 << InputExpr->getSourceRange();
499 return StmtError();
500 }
501
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000502 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000503}
504
John McCallf413f5e2013-05-03 00:10:13 +0000505ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
506 SourceLocation TemplateKWLoc,
507 UnqualifiedId &Id,
Alp Toker10399272014-06-08 05:11:37 +0000508 llvm::InlineAsmIdentifierInfo &Info,
John McCallf413f5e2013-05-03 00:10:13 +0000509 bool IsUnevaluatedContext) {
Chad Rosierb18a2852013-04-22 17:01:37 +0000510 Info.clear();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000511
John McCallf413f5e2013-05-03 00:10:13 +0000512 if (IsUnevaluatedContext)
513 PushExpressionEvaluationContext(UnevaluatedAbstract,
514 ReuseLambdaContextDecl);
515
516 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
517 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000518 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000519 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000520 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000521
522 if (IsUnevaluatedContext)
523 PopExpressionEvaluationContext();
524
525 if (!Result.isUsable()) return Result;
526
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000527 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000528 if (!Result.isUsable()) return Result;
529
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000530 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000531 if (CheckNakedParmReference(Result.get(), *this))
532 return ExprError();
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000533
John McCallf413f5e2013-05-03 00:10:13 +0000534 QualType T = Result.get()->getType();
535
536 // For now, reject dependent types.
537 if (T->isDependentType()) {
538 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
539 return ExprError();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000540 }
541
John McCallf413f5e2013-05-03 00:10:13 +0000542 // Any sort of function type is fine.
543 if (T->isFunctionType()) {
544 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000545 }
546
John McCallf413f5e2013-05-03 00:10:13 +0000547 // Otherwise, it needs to be a complete type.
548 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
549 return ExprError();
550 }
551
552 // Compute the type size (and array length if applicable?).
553 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
554 if (T->isArrayType()) {
555 const ArrayType *ATy = Context.getAsArrayType(T);
556 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
557 Info.Length = Info.Size / Info.Type;
558 }
559
560 // We can work with the expression as long as it's not an r-value.
561 if (!Result.get()->isRValue())
Chad Rosierb18a2852013-04-22 17:01:37 +0000562 Info.IsVarDecl = true;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000563
John McCallf413f5e2013-05-03 00:10:13 +0000564 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000565}
Chad Rosierd997bd12012-08-22 19:18:30 +0000566
Chad Rosier5c563642012-10-25 21:49:22 +0000567bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
568 unsigned &Offset, SourceLocation AsmLoc) {
569 Offset = 0;
570 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
571 LookupOrdinaryName);
572
573 if (!LookupName(BaseResult, getCurScope()))
574 return true;
575
576 if (!BaseResult.isSingleResult())
577 return true;
578
Craig Topperc3ec1492014-05-26 06:22:03 +0000579 const RecordType *RT = nullptr;
Chad Rosier10230d42013-04-01 17:58:03 +0000580 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
581 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
Chad Rosier5c563642012-10-25 21:49:22 +0000582 RT = VD->getType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000583 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
584 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Chad Rosier5c563642012-10-25 21:49:22 +0000585 RT = TD->getUnderlyingType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000586 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
Nico Weber9ef9ca42014-05-06 03:13:27 +0000587 RT = TD->getTypeForDecl()->getAs<RecordType>();
Chad Rosier5c563642012-10-25 21:49:22 +0000588 if (!RT)
589 return true;
590
591 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
592 return true;
593
594 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
595 LookupMemberName);
596
597 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
598 return true;
599
600 // FIXME: Handle IndirectFieldDecl?
601 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
602 if (!FD)
603 return true;
604
605 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
606 unsigned i = FD->getFieldIndex();
607 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
608 Offset = (unsigned)Result.getQuantity();
609
610 return false;
611}
612
Chad Rosierb261a502012-09-13 00:06:55 +0000613StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000614 ArrayRef<Token> AsmToks,
615 StringRef AsmString,
616 unsigned NumOutputs, unsigned NumInputs,
617 ArrayRef<StringRef> Constraints,
618 ArrayRef<StringRef> Clobbers,
619 ArrayRef<Expr*> Exprs,
620 SourceLocation EndLoc) {
621 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000622 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000623 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000624 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
625 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000626 Constraints, Exprs, AsmString,
627 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000628 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000629}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000630
631LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
632 SourceLocation Location,
633 bool AlwaysCreate) {
634 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
635 Location);
636
Ehsan Akhgari42924432014-10-08 17:28:34 +0000637 if (Label->isMSAsmLabel()) {
638 // If we have previously created this label implicitly, mark it as used.
639 Label->markUsed(Context);
640 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000641 // Otherwise, insert it, but only resolve it if we have seen the label itself.
642 std::string InternalName;
643 llvm::raw_string_ostream OS(InternalName);
644 // Create an internal name for the label. The name should not be a valid mangled
645 // name, and should be unique. We use a dot to make the name an invalid mangled
646 // name.
647 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
648 Label->setMSAsmLabel(OS.str());
649 }
650 if (AlwaysCreate) {
651 // The label might have been created implicitly from a previously encountered
652 // goto statement. So, for both newly created and looked up labels, we mark
653 // them as resolved.
654 Label->setMSAsmLabelResolved();
655 }
656 // Adjust their location for being able to generate accurate diagnostics.
657 Label->setLocation(Location);
658
659 return Label;
660}