blob: 24a91716cb8527ad5b047f2943ea0b4ba946939b [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"
Chad Rosier5c563642012-10-25 21:49:22 +000015#include "clang/AST/RecordLayout.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000016#include "clang/AST/TypeLoc.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000017#include "clang/Basic/TargetInfo.h"
Ehsan Akhgari31097582014-09-22 02:21:54 +000018#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000023#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/BitVector.h"
Alp Toker10399272014-06-08 05:11:37 +000025#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000026using namespace clang;
27using namespace sema;
28
29/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
30/// ignore "noop" casts in places where an lvalue is required by an inline asm.
31/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
32/// provide a strong guidance to not use it.
33///
34/// This method checks to see if the argument is an acceptable l-value and
35/// returns false if it is a case we can handle.
36static bool CheckAsmLValue(const Expr *E, Sema &S) {
37 // Type dependent expressions will be checked during instantiation.
38 if (E->isTypeDependent())
39 return false;
40
41 if (E->isLValue())
42 return false; // Cool, this is an lvalue.
43
44 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
45 // are supposed to allow.
46 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
47 if (E != E2 && E2->isLValue()) {
48 if (!S.getLangOpts().HeinousExtensions)
49 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
50 << E->getSourceRange();
51 else
52 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
53 << E->getSourceRange();
54 // Accept, even if we emitted an error diagnostic.
55 return false;
56 }
57
58 // None of the above, just randomly invalid non-lvalue.
59 return true;
60}
61
62/// isOperandMentioned - Return true if the specified operand # is mentioned
63/// anywhere in the decomposed asm string.
64static bool isOperandMentioned(unsigned OpNo,
Chad Rosierde70e0e2012-08-25 00:11:56 +000065 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +000066 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +000067 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier0731aff2012-08-17 21:19:40 +000068 if (!Piece.isOperand()) continue;
69
70 // If this is a reference to the input and if the input was the smaller
71 // one, then we have to reject this asm.
72 if (Piece.getOperandNo() == OpNo)
73 return true;
74 }
75 return false;
76}
77
Hans Wennborge9d240a2014-10-08 01:58:02 +000078static bool CheckNakedParmReference(Expr *E, Sema &S) {
79 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
80 if (!Func)
81 return false;
82 if (!Func->hasAttr<NakedAttr>())
83 return false;
84
85 SmallVector<Expr*, 4> WorkList;
86 WorkList.push_back(E);
87 while (WorkList.size()) {
88 Expr *E = WorkList.pop_back_val();
89 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
90 if (isa<ParmVarDecl>(DRE->getDecl())) {
91 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
93 return true;
94 }
95 }
96 for (Stmt *Child : E->children()) {
97 if (Expr *E = dyn_cast_or_null<Expr>(Child))
98 WorkList.push_back(E);
99 }
100 }
101 return false;
102}
103
Chad Rosierde70e0e2012-08-25 00:11:56 +0000104StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
105 bool IsVolatile, unsigned NumOutputs,
106 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000107 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000108 Expr *asmString, MultiExprArg clobbers,
109 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000110 unsigned NumClobbers = clobbers.size();
111 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000112 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000113 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000114 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000115
116 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
117
118 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000119 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000120
121 for (unsigned i = 0; i != NumOutputs; i++) {
122 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000123 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000124
125 StringRef OutputName;
126 if (Names[i])
127 OutputName = Names[i]->getName();
128
129 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
130 if (!Context.getTargetInfo().validateOutputConstraint(Info))
131 return StmtError(Diag(Literal->getLocStart(),
132 diag::err_asm_invalid_output_constraint)
133 << Info.getConstraintStr());
134
David Majnemer0f4d6412014-12-29 09:30:33 +0000135 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
136 if (ER.isInvalid())
137 return StmtError();
138 Exprs[i] = ER.get();
139
Chad Rosier0731aff2012-08-17 21:19:40 +0000140 // Check that the output exprs are valid lvalues.
141 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000142
Hans Wennborge9d240a2014-10-08 01:58:02 +0000143 // Referring to parameters is not allowed in naked functions.
144 if (CheckNakedParmReference(OutputExpr, *this))
145 return StmtError();
146
Chad Rosier0731aff2012-08-17 21:19:40 +0000147 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000148
David Majnemer0f4d6412014-12-29 09:30:33 +0000149 // If this is dependent, just continue.
150 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000151 continue;
152
David Majnemer0f4d6412014-12-29 09:30:33 +0000153 Expr::isModifiableLvalueResult IsLV =
154 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
155 switch (IsLV) {
156 case Expr::MLV_Valid:
157 // Cool, this is an lvalue.
158 break;
159 case Expr::MLV_LValueCast: {
160 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
161 if (!getLangOpts().HeinousExtensions) {
162 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
163 << OutputExpr->getSourceRange();
164 } else {
165 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
166 << OutputExpr->getSourceRange();
167 }
168 // Accept, even if we emitted an error diagnostic.
169 break;
170 }
171 case Expr::MLV_IncompleteType:
172 case Expr::MLV_IncompleteVoidType:
173 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
174 diag::err_dereference_incomplete_type))
175 return StmtError();
176 default:
177 return StmtError(Diag(OutputExpr->getLocStart(),
178 diag::err_asm_invalid_lvalue_in_output)
179 << OutputExpr->getSourceRange());
180 }
181
182 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Akira Hatanaka974131e2014-09-18 18:17:18 +0000183 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
184 Size))
185 return StmtError(Diag(OutputExpr->getLocStart(),
186 diag::err_asm_invalid_output_size)
187 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000188 }
189
190 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
191
192 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
193 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000194 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000195
196 StringRef InputName;
197 if (Names[i])
198 InputName = Names[i]->getName();
199
200 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
201 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
202 NumOutputs, Info)) {
203 return StmtError(Diag(Literal->getLocStart(),
204 diag::err_asm_invalid_input_constraint)
205 << Info.getConstraintStr());
206 }
207
David Majnemer0f4d6412014-12-29 09:30:33 +0000208 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
209 if (ER.isInvalid())
210 return StmtError();
211 Exprs[i] = ER.get();
212
Chad Rosier0731aff2012-08-17 21:19:40 +0000213 Expr *InputExpr = Exprs[i];
214
Hans Wennborge9d240a2014-10-08 01:58:02 +0000215 // Referring to parameters is not allowed in naked functions.
216 if (CheckNakedParmReference(InputExpr, *this))
217 return StmtError();
218
Chad Rosier0731aff2012-08-17 21:19:40 +0000219 // Only allow void types for memory constraints.
220 if (Info.allowsMemory() && !Info.allowsRegister()) {
221 if (CheckAsmLValue(InputExpr, *this))
222 return StmtError(Diag(InputExpr->getLocStart(),
223 diag::err_asm_invalid_lvalue_in_input)
224 << Info.getConstraintStr()
225 << InputExpr->getSourceRange());
David Majnemerade4bee2014-07-14 16:27:53 +0000226 } else {
227 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
228 if (Result.isInvalid())
229 return StmtError();
230
231 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000232 }
233
234 if (Info.allowsRegister()) {
235 if (InputExpr->getType()->isVoidType()) {
236 return StmtError(Diag(InputExpr->getLocStart(),
237 diag::err_asm_invalid_type_in_input)
238 << InputExpr->getType() << Info.getConstraintStr()
239 << InputExpr->getSourceRange());
240 }
241 }
242
Chad Rosier0731aff2012-08-17 21:19:40 +0000243 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000244
245 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000246 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000247 continue;
248
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000249 if (!Ty->isVoidType() || !Info.allowsMemory())
Bill Wendlingb68b7572013-03-27 06:06:26 +0000250 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
251 diag::err_dereference_incomplete_type))
252 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000253
Bill Wendling887b4852012-11-12 06:42:51 +0000254 unsigned Size = Context.getTypeSize(Ty);
255 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
256 Size))
257 return StmtError(Diag(InputExpr->getLocStart(),
258 diag::err_asm_invalid_input_size)
259 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000260 }
261
262 // Check that the clobbers are valid.
263 for (unsigned i = 0; i != NumClobbers; i++) {
264 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000265 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000266
267 StringRef Clobber = Literal->getString();
268
269 if (!Context.getTargetInfo().isValidClobber(Clobber))
270 return StmtError(Diag(Literal->getLocStart(),
271 diag::err_asm_unknown_register_name) << Clobber);
272 }
273
Chad Rosierde70e0e2012-08-25 00:11:56 +0000274 GCCAsmStmt *NS =
275 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000276 NumInputs, Names, Constraints, Exprs.data(),
277 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000278 // Validate the asm string, ensuring it makes sense given the operands we
279 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000280 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000281 unsigned DiagOffs;
282 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
283 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
284 << AsmString->getSourceRange();
285 return StmtError();
286 }
287
Bill Wendling9d1ee112012-10-25 23:28:48 +0000288 // Validate constraints and modifiers.
289 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
290 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
291 if (!Piece.isOperand()) continue;
292
293 // Look for the correct constraint index.
294 unsigned Idx = 0;
295 unsigned ConstraintIdx = 0;
296 for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
297 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
298 if (Idx == Piece.getOperandNo())
299 break;
300 ++Idx;
301
302 if (Info.isReadWrite()) {
303 if (Idx == Piece.getOperandNo())
304 break;
305 ++Idx;
306 }
307 }
308
309 for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
310 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
311 if (Idx == Piece.getOperandNo())
312 break;
313 ++Idx;
314
315 if (Info.isReadWrite()) {
316 if (Idx == Piece.getOperandNo())
317 break;
318 ++Idx;
319 }
320 }
321
322 // Now that we have the right indexes go ahead and check.
323 StringLiteral *Literal = Constraints[ConstraintIdx];
324 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
325 if (Ty->isDependentType() || Ty->isIncompleteType())
326 continue;
327
328 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000329 std::string SuggestedModifier;
330 if (!Context.getTargetInfo().validateConstraintModifier(
331 Literal->getString(), Piece.getModifier(), Size,
332 SuggestedModifier)) {
Bill Wendling9d1ee112012-10-25 23:28:48 +0000333 Diag(Exprs[ConstraintIdx]->getLocStart(),
334 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000335
336 if (!SuggestedModifier.empty()) {
337 auto B = Diag(Piece.getRange().getBegin(),
338 diag::note_asm_missing_constraint_modifier)
339 << SuggestedModifier;
340 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
341 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
342 SuggestedModifier));
343 }
344 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000345 }
346
Chad Rosier0731aff2012-08-17 21:19:40 +0000347 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000348 unsigned NumAlternatives = ~0U;
349 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
350 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
351 StringRef ConstraintStr = Info.getConstraintStr();
352 unsigned AltCount = ConstraintStr.count(',') + 1;
353 if (NumAlternatives == ~0U)
354 NumAlternatives = AltCount;
355 else if (NumAlternatives != AltCount)
356 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
357 diag::err_asm_unexpected_constraint_alternatives)
358 << NumAlternatives << AltCount);
359 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000360 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
361 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000362 StringRef ConstraintStr = Info.getConstraintStr();
363 unsigned AltCount = ConstraintStr.count(',') + 1;
364 if (NumAlternatives == ~0U)
365 NumAlternatives = AltCount;
366 else if (NumAlternatives != AltCount)
367 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
368 diag::err_asm_unexpected_constraint_alternatives)
369 << NumAlternatives << AltCount);
Chad Rosier0731aff2012-08-17 21:19:40 +0000370
371 // If this is a tied constraint, verify that the output and input have
372 // either exactly the same type, or that they are int/ptr operands with the
373 // same size (int/long, int*/long, are ok etc).
374 if (!Info.hasTiedOperand()) continue;
375
376 unsigned TiedTo = Info.getTiedOperand();
377 unsigned InputOpNo = i+NumOutputs;
378 Expr *OutputExpr = Exprs[TiedTo];
379 Expr *InputExpr = Exprs[InputOpNo];
380
381 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
382 continue;
383
384 QualType InTy = InputExpr->getType();
385 QualType OutTy = OutputExpr->getType();
386 if (Context.hasSameType(InTy, OutTy))
387 continue; // All types can be tied to themselves.
388
389 // Decide if the input and output are in the same domain (integer/ptr or
390 // floating point.
391 enum AsmDomain {
392 AD_Int, AD_FP, AD_Other
393 } InputDomain, OutputDomain;
394
395 if (InTy->isIntegerType() || InTy->isPointerType())
396 InputDomain = AD_Int;
397 else if (InTy->isRealFloatingType())
398 InputDomain = AD_FP;
399 else
400 InputDomain = AD_Other;
401
402 if (OutTy->isIntegerType() || OutTy->isPointerType())
403 OutputDomain = AD_Int;
404 else if (OutTy->isRealFloatingType())
405 OutputDomain = AD_FP;
406 else
407 OutputDomain = AD_Other;
408
409 // They are ok if they are the same size and in the same domain. This
410 // allows tying things like:
411 // void* to int*
412 // void* to int if they are the same size.
413 // double to long double if they are the same size.
414 //
415 uint64_t OutSize = Context.getTypeSize(OutTy);
416 uint64_t InSize = Context.getTypeSize(InTy);
417 if (OutSize == InSize && InputDomain == OutputDomain &&
418 InputDomain != AD_Other)
419 continue;
420
421 // If the smaller input/output operand is not mentioned in the asm string,
422 // then we can promote the smaller one to a larger input and the asm string
423 // won't notice.
424 bool SmallerValueMentioned = false;
425
426 // If this is a reference to the input and if the input was the smaller
427 // one, then we have to reject this asm.
428 if (isOperandMentioned(InputOpNo, Pieces)) {
429 // This is a use in the asm string of the smaller operand. Since we
430 // codegen this by promoting to a wider value, the asm will get printed
431 // "wrong".
432 SmallerValueMentioned |= InSize < OutSize;
433 }
434 if (isOperandMentioned(TiedTo, Pieces)) {
435 // If this is a reference to the output, and if the output is the larger
436 // value, then it's ok because we'll promote the input to the larger type.
437 SmallerValueMentioned |= OutSize < InSize;
438 }
439
440 // If the smaller value wasn't mentioned in the asm string, and if the
441 // output was a register, just extend the shorter one to the size of the
442 // larger one.
443 if (!SmallerValueMentioned && InputDomain != AD_Other &&
444 OutputConstraintInfos[TiedTo].allowsRegister())
445 continue;
446
447 // Either both of the operands were mentioned or the smaller one was
448 // mentioned. One more special case that we'll allow: if the tied input is
449 // integer, unmentioned, and is a constant, then we'll allow truncating it
450 // down to the size of the destination.
451 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
452 !isOperandMentioned(InputOpNo, Pieces) &&
453 InputExpr->isEvaluatable(Context)) {
454 CastKind castKind =
455 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000456 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000457 Exprs[InputOpNo] = InputExpr;
458 NS->setInputExpr(i, InputExpr);
459 continue;
460 }
461
462 Diag(InputExpr->getLocStart(),
463 diag::err_asm_tying_incompatible_types)
464 << InTy << OutTy << OutputExpr->getSourceRange()
465 << InputExpr->getSourceRange();
466 return StmtError();
467 }
468
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000469 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000470}
471
John McCallf413f5e2013-05-03 00:10:13 +0000472ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
473 SourceLocation TemplateKWLoc,
474 UnqualifiedId &Id,
Alp Toker10399272014-06-08 05:11:37 +0000475 llvm::InlineAsmIdentifierInfo &Info,
John McCallf413f5e2013-05-03 00:10:13 +0000476 bool IsUnevaluatedContext) {
Chad Rosierb18a2852013-04-22 17:01:37 +0000477 Info.clear();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000478
John McCallf413f5e2013-05-03 00:10:13 +0000479 if (IsUnevaluatedContext)
480 PushExpressionEvaluationContext(UnevaluatedAbstract,
481 ReuseLambdaContextDecl);
482
483 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
484 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000485 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000486 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000487 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000488
489 if (IsUnevaluatedContext)
490 PopExpressionEvaluationContext();
491
492 if (!Result.isUsable()) return Result;
493
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000494 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000495 if (!Result.isUsable()) return Result;
496
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000497 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000498 if (CheckNakedParmReference(Result.get(), *this))
499 return ExprError();
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000500
John McCallf413f5e2013-05-03 00:10:13 +0000501 QualType T = Result.get()->getType();
502
503 // For now, reject dependent types.
504 if (T->isDependentType()) {
505 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
506 return ExprError();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000507 }
508
John McCallf413f5e2013-05-03 00:10:13 +0000509 // Any sort of function type is fine.
510 if (T->isFunctionType()) {
511 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000512 }
513
John McCallf413f5e2013-05-03 00:10:13 +0000514 // Otherwise, it needs to be a complete type.
515 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
516 return ExprError();
517 }
518
519 // Compute the type size (and array length if applicable?).
520 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
521 if (T->isArrayType()) {
522 const ArrayType *ATy = Context.getAsArrayType(T);
523 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
524 Info.Length = Info.Size / Info.Type;
525 }
526
527 // We can work with the expression as long as it's not an r-value.
528 if (!Result.get()->isRValue())
Chad Rosierb18a2852013-04-22 17:01:37 +0000529 Info.IsVarDecl = true;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000530
John McCallf413f5e2013-05-03 00:10:13 +0000531 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000532}
Chad Rosierd997bd12012-08-22 19:18:30 +0000533
Chad Rosier5c563642012-10-25 21:49:22 +0000534bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
535 unsigned &Offset, SourceLocation AsmLoc) {
536 Offset = 0;
537 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
538 LookupOrdinaryName);
539
540 if (!LookupName(BaseResult, getCurScope()))
541 return true;
542
543 if (!BaseResult.isSingleResult())
544 return true;
545
Craig Topperc3ec1492014-05-26 06:22:03 +0000546 const RecordType *RT = nullptr;
Chad Rosier10230d42013-04-01 17:58:03 +0000547 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
548 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
Chad Rosier5c563642012-10-25 21:49:22 +0000549 RT = VD->getType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000550 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
551 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Chad Rosier5c563642012-10-25 21:49:22 +0000552 RT = TD->getUnderlyingType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000553 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
Nico Weber9ef9ca42014-05-06 03:13:27 +0000554 RT = TD->getTypeForDecl()->getAs<RecordType>();
Chad Rosier5c563642012-10-25 21:49:22 +0000555 if (!RT)
556 return true;
557
558 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
559 return true;
560
561 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
562 LookupMemberName);
563
564 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
565 return true;
566
567 // FIXME: Handle IndirectFieldDecl?
568 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
569 if (!FD)
570 return true;
571
572 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
573 unsigned i = FD->getFieldIndex();
574 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
575 Offset = (unsigned)Result.getQuantity();
576
577 return false;
578}
579
Chad Rosierb261a502012-09-13 00:06:55 +0000580StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000581 ArrayRef<Token> AsmToks,
582 StringRef AsmString,
583 unsigned NumOutputs, unsigned NumInputs,
584 ArrayRef<StringRef> Constraints,
585 ArrayRef<StringRef> Clobbers,
586 ArrayRef<Expr*> Exprs,
587 SourceLocation EndLoc) {
588 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000589 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000590 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000591 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
592 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000593 Constraints, Exprs, AsmString,
594 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000595 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000596}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000597
598LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
599 SourceLocation Location,
600 bool AlwaysCreate) {
601 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
602 Location);
603
Ehsan Akhgari42924432014-10-08 17:28:34 +0000604 if (Label->isMSAsmLabel()) {
605 // If we have previously created this label implicitly, mark it as used.
606 Label->markUsed(Context);
607 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000608 // Otherwise, insert it, but only resolve it if we have seen the label itself.
609 std::string InternalName;
610 llvm::raw_string_ostream OS(InternalName);
611 // Create an internal name for the label. The name should not be a valid mangled
612 // name, and should be unique. We use a dot to make the name an invalid mangled
613 // name.
614 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
615 Label->setMSAsmLabel(OS.str());
616 }
617 if (AlwaysCreate) {
618 // The label might have been created implicitly from a previously encountered
619 // goto statement. So, for both newly created and looked up labels, we mark
620 // them as resolved.
621 Label->setMSAsmLabelResolved();
622 }
623 // Adjust their location for being able to generate accurate diagnostics.
624 Label->setLocation(Location);
625
626 return Label;
627}