1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
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/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Triple.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCInstPrinter.h"
41 #include "llvm/MC/MCInstrInfo.h"
42 #include "llvm/MC/MCObjectFileInfo.h"
43 #include "llvm/MC/MCRegisterInfo.h"
44 #include "llvm/MC/MCStreamer.h"
45 #include "llvm/MC/MCSubtargetInfo.h"
46 #include "llvm/MC/MCTargetAsmParser.h"
47 #include "llvm/MC/MCParser/MCAsmLexer.h"
48 #include "llvm/MC/MCParser/MCAsmParser.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 using namespace clang;
55 StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
57 if (!E) // FIXME: FullExprArg has no error state?
60 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
61 // void expression for its side effects. Conversion to void allows any
62 // operand, even incomplete types.
64 // Same thing in for stmt first clause (when expr) and third clause.
65 return Owned(static_cast<Stmt*>(E));
69 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
70 bool HasLeadingEmptyMacro) {
71 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
74 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
75 SourceLocation EndLoc) {
76 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
78 // If we have an invalid decl, just return an error.
79 if (DG.isNull()) return StmtError();
81 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
84 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
85 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
87 // If we have an invalid decl, just return.
88 if (DG.isNull() || !DG.isSingleDecl()) return;
89 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
91 // suppress any potential 'unused variable' warning.
94 // foreach variables are never actually initialized in the way that
95 // the parser came up with.
98 // In ARC, we don't need to retain the iteration variable of a fast
99 // enumeration loop. Rather than actually trying to catch that
100 // during declaration processing, we remove the consequences here.
101 if (getLangOpts().ObjCAutoRefCount) {
102 QualType type = var->getType();
104 // Only do this if we inferred the lifetime. Inferred lifetime
105 // will show up as a local qualifier because explicit lifetime
106 // should have shown up as an AttributedType instead.
107 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
108 // Add 'const' and mark the variable as pseudo-strong.
109 var->setType(type.withConst());
110 var->setARCPseudoStrong(true);
115 /// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
117 /// Adding a cast to void (or other expression wrappers) will prevent the
118 /// warning from firing.
119 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
121 bool IsNotEqual, CanAssign;
123 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
124 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
127 Loc = Op->getOperatorLoc();
128 IsNotEqual = Op->getOpcode() == BO_NE;
129 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
130 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
131 if (Op->getOperator() != OO_EqualEqual &&
132 Op->getOperator() != OO_ExclaimEqual)
135 Loc = Op->getOperatorLoc();
136 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
137 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
139 // Not a typo-prone comparison.
143 // Suppress warnings when the operator, suspicious as it may be, comes from
144 // a macro expansion.
148 S.Diag(Loc, diag::warn_unused_comparison)
149 << (unsigned)IsNotEqual << E->getSourceRange();
151 // If the LHS is a plausible entity to assign to, provide a fixit hint to
152 // correct common typos.
155 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
156 << FixItHint::CreateReplacement(Loc, "|=");
158 S.Diag(Loc, diag::note_equality_comparison_to_assign)
159 << FixItHint::CreateReplacement(Loc, "=");
165 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
166 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
167 return DiagnoseUnusedExprResult(Label->getSubStmt());
169 const Expr *E = dyn_cast_or_null<Expr>(S);
173 const Expr *WarnExpr;
176 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
177 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
180 // Okay, we have an unused result. Depending on what the base expression is,
181 // we might want to make a more specific diagnostic. Check for one of these
183 unsigned DiagID = diag::warn_unused_expr;
184 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
185 E = Temps->getSubExpr();
186 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
187 E = TempExpr->getSubExpr();
189 if (DiagnoseUnusedComparison(*this, E))
193 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
194 if (E->getType()->isVoidType())
197 // If the callee has attribute pure, const, or warn_unused_result, warn with
198 // a more specific message to make it clear what is happening.
199 if (const Decl *FD = CE->getCalleeDecl()) {
200 if (FD->getAttr<WarnUnusedResultAttr>()) {
201 Diag(Loc, diag::warn_unused_result) << R1 << R2;
204 if (FD->getAttr<PureAttr>()) {
205 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
208 if (FD->getAttr<ConstAttr>()) {
209 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
213 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
214 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
215 Diag(Loc, diag::err_arc_unused_init_message) << R1;
218 const ObjCMethodDecl *MD = ME->getMethodDecl();
219 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
220 Diag(Loc, diag::warn_unused_result) << R1 << R2;
223 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
224 const Expr *Source = POE->getSyntacticForm();
225 if (isa<ObjCSubscriptRefExpr>(Source))
226 DiagID = diag::warn_unused_container_subscript_expr;
228 DiagID = diag::warn_unused_property_expr;
229 } else if (const CXXFunctionalCastExpr *FC
230 = dyn_cast<CXXFunctionalCastExpr>(E)) {
231 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
232 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
235 // Diagnose "(void*) blah" as a typo for "(void) blah".
236 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
237 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
238 QualType T = TI->getType();
240 // We really do want to use the non-canonical type here.
241 if (T == Context.VoidPtrTy) {
242 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
244 Diag(Loc, diag::warn_unused_voidptr)
245 << FixItHint::CreateRemoval(TL.getStarLoc());
250 if (E->isGLValue() && E->getType().isVolatileQualified()) {
251 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
255 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
258 void Sema::ActOnStartOfCompoundStmt() {
262 void Sema::ActOnFinishOfCompoundStmt() {
266 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
267 return getCurFunction()->CompoundScopes.back();
271 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
272 MultiStmtArg elts, bool isStmtExpr) {
273 unsigned NumElts = elts.size();
274 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
275 // If we're in C89 mode, check that we don't have any decls after stmts. If
276 // so, emit an extension diagnostic.
277 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
278 // Note that __extension__ can be around a decl.
280 // Skip over all declarations.
281 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
284 // We found the end of the list or a statement. Scan for another declstmt.
285 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
289 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
290 Diag(D->getLocation(), diag::ext_mixed_decls_code);
293 // Warn about unused expressions in statements.
294 for (unsigned i = 0; i != NumElts; ++i) {
295 // Ignore statements that are last in a statement expression.
296 if (isStmtExpr && i == NumElts - 1)
299 DiagnoseUnusedExprResult(Elts[i]);
302 // Check for suspicious empty body (null statement) in `for' and `while'
303 // statements. Don't do anything for template instantiations, this just adds
305 if (NumElts != 0 && !CurrentInstantiationScope &&
306 getCurCompoundScope().HasEmptyLoopBodies) {
307 for (unsigned i = 0; i != NumElts - 1; ++i)
308 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
311 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
315 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
316 SourceLocation DotDotDotLoc, Expr *RHSVal,
317 SourceLocation ColonLoc) {
318 assert((LHSVal != 0) && "missing expression in case statement");
320 if (getCurFunction()->SwitchStack.empty()) {
321 Diag(CaseLoc, diag::err_case_not_in_switch);
325 if (!getLangOpts().CPlusPlus0x) {
326 // C99 6.8.4.2p3: The expression shall be an integer constant.
327 // However, GCC allows any evaluatable integer expression.
328 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
329 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
334 // GCC extension: The expression shall be an integer constant.
336 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
337 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
338 // Recover from an error by just forgetting about it.
342 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
344 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
348 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
349 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
350 DiagnoseUnusedExprResult(SubStmt);
352 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
353 CS->setSubStmt(SubStmt);
357 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
358 Stmt *SubStmt, Scope *CurScope) {
359 DiagnoseUnusedExprResult(SubStmt);
361 if (getCurFunction()->SwitchStack.empty()) {
362 Diag(DefaultLoc, diag::err_default_not_in_switch);
363 return Owned(SubStmt);
366 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
367 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
372 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
373 SourceLocation ColonLoc, Stmt *SubStmt) {
374 // If the label was multiply defined, reject it now.
375 if (TheDecl->getStmt()) {
376 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
377 Diag(TheDecl->getLocation(), diag::note_previous_definition);
378 return Owned(SubStmt);
381 // Otherwise, things are good. Fill in the declaration and return it.
382 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
383 TheDecl->setStmt(LS);
384 if (!TheDecl->isGnuLocal())
385 TheDecl->setLocation(IdentLoc);
389 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
390 ArrayRef<const Attr*> Attrs,
392 // Fill in the declaration and return it.
393 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
398 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
399 Stmt *thenStmt, SourceLocation ElseLoc,
401 ExprResult CondResult(CondVal.release());
403 VarDecl *ConditionVar = 0;
405 ConditionVar = cast<VarDecl>(CondVar);
406 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
407 if (CondResult.isInvalid())
410 Expr *ConditionExpr = CondResult.takeAs<Expr>();
414 DiagnoseUnusedExprResult(thenStmt);
417 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
418 diag::warn_empty_if_body);
421 DiagnoseUnusedExprResult(elseStmt);
423 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
424 thenStmt, ElseLoc, elseStmt));
427 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
428 /// the specified width and sign. If an overflow occurs, detect it and emit
429 /// the specified diagnostic.
430 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
431 unsigned NewWidth, bool NewSign,
434 // Perform a conversion to the promoted condition type if needed.
435 if (NewWidth > Val.getBitWidth()) {
436 // If this is an extension, just do it.
437 Val = Val.extend(NewWidth);
438 Val.setIsSigned(NewSign);
440 // If the input was signed and negative and the output is
441 // unsigned, don't bother to warn: this is implementation-defined
443 // FIXME: Introduce a second, default-ignored warning for this case?
444 } else if (NewWidth < Val.getBitWidth()) {
445 // If this is a truncation, check for overflow.
446 llvm::APSInt ConvVal(Val);
447 ConvVal = ConvVal.trunc(NewWidth);
448 ConvVal.setIsSigned(NewSign);
449 ConvVal = ConvVal.extend(Val.getBitWidth());
450 ConvVal.setIsSigned(Val.isSigned());
452 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
454 // Regardless of whether a diagnostic was emitted, really do the
456 Val = Val.trunc(NewWidth);
457 Val.setIsSigned(NewSign);
458 } else if (NewSign != Val.isSigned()) {
459 // Convert the sign to match the sign of the condition. This can cause
460 // overflow as well: unsigned(INTMIN)
461 // We don't diagnose this overflow, because it is implementation-defined
463 // FIXME: Introduce a second, default-ignored warning for this case?
464 llvm::APSInt OldVal(Val);
465 Val.setIsSigned(NewSign);
470 struct CaseCompareFunctor {
471 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
472 const llvm::APSInt &RHS) {
473 return LHS.first < RHS;
475 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
476 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
477 return LHS.first < RHS.first;
479 bool operator()(const llvm::APSInt &LHS,
480 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
481 return LHS < RHS.first;
486 /// CmpCaseVals - Comparison predicate for sorting case values.
488 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
489 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
490 if (lhs.first < rhs.first)
493 if (lhs.first == rhs.first &&
494 lhs.second->getCaseLoc().getRawEncoding()
495 < rhs.second->getCaseLoc().getRawEncoding())
500 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
502 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
503 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
505 return lhs.first < rhs.first;
508 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
510 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
511 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
513 return lhs.first == rhs.first;
516 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
517 /// potentially integral-promoted expression @p expr.
518 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
519 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
520 expr = cleanups->getSubExpr();
521 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
522 if (impcast->getCastKind() != CK_IntegralCast) break;
523 expr = impcast->getSubExpr();
525 return expr->getType();
529 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
531 ExprResult CondResult;
533 VarDecl *ConditionVar = 0;
535 ConditionVar = cast<VarDecl>(CondVar);
536 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
537 if (CondResult.isInvalid())
540 Cond = CondResult.release();
546 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
550 SwitchConvertDiagnoser(Expr *Cond)
551 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
553 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
555 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
558 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
560 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
561 << T << Cond->getSourceRange();
564 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
567 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
570 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
572 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
573 << ConvTy->isEnumeralType() << ConvTy;
576 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
578 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
581 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
583 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
584 << ConvTy->isEnumeralType() << ConvTy;
587 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
590 return DiagnosticBuilder::getEmpty();
592 } SwitchDiagnoser(Cond);
595 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
596 /*AllowScopedEnumerations*/ true);
597 if (CondResult.isInvalid()) return StmtError();
598 Cond = CondResult.take();
600 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
601 CondResult = UsualUnaryConversions(Cond);
602 if (CondResult.isInvalid()) return StmtError();
603 Cond = CondResult.take();
606 CheckImplicitConversions(Cond, SwitchLoc);
607 CondResult = MaybeCreateExprWithCleanups(Cond);
608 if (CondResult.isInvalid())
610 Cond = CondResult.take();
613 getCurFunction()->setHasBranchIntoScope();
615 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
616 getCurFunction()->SwitchStack.push_back(SS);
620 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
621 if (Val.getBitWidth() < BitWidth)
622 Val = Val.extend(BitWidth);
623 else if (Val.getBitWidth() > BitWidth)
624 Val = Val.trunc(BitWidth);
625 Val.setIsSigned(IsSigned);
629 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
631 SwitchStmt *SS = cast<SwitchStmt>(Switch);
632 assert(SS == getCurFunction()->SwitchStack.back() &&
633 "switch stack missing push/pop!");
635 SS->setBody(BodyStmt, SwitchLoc);
636 getCurFunction()->SwitchStack.pop_back();
638 Expr *CondExpr = SS->getCond();
639 if (!CondExpr) return StmtError();
641 QualType CondType = CondExpr->getType();
643 Expr *CondExprBeforePromotion = CondExpr;
644 QualType CondTypeBeforePromotion =
645 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
648 // Integral promotions are performed (on the switch condition).
650 // A case value unrepresentable by the original switch condition
651 // type (before the promotion) doesn't make sense, even when it can
652 // be represented by the promoted type. Therefore we need to find
653 // the pre-promotion type of the switch condition.
654 if (!CondExpr->isTypeDependent()) {
655 // We have already converted the expression to an integral or enumeration
656 // type, when we started the switch statement. If we don't have an
657 // appropriate type now, just return an error.
658 if (!CondType->isIntegralOrEnumerationType())
661 if (CondExpr->isKnownToHaveBooleanValue()) {
662 // switch(bool_expr) {...} is often a programmer error, e.g.
663 // switch(n && mask) { ... } // Doh - should be "n & mask".
664 // One can always use an if statement instead of switch(bool_expr).
665 Diag(SwitchLoc, diag::warn_bool_switch_condition)
666 << CondExpr->getSourceRange();
670 // Get the bitwidth of the switched-on value before promotions. We must
671 // convert the integer case values to this width before comparison.
672 bool HasDependentValue
673 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
675 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
677 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
679 // Accumulate all of the case values in a vector so that we can sort them
680 // and detect duplicates. This vector contains the APInt for the case after
681 // it has been converted to the condition type.
682 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
685 // Keep track of any GNU case ranges we see. The APSInt is the low value.
686 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
687 CaseRangesTy CaseRanges;
689 DefaultStmt *TheDefaultStmt = 0;
691 bool CaseListIsErroneous = false;
693 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
694 SC = SC->getNextSwitchCase()) {
696 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
697 if (TheDefaultStmt) {
698 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
699 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
701 // FIXME: Remove the default statement from the switch block so that
702 // we'll return a valid AST. This requires recursing down the AST and
703 // finding it, not something we are set up to do right now. For now,
704 // just lop the entire switch stmt out of the AST.
705 CaseListIsErroneous = true;
710 CaseStmt *CS = cast<CaseStmt>(SC);
712 Expr *Lo = CS->getLHS();
714 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
715 HasDependentValue = true;
721 if (getLangOpts().CPlusPlus0x) {
722 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
723 // constant expression of the promoted type of the switch condition.
725 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
726 if (ConvLo.isInvalid()) {
727 CaseListIsErroneous = true;
732 // We already verified that the expression has a i-c-e value (C99
733 // 6.8.4.2p3) - get that value now.
734 LoVal = Lo->EvaluateKnownConstInt(Context);
736 // If the LHS is not the same type as the condition, insert an implicit
738 Lo = DefaultLvalueConversion(Lo).take();
739 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
742 // Convert the value to the same width/sign as the condition had prior to
743 // integral promotions.
745 // FIXME: This causes us to reject valid code:
746 // switch ((char)c) { case 256: case 0: return 0; }
747 // Here we claim there is a duplicated condition value, but there is not.
748 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
750 diag::warn_case_value_overflow);
754 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
756 if (CS->getRHS()->isTypeDependent() ||
757 CS->getRHS()->isValueDependent()) {
758 HasDependentValue = true;
761 CaseRanges.push_back(std::make_pair(LoVal, CS));
763 CaseVals.push_back(std::make_pair(LoVal, CS));
767 if (!HasDependentValue) {
768 // If we don't have a default statement, check whether the
769 // condition is constant.
770 llvm::APSInt ConstantCondValue;
771 bool HasConstantCond = false;
772 if (!HasDependentValue && !TheDefaultStmt) {
774 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
775 Expr::SE_AllowSideEffects);
776 assert(!HasConstantCond ||
777 (ConstantCondValue.getBitWidth() == CondWidth &&
778 ConstantCondValue.isSigned() == CondIsSigned));
780 bool ShouldCheckConstantCond = HasConstantCond;
782 // Sort all the scalar case values so we can easily detect duplicates.
783 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
785 if (!CaseVals.empty()) {
786 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
787 if (ShouldCheckConstantCond &&
788 CaseVals[i].first == ConstantCondValue)
789 ShouldCheckConstantCond = false;
791 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
792 // If we have a duplicate, report it.
793 // First, determine if either case value has a name
794 StringRef PrevString, CurrString;
795 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
796 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
797 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
798 PrevString = DeclRef->getDecl()->getName();
800 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
801 CurrString = DeclRef->getDecl()->getName();
803 llvm::SmallString<16> CaseValStr;
804 CaseVals[i-1].first.toString(CaseValStr);
806 if (PrevString == CurrString)
807 Diag(CaseVals[i].second->getLHS()->getLocStart(),
808 diag::err_duplicate_case) <<
809 (PrevString.empty() ? CaseValStr.str() : PrevString);
811 Diag(CaseVals[i].second->getLHS()->getLocStart(),
812 diag::err_duplicate_case_differing_expr) <<
813 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
814 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
817 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
818 diag::note_duplicate_case_prev);
819 // FIXME: We really want to remove the bogus case stmt from the
820 // substmt, but we have no way to do this right now.
821 CaseListIsErroneous = true;
826 // Detect duplicate case ranges, which usually don't exist at all in
828 if (!CaseRanges.empty()) {
829 // Sort all the case ranges by their low value so we can easily detect
830 // overlaps between ranges.
831 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
833 // Scan the ranges, computing the high values and removing empty ranges.
834 std::vector<llvm::APSInt> HiVals;
835 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
836 llvm::APSInt &LoVal = CaseRanges[i].first;
837 CaseStmt *CR = CaseRanges[i].second;
838 Expr *Hi = CR->getRHS();
841 if (getLangOpts().CPlusPlus0x) {
842 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
843 // constant expression of the promoted type of the switch condition.
845 CheckConvertedConstantExpression(Hi, CondType, HiVal,
847 if (ConvHi.isInvalid()) {
848 CaseListIsErroneous = true;
853 HiVal = Hi->EvaluateKnownConstInt(Context);
855 // If the RHS is not the same type as the condition, insert an
857 Hi = DefaultLvalueConversion(Hi).take();
858 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
861 // Convert the value to the same width/sign as the condition.
862 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
864 diag::warn_case_value_overflow);
868 // If the low value is bigger than the high value, the case is empty.
870 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
871 << SourceRange(CR->getLHS()->getLocStart(),
873 CaseRanges.erase(CaseRanges.begin()+i);
878 if (ShouldCheckConstantCond &&
879 LoVal <= ConstantCondValue &&
880 ConstantCondValue <= HiVal)
881 ShouldCheckConstantCond = false;
883 HiVals.push_back(HiVal);
886 // Rescan the ranges, looking for overlap with singleton values and other
887 // ranges. Since the range list is sorted, we only need to compare case
888 // ranges with their neighbors.
889 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
890 llvm::APSInt &CRLo = CaseRanges[i].first;
891 llvm::APSInt &CRHi = HiVals[i];
892 CaseStmt *CR = CaseRanges[i].second;
894 // Check to see whether the case range overlaps with any
896 CaseStmt *OverlapStmt = 0;
897 llvm::APSInt OverlapVal(32);
899 // Find the smallest value >= the lower bound. If I is in the
900 // case range, then we have overlap.
901 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
902 CaseVals.end(), CRLo,
903 CaseCompareFunctor());
904 if (I != CaseVals.end() && I->first < CRHi) {
905 OverlapVal = I->first; // Found overlap with scalar.
906 OverlapStmt = I->second;
909 // Find the smallest value bigger than the upper bound.
910 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
911 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
912 OverlapVal = (I-1)->first; // Found overlap with scalar.
913 OverlapStmt = (I-1)->second;
916 // Check to see if this case stmt overlaps with the subsequent
918 if (i && CRLo <= HiVals[i-1]) {
919 OverlapVal = HiVals[i-1]; // Found overlap with range.
920 OverlapStmt = CaseRanges[i-1].second;
924 // If we have a duplicate, report it.
925 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
926 << OverlapVal.toString(10);
927 Diag(OverlapStmt->getLHS()->getLocStart(),
928 diag::note_duplicate_case_prev);
929 // FIXME: We really want to remove the bogus case stmt from the
930 // substmt, but we have no way to do this right now.
931 CaseListIsErroneous = true;
936 // Complain if we have a constant condition and we didn't find a match.
937 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
938 // TODO: it would be nice if we printed enums as enums, chars as
940 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
941 << ConstantCondValue.toString(10)
942 << CondExpr->getSourceRange();
945 // Check to see if switch is over an Enum and handles all of its
946 // values. We only issue a warning if there is not 'default:', but
947 // we still do the analysis to preserve this information in the AST
948 // (which can be used by flow-based analyes).
950 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
952 // If switch has default case, then ignore it.
953 if (!CaseListIsErroneous && !HasConstantCond && ET) {
954 const EnumDecl *ED = ET->getDecl();
955 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
959 // Gather all enum values, set their type and sort them,
960 // allowing easier comparison with CaseVals.
961 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
962 EDI != ED->enumerator_end(); ++EDI) {
963 llvm::APSInt Val = EDI->getInitVal();
964 AdjustAPSInt(Val, CondWidth, CondIsSigned);
965 EnumVals.push_back(std::make_pair(Val, *EDI));
967 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
968 EnumValsTy::iterator EIend =
969 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
971 // See which case values aren't in enum.
972 EnumValsTy::const_iterator EI = EnumVals.begin();
973 for (CaseValsTy::const_iterator CI = CaseVals.begin();
974 CI != CaseVals.end(); CI++) {
975 while (EI != EIend && EI->first < CI->first)
977 if (EI == EIend || EI->first > CI->first)
978 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
979 << CondTypeBeforePromotion;
981 // See which of case ranges aren't in enum
982 EI = EnumVals.begin();
983 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
984 RI != CaseRanges.end() && EI != EIend; RI++) {
985 while (EI != EIend && EI->first < RI->first)
988 if (EI == EIend || EI->first != RI->first) {
989 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
990 << CondTypeBeforePromotion;
994 RI->second->getRHS()->EvaluateKnownConstInt(Context);
995 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
996 while (EI != EIend && EI->first < Hi)
998 if (EI == EIend || EI->first != Hi)
999 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
1000 << CondTypeBeforePromotion;
1003 // Check which enum vals aren't in switch
1004 CaseValsTy::const_iterator CI = CaseVals.begin();
1005 CaseRangesTy::const_iterator RI = CaseRanges.begin();
1006 bool hasCasesNotInSwitch = false;
1008 SmallVector<DeclarationName,8> UnhandledNames;
1010 for (EI = EnumVals.begin(); EI != EIend; EI++){
1011 // Drop unneeded case values
1013 while (CI != CaseVals.end() && CI->first < EI->first)
1016 if (CI != CaseVals.end() && CI->first == EI->first)
1019 // Drop unneeded case ranges
1020 for (; RI != CaseRanges.end(); RI++) {
1022 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1023 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1024 if (EI->first <= Hi)
1028 if (RI == CaseRanges.end() || EI->first < RI->first) {
1029 hasCasesNotInSwitch = true;
1030 UnhandledNames.push_back(EI->second->getDeclName());
1034 if (TheDefaultStmt && UnhandledNames.empty())
1035 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1037 // Produce a nice diagnostic if multiple values aren't handled.
1038 switch (UnhandledNames.size()) {
1041 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1042 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1043 << UnhandledNames[0];
1046 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1047 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1048 << UnhandledNames[0] << UnhandledNames[1];
1051 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1052 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1053 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1056 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1057 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1058 << (unsigned)UnhandledNames.size()
1059 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1063 if (!hasCasesNotInSwitch)
1064 SS->setAllEnumCasesCovered();
1068 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1069 diag::warn_empty_switch_body);
1071 // FIXME: If the case list was broken is some way, we don't have a good system
1072 // to patch it up. Instead, just return the whole substmt as broken.
1073 if (CaseListIsErroneous)
1080 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1082 unsigned DIAG = diag::warn_not_in_enum_assignement;
1083 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1084 == DiagnosticsEngine::Ignored)
1087 if (const EnumType *ET = DstType->getAs<EnumType>())
1088 if (!Context.hasSameType(SrcType, DstType) &&
1089 SrcType->isIntegerType()) {
1090 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1091 SrcExpr->isIntegerConstantExpr(Context)) {
1092 // Get the bitwidth of the enum value before promotions.
1093 unsigned DstWith = Context.getIntWidth(DstType);
1094 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1096 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1097 const EnumDecl *ED = ET->getDecl();
1098 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1100 EnumValsTy EnumVals;
1102 // Gather all enum values, set their type and sort them,
1103 // allowing easier comparison with rhs constant.
1104 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1105 EDI != ED->enumerator_end(); ++EDI) {
1106 llvm::APSInt Val = EDI->getInitVal();
1107 AdjustAPSInt(Val, DstWith, DstIsSigned);
1108 EnumVals.push_back(std::make_pair(Val, *EDI));
1110 if (EnumVals.empty())
1112 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1113 EnumValsTy::iterator EIend =
1114 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1116 // See which case values aren't in enum.
1117 EnumValsTy::const_iterator EI = EnumVals.begin();
1118 while (EI != EIend && EI->first < RhsVal)
1120 if (EI == EIend || EI->first != RhsVal) {
1121 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1129 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1130 Decl *CondVar, Stmt *Body) {
1131 ExprResult CondResult(Cond.release());
1133 VarDecl *ConditionVar = 0;
1135 ConditionVar = cast<VarDecl>(CondVar);
1136 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1137 if (CondResult.isInvalid())
1140 Expr *ConditionExpr = CondResult.take();
1144 DiagnoseUnusedExprResult(Body);
1146 if (isa<NullStmt>(Body))
1147 getCurCompoundScope().setHasEmptyLoopBodies();
1149 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
1154 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1155 SourceLocation WhileLoc, SourceLocation CondLParen,
1156 Expr *Cond, SourceLocation CondRParen) {
1157 assert(Cond && "ActOnDoStmt(): missing expression");
1159 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1160 if (CondResult.isInvalid() || CondResult.isInvalid())
1162 Cond = CondResult.take();
1164 CheckImplicitConversions(Cond, DoLoc);
1165 CondResult = MaybeCreateExprWithCleanups(Cond);
1166 if (CondResult.isInvalid())
1168 Cond = CondResult.take();
1170 DiagnoseUnusedExprResult(Body);
1172 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
1176 // This visitor will traverse a conditional statement and store all
1177 // the evaluated decls into a vector. Simple is set to true if none
1178 // of the excluded constructs are used.
1179 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1180 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1181 llvm::SmallVector<SourceRange, 10> &Ranges;
1184 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1186 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1187 llvm::SmallVector<SourceRange, 10> &Ranges) :
1188 Inherited(S.Context),
1193 bool isSimple() { return Simple; }
1195 // Replaces the method in EvaluatedExprVisitor.
1196 void VisitMemberExpr(MemberExpr* E) {
1200 // Any Stmt not whitelisted will cause the condition to be marked complex.
1201 void VisitStmt(Stmt *S) {
1205 void VisitBinaryOperator(BinaryOperator *E) {
1210 void VisitCastExpr(CastExpr *E) {
1211 Visit(E->getSubExpr());
1214 void VisitUnaryOperator(UnaryOperator *E) {
1215 // Skip checking conditionals with derefernces.
1216 if (E->getOpcode() == UO_Deref)
1219 Visit(E->getSubExpr());
1222 void VisitConditionalOperator(ConditionalOperator *E) {
1223 Visit(E->getCond());
1224 Visit(E->getTrueExpr());
1225 Visit(E->getFalseExpr());
1228 void VisitParenExpr(ParenExpr *E) {
1229 Visit(E->getSubExpr());
1232 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1233 Visit(E->getOpaqueValue()->getSourceExpr());
1234 Visit(E->getFalseExpr());
1237 void VisitIntegerLiteral(IntegerLiteral *E) { }
1238 void VisitFloatingLiteral(FloatingLiteral *E) { }
1239 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1240 void VisitCharacterLiteral(CharacterLiteral *E) { }
1241 void VisitGNUNullExpr(GNUNullExpr *E) { }
1242 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1244 void VisitDeclRefExpr(DeclRefExpr *E) {
1245 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1248 Ranges.push_back(E->getSourceRange());
1253 }; // end class DeclExtractor
1255 // DeclMatcher checks to see if the decls are used in a non-evauluated
1257 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1258 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1262 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1264 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1265 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1266 if (!Statement) return;
1271 void VisitReturnStmt(ReturnStmt *S) {
1275 void VisitBreakStmt(BreakStmt *S) {
1279 void VisitGotoStmt(GotoStmt *S) {
1283 void VisitCastExpr(CastExpr *E) {
1284 if (E->getCastKind() == CK_LValueToRValue)
1285 CheckLValueToRValueCast(E->getSubExpr());
1287 Visit(E->getSubExpr());
1290 void CheckLValueToRValueCast(Expr *E) {
1291 E = E->IgnoreParenImpCasts();
1293 if (isa<DeclRefExpr>(E)) {
1297 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1298 Visit(CO->getCond());
1299 CheckLValueToRValueCast(CO->getTrueExpr());
1300 CheckLValueToRValueCast(CO->getFalseExpr());
1304 if (BinaryConditionalOperator *BCO =
1305 dyn_cast<BinaryConditionalOperator>(E)) {
1306 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1307 CheckLValueToRValueCast(BCO->getFalseExpr());
1314 void VisitDeclRefExpr(DeclRefExpr *E) {
1315 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1316 if (Decls.count(VD))
1320 bool FoundDeclInUse() { return FoundDecl; }
1322 }; // end class DeclMatcher
1324 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1325 Expr *Third, Stmt *Body) {
1326 // Condition is empty
1327 if (!Second) return;
1329 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1330 Second->getLocStart())
1331 == DiagnosticsEngine::Ignored)
1334 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1335 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1336 llvm::SmallVector<SourceRange, 10> Ranges;
1337 DeclExtractor DE(S, Decls, Ranges);
1340 // Don't analyze complex conditionals.
1341 if (!DE.isSimple()) return;
1344 if (Decls.size() == 0) return;
1346 // Don't warn on volatile, static, or global variables.
1347 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1350 if ((*I)->getType().isVolatileQualified() ||
1351 (*I)->hasGlobalStorage()) return;
1353 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1354 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1355 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1358 // Load decl names into diagnostic.
1359 if (Decls.size() > 4)
1362 PDiag << Decls.size();
1363 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1366 PDiag << (*I)->getDeclName();
1369 // Load SourceRanges into diagnostic if there is room.
1370 // Otherwise, load the SourceRange of the conditional expression.
1371 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1372 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1377 PDiag << Second->getSourceRange();
1379 S.Diag(Ranges.begin()->getBegin(), PDiag);
1385 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1386 Stmt *First, FullExprArg second, Decl *secondVar,
1388 SourceLocation RParenLoc, Stmt *Body) {
1389 if (!getLangOpts().CPlusPlus) {
1390 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1391 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1392 // declare identifiers for objects having storage class 'auto' or
1394 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1396 VarDecl *VD = dyn_cast<VarDecl>(*DI);
1397 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1400 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1401 // FIXME: mark decl erroneous!
1406 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1408 ExprResult SecondResult(second.release());
1409 VarDecl *ConditionVar = 0;
1411 ConditionVar = cast<VarDecl>(secondVar);
1412 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1413 if (SecondResult.isInvalid())
1417 Expr *Third = third.release().takeAs<Expr>();
1419 DiagnoseUnusedExprResult(First);
1420 DiagnoseUnusedExprResult(Third);
1421 DiagnoseUnusedExprResult(Body);
1423 if (isa<NullStmt>(Body))
1424 getCurCompoundScope().setHasEmptyLoopBodies();
1426 return Owned(new (Context) ForStmt(Context, First,
1427 SecondResult.take(), ConditionVar,
1428 Third, Body, ForLoc, LParenLoc,
1432 /// In an Objective C collection iteration statement:
1434 /// x can be an arbitrary l-value expression. Bind it up as a
1435 /// full-expression.
1436 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1437 // Reduce placeholder expressions here. Note that this rejects the
1438 // use of pseudo-object l-values in this position.
1439 ExprResult result = CheckPlaceholderExpr(E);
1440 if (result.isInvalid()) return StmtError();
1443 CheckImplicitConversions(E);
1445 result = MaybeCreateExprWithCleanups(E);
1446 if (result.isInvalid()) return StmtError();
1448 return Owned(static_cast<Stmt*>(result.take()));
1452 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1456 // Bail out early if we've got a type-dependent expression.
1457 if (collection->isTypeDependent()) return Owned(collection);
1459 // Perform normal l-value conversion.
1460 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1461 if (result.isInvalid())
1463 collection = result.take();
1465 // The operand needs to have object-pointer type.
1466 // TODO: should we do a contextual conversion?
1467 const ObjCObjectPointerType *pointerType =
1468 collection->getType()->getAs<ObjCObjectPointerType>();
1470 return Diag(forLoc, diag::err_collection_expr_type)
1471 << collection->getType() << collection->getSourceRange();
1473 // Check that the operand provides
1474 // - countByEnumeratingWithState:objects:count:
1475 const ObjCObjectType *objectType = pointerType->getObjectType();
1476 ObjCInterfaceDecl *iface = objectType->getInterface();
1478 // If we have a forward-declared type, we can't do this check.
1479 // Under ARC, it is an error not to have a forward-declared class.
1481 RequireCompleteType(forLoc, QualType(objectType, 0),
1482 getLangOpts().ObjCAutoRefCount
1483 ? diag::err_arc_collection_forward
1486 // Otherwise, if we have any useful type information, check that
1487 // the type declares the appropriate method.
1488 } else if (iface || !objectType->qual_empty()) {
1489 IdentifierInfo *selectorIdents[] = {
1490 &Context.Idents.get("countByEnumeratingWithState"),
1491 &Context.Idents.get("objects"),
1492 &Context.Idents.get("count")
1494 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1496 ObjCMethodDecl *method = 0;
1498 // If there's an interface, look in both the public and private APIs.
1500 method = iface->lookupInstanceMethod(selector);
1501 if (!method) method = iface->lookupPrivateMethod(selector);
1504 // Also check protocol qualifiers.
1506 method = LookupMethodInQualifiedType(selector, pointerType,
1509 // If we didn't find it anywhere, give up.
1511 Diag(forLoc, diag::warn_collection_expr_type)
1512 << collection->getType() << selector << collection->getSourceRange();
1515 // TODO: check for an incompatible signature?
1518 // Wrap up any cleanups in the expression.
1519 return Owned(MaybeCreateExprWithCleanups(collection));
1523 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1524 SourceLocation LParenLoc,
1525 Stmt *First, Expr *collection,
1526 SourceLocation RParenLoc) {
1528 ExprResult CollectionExprResult =
1529 CheckObjCForCollectionOperand(ForLoc, collection);
1533 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1534 if (!DS->isSingleDecl())
1535 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1536 diag::err_toomany_element_decls));
1538 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1539 FirstType = D->getType();
1540 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1541 // declare identifiers for objects having storage class 'auto' or
1543 if (!D->hasLocalStorage())
1544 return StmtError(Diag(D->getLocation(),
1545 diag::err_non_variable_decl_in_for));
1547 Expr *FirstE = cast<Expr>(First);
1548 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1549 return StmtError(Diag(First->getLocStart(),
1550 diag::err_selector_element_not_lvalue)
1551 << First->getSourceRange());
1553 FirstType = static_cast<Expr*>(First)->getType();
1555 if (!FirstType->isDependentType() &&
1556 !FirstType->isObjCObjectPointerType() &&
1557 !FirstType->isBlockPointerType())
1558 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1559 << FirstType << First->getSourceRange());
1562 if (CollectionExprResult.isInvalid())
1565 return Owned(new (Context) ObjCForCollectionStmt(First,
1566 CollectionExprResult.take(), 0,
1567 ForLoc, RParenLoc));
1572 enum BeginEndFunction {
1577 /// Build a variable declaration for a for-range statement.
1578 static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1579 QualType Type, const char *Name) {
1580 DeclContext *DC = SemaRef.CurContext;
1581 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1582 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1583 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1584 TInfo, SC_Auto, SC_None);
1585 Decl->setImplicit();
1589 /// Finish building a variable declaration for a for-range statement.
1590 /// \return true if an error occurs.
1591 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1592 SourceLocation Loc, int diag) {
1593 // Deduce the type for the iterator variable now rather than leaving it to
1594 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1595 TypeSourceInfo *InitTSI = 0;
1596 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1597 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1599 SemaRef.Diag(Loc, diag) << Init->getType();
1601 Decl->setInvalidDecl();
1604 Decl->setTypeSourceInfo(InitTSI);
1605 Decl->setType(InitTSI->getType());
1607 // In ARC, infer lifetime.
1608 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1609 // we're doing the equivalent of fast iteration.
1610 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1611 SemaRef.inferObjCARCLifetime(Decl))
1612 Decl->setInvalidDecl();
1614 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1615 /*TypeMayContainAuto=*/false);
1616 SemaRef.FinalizeDeclaration(Decl);
1617 SemaRef.CurContext->addHiddenDecl(Decl);
1621 /// Produce a note indicating which begin/end function was implicitly called
1622 /// by a C++0x for-range statement. This is often not obvious from the code,
1623 /// nor from the diagnostics produced when analysing the implicit expressions
1624 /// required in a for-range statement.
1625 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1626 BeginEndFunction BEF) {
1627 CallExpr *CE = dyn_cast<CallExpr>(E);
1630 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1633 SourceLocation Loc = D->getLocation();
1635 std::string Description;
1636 bool IsTemplate = false;
1637 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1638 Description = SemaRef.getTemplateArgumentBindingsText(
1639 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1643 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1644 << BEF << IsTemplate << Description << E->getType();
1647 /// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1648 /// given LookupResult is non-empty, it is assumed to describe a member which
1649 /// will be invoked. Otherwise, the function will be found via argument
1650 /// dependent lookup.
1651 static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1654 BeginEndFunction BEF,
1655 const DeclarationNameInfo &NameInfo,
1656 LookupResult &MemberLookup,
1658 ExprResult CallExpr;
1659 if (!MemberLookup.empty()) {
1660 ExprResult MemberRef =
1661 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1662 /*IsPtr=*/false, CXXScopeSpec(),
1663 /*TemplateKWLoc=*/SourceLocation(),
1664 /*FirstQualifierInScope=*/0,
1666 /*TemplateArgs=*/0);
1667 if (MemberRef.isInvalid())
1669 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1671 if (CallExpr.isInvalid())
1674 UnresolvedSet<0> FoundNames;
1675 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1676 // std is an associated namespace.
1677 UnresolvedLookupExpr *Fn =
1678 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1679 NestedNameSpecifierLoc(), NameInfo,
1680 /*NeedsADL=*/true, /*Overloaded=*/false,
1681 FoundNames.begin(), FoundNames.end(),
1682 /*LookInStdNamespace=*/true);
1683 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1684 0, /*AllowTypoCorrection=*/false);
1685 if (CallExpr.isInvalid()) {
1686 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1687 << Range->getType();
1691 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1692 diag::err_for_range_iter_deduction_failure)) {
1693 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1701 static bool ObjCEnumerationCollection(Expr *Collection) {
1702 return !Collection->isTypeDependent()
1703 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1706 /// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1708 /// C++0x [stmt.ranged]:
1709 /// A range-based for statement is equivalent to
1712 /// auto && __range = range-init;
1713 /// for ( auto __begin = begin-expr,
1714 /// __end = end-expr;
1715 /// __begin != __end;
1717 /// for-range-declaration = *__begin;
1722 /// The body of the loop is not available yet, since it cannot be analysed until
1723 /// we have determined the type of the for-range-declaration.
1725 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1726 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1727 SourceLocation RParenLoc) {
1728 if (!First || !Range)
1731 if (ObjCEnumerationCollection(Range))
1732 return ActOnObjCForCollectionStmt(ForLoc, LParenLoc, First, Range,
1735 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1736 assert(DS && "first part of for range not a decl stmt");
1738 if (!DS->isSingleDecl()) {
1739 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1742 if (DS->getSingleDecl()->isInvalidDecl())
1745 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1748 // Build auto && __range = range-init
1749 SourceLocation RangeLoc = Range->getLocStart();
1750 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1751 Context.getAutoRRefDeductType(),
1753 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1754 diag::err_for_range_deduction_failure))
1757 // Claim the type doesn't contain auto: we've already done the checking.
1758 DeclGroupPtrTy RangeGroup =
1759 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1760 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1761 if (RangeDecl.isInvalid())
1764 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1765 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1769 /// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1771 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1772 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1773 Expr *Inc, Stmt *LoopVarDecl,
1774 SourceLocation RParenLoc) {
1775 Scope *S = getCurScope();
1777 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1778 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1779 QualType RangeVarType = RangeVar->getType();
1781 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1782 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1784 StmtResult BeginEndDecl = BeginEnd;
1785 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1787 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1788 SourceLocation RangeLoc = RangeVar->getLocation();
1790 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1792 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1793 VK_LValue, ColonLoc);
1794 if (BeginRangeRef.isInvalid())
1797 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1798 VK_LValue, ColonLoc);
1799 if (EndRangeRef.isInvalid())
1802 QualType AutoType = Context.getAutoDeductType();
1803 Expr *Range = RangeVar->getInit();
1806 QualType RangeType = Range->getType();
1808 if (RequireCompleteType(RangeLoc, RangeType,
1809 diag::err_for_range_incomplete_type))
1812 // Build auto __begin = begin-expr, __end = end-expr.
1813 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1815 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1818 // Build begin-expr and end-expr and attach to __begin and __end variables.
1819 ExprResult BeginExpr, EndExpr;
1820 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1821 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1822 // __range + __bound, respectively, where __bound is the array bound. If
1823 // _RangeT is an array of unknown size or an array of incomplete type,
1824 // the program is ill-formed;
1826 // begin-expr is __range.
1827 BeginExpr = BeginRangeRef;
1828 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
1829 diag::err_for_range_iter_deduction_failure)) {
1830 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1834 // Find the array bound.
1835 ExprResult BoundExpr;
1836 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1837 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1838 Context.getPointerDiffType(),
1840 else if (const VariableArrayType *VAT =
1841 dyn_cast<VariableArrayType>(UnqAT))
1842 BoundExpr = VAT->getSizeExpr();
1844 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1845 // UnqAT is not incomplete and Range is not type-dependent.
1846 llvm_unreachable("Unexpected array type in for-range");
1849 // end-expr is __range + __bound.
1850 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
1852 if (EndExpr.isInvalid())
1854 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1855 diag::err_for_range_iter_deduction_failure)) {
1856 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1860 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1862 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1865 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1866 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1868 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1869 // - if _RangeT is a class type, the unqualified-ids begin and end are
1870 // looked up in the scope of class _RangeT as if by class member access
1871 // lookup (3.4.5), and if either (or both) finds at least one
1872 // declaration, begin-expr and end-expr are __range.begin() and
1873 // __range.end(), respectively;
1874 LookupQualifiedName(BeginMemberLookup, D);
1875 LookupQualifiedName(EndMemberLookup, D);
1877 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1878 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1879 << RangeType << BeginMemberLookup.empty();
1883 // - otherwise, begin-expr and end-expr are begin(__range) and
1884 // end(__range), respectively, where begin and end are looked up with
1885 // argument-dependent lookup (3.4.2). For the purposes of this name
1886 // lookup, namespace std is an associated namespace.
1889 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1890 BEF_begin, BeginNameInfo,
1892 BeginRangeRef.get());
1893 if (BeginExpr.isInvalid())
1896 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1897 BEF_end, EndNameInfo,
1898 EndMemberLookup, EndRangeRef.get());
1899 if (EndExpr.isInvalid())
1903 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1904 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1905 if (!Context.hasSameType(BeginType, EndType)) {
1906 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1907 << BeginType << EndType;
1908 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1909 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1912 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1913 // Claim the type doesn't contain auto: we've already done the checking.
1914 DeclGroupPtrTy BeginEndGroup =
1915 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1916 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1918 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1919 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1920 VK_LValue, ColonLoc);
1921 if (BeginRef.isInvalid())
1924 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1925 VK_LValue, ColonLoc);
1926 if (EndRef.isInvalid())
1929 // Build and check __begin != __end expression.
1930 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1931 BeginRef.get(), EndRef.get());
1932 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1933 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1934 if (NotEqExpr.isInvalid()) {
1935 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1936 if (!Context.hasSameType(BeginType, EndType))
1937 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1941 // Build and check ++__begin expression.
1942 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1943 VK_LValue, ColonLoc);
1944 if (BeginRef.isInvalid())
1947 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1948 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1949 if (IncrExpr.isInvalid()) {
1950 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1954 // Build and check *__begin expression.
1955 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1956 VK_LValue, ColonLoc);
1957 if (BeginRef.isInvalid())
1960 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1961 if (DerefExpr.isInvalid()) {
1962 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1966 // Attach *__begin as initializer for VD.
1967 if (!LoopVar->isInvalidDecl()) {
1968 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1969 /*TypeMayContainAuto=*/true);
1970 if (LoopVar->isInvalidDecl())
1971 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1974 // The range is implicitly used as a placeholder when it is dependent.
1975 RangeVar->setUsed();
1978 return Owned(new (Context) CXXForRangeStmt(RangeDS,
1979 cast_or_null<DeclStmt>(BeginEndDecl.get()),
1980 NotEqExpr.take(), IncrExpr.take(),
1981 LoopVarDS, /*Body=*/0, ForLoc,
1982 ColonLoc, RParenLoc));
1985 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
1987 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
1990 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
1992 ForStmt->setBody(B);
1996 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1997 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1998 /// body cannot be performed until after the type of the range variable is
2000 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2004 if (isa<ObjCForCollectionStmt>(S))
2005 return FinishObjCForCollectionStmt(S, B);
2007 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2008 ForStmt->setBody(B);
2010 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2011 diag::warn_empty_range_based_for_body);
2016 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2017 SourceLocation LabelLoc,
2018 LabelDecl *TheDecl) {
2019 getCurFunction()->setHasBranchIntoScope();
2021 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
2025 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2027 // Convert operand to void*
2028 if (!E->isTypeDependent()) {
2029 QualType ETy = E->getType();
2030 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2031 ExprResult ExprRes = Owned(E);
2032 AssignConvertType ConvTy =
2033 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2034 if (ExprRes.isInvalid())
2037 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2039 E = MaybeCreateExprWithCleanups(E);
2042 getCurFunction()->setHasIndirectGoto();
2044 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
2048 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2049 Scope *S = CurScope->getContinueParent();
2051 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2052 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2055 return Owned(new (Context) ContinueStmt(ContinueLoc));
2059 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2060 Scope *S = CurScope->getBreakParent();
2062 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2063 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2066 return Owned(new (Context) BreakStmt(BreakLoc));
2069 /// \brief Determine whether the given expression is a candidate for
2070 /// copy elision in either a return statement or a throw expression.
2072 /// \param ReturnType If we're determining the copy elision candidate for
2073 /// a return statement, this is the return type of the function. If we're
2074 /// determining the copy elision candidate for a throw expression, this will
2077 /// \param E The expression being returned from the function or block, or
2080 /// \param AllowFunctionParameter Whether we allow function parameters to
2081 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2082 /// we re-use this logic to determine whether we should try to move as part of
2083 /// a return or throw (which does allow function parameters).
2085 /// \returns The NRVO candidate variable, if the return statement may use the
2086 /// NRVO, or NULL if there is no such candidate.
2087 const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2089 bool AllowFunctionParameter) {
2090 QualType ExprType = E->getType();
2091 // - in a return statement in a function with ...
2092 // ... a class return type ...
2093 if (!ReturnType.isNull()) {
2094 if (!ReturnType->isRecordType())
2096 // ... the same cv-unqualified type as the function return type ...
2097 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2101 // ... the expression is the name of a non-volatile automatic object
2102 // (other than a function or catch-clause parameter)) ...
2103 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2104 if (!DR || DR->refersToEnclosingLocal())
2106 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2110 // ...object (other than a function or catch-clause parameter)...
2111 if (VD->getKind() != Decl::Var &&
2112 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2114 if (VD->isExceptionVariable()) return 0;
2117 if (!VD->hasLocalStorage()) return 0;
2119 // ...non-volatile...
2120 if (VD->getType().isVolatileQualified()) return 0;
2121 if (VD->getType()->isReferenceType()) return 0;
2123 // __block variables can't be allocated in a way that permits NRVO.
2124 if (VD->hasAttr<BlocksAttr>()) return 0;
2126 // Variables with higher required alignment than their type's ABI
2127 // alignment cannot use NRVO.
2128 if (VD->hasAttr<AlignedAttr>() &&
2129 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2135 /// \brief Perform the initialization of a potentially-movable value, which
2136 /// is the result of return value.
2138 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2139 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2140 /// then falls back to treating them as lvalues if that failed.
2142 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2143 const VarDecl *NRVOCandidate,
2144 QualType ResultType,
2147 // C++0x [class.copy]p33:
2148 // When the criteria for elision of a copy operation are met or would
2149 // be met save for the fact that the source object is a function
2150 // parameter, and the object to be copied is designated by an lvalue,
2151 // overload resolution to select the constructor for the copy is first
2152 // performed as if the object were designated by an rvalue.
2153 ExprResult Res = ExprError();
2155 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2156 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2157 Value->getType(), CK_NoOp, Value, VK_XValue);
2159 Expr *InitExpr = &AsRvalue;
2160 InitializationKind Kind
2161 = InitializationKind::CreateCopy(Value->getLocStart(),
2162 Value->getLocStart());
2163 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
2165 // [...] If overload resolution fails, or if the type of the first
2166 // parameter of the selected constructor is not an rvalue reference
2167 // to the object's type (possibly cv-qualified), overload resolution
2168 // is performed again, considering the object as an lvalue.
2170 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2171 StepEnd = Seq.step_end();
2172 Step != StepEnd; ++Step) {
2173 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2176 CXXConstructorDecl *Constructor
2177 = cast<CXXConstructorDecl>(Step->Function.Function);
2179 const RValueReferenceType *RRefType
2180 = Constructor->getParamDecl(0)->getType()
2181 ->getAs<RValueReferenceType>();
2183 // If we don't meet the criteria, break out now.
2185 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2186 Context.getTypeDeclType(Constructor->getParent())))
2189 // Promote "AsRvalue" to the heap, since we now need this
2190 // expression node to persist.
2191 Value = ImplicitCastExpr::Create(Context, Value->getType(),
2192 CK_NoOp, Value, 0, VK_XValue);
2194 // Complete type-checking the initialization of the return type
2195 // using the constructor we found.
2196 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
2201 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2202 // above, or overload resolution failed. Either way, we need to try
2203 // (again) now with the return value expression as written.
2204 if (Res.isInvalid())
2205 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2210 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2211 /// for capturing scopes.
2214 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2215 // If this is the first return we've seen, infer the return type.
2216 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2217 // rules which allows multiple return statements.
2218 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2219 QualType FnRetType = CurCap->ReturnType;
2221 // For blocks/lambdas with implicit return types, we check each return
2222 // statement individually, and deduce the common return type when the block
2223 // or lambda is completed.
2224 if (CurCap->HasImplicitReturnType) {
2225 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2226 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2227 if (Result.isInvalid())
2229 RetValExp = Result.take();
2231 if (!RetValExp->isTypeDependent())
2232 FnRetType = RetValExp->getType();
2234 FnRetType = CurCap->ReturnType = Context.DependentTy;
2237 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2238 // initializer list, because it is not an expression (even
2239 // though we represent it as one). We still deduce 'void'.
2240 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2241 << RetValExp->getSourceRange();
2244 FnRetType = Context.VoidTy;
2247 // Although we'll properly infer the type of the block once it's completed,
2248 // make sure we provide a return type now for better error recovery.
2249 if (CurCap->ReturnType.isNull())
2250 CurCap->ReturnType = FnRetType;
2252 assert(!FnRetType.isNull());
2254 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2255 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2256 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2260 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2261 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2262 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2267 // Otherwise, verify that this result type matches the previous one. We are
2268 // pickier with blocks than for normal functions because we don't have GCC
2269 // compatibility to worry about here.
2270 const VarDecl *NRVOCandidate = 0;
2271 if (FnRetType->isDependentType()) {
2272 // Delay processing for now. TODO: there are lots of dependent
2273 // types we can conclusively prove aren't void.
2274 } else if (FnRetType->isVoidType()) {
2275 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2276 !(getLangOpts().CPlusPlus &&
2277 (RetValExp->isTypeDependent() ||
2278 RetValExp->getType()->isVoidType()))) {
2279 if (!getLangOpts().CPlusPlus &&
2280 RetValExp->getType()->isVoidType())
2281 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2283 Diag(ReturnLoc, diag::err_return_block_has_expr);
2287 } else if (!RetValExp) {
2288 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2289 } else if (!RetValExp->isTypeDependent()) {
2290 // we have a non-void block with an expression, continue checking
2292 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2293 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2296 // In C++ the return statement is handled via a copy initialization.
2297 // the C version of which boils down to CheckSingleAssignmentConstraints.
2298 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2299 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2301 NRVOCandidate != 0);
2302 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2303 FnRetType, RetValExp);
2304 if (Res.isInvalid()) {
2305 // FIXME: Cleanup temporaries here, anyway?
2308 RetValExp = Res.take();
2309 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2313 CheckImplicitConversions(RetValExp, ReturnLoc);
2314 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2316 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2319 // If we need to check for the named return value optimization,
2320 // or if we need to infer the return type,
2321 // save the return statement in our scope for later processing.
2322 if (CurCap->HasImplicitReturnType ||
2323 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2324 !CurContext->isDependentContext()))
2325 FunctionScopes.back()->Returns.push_back(Result);
2327 return Owned(Result);
2331 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2332 // Check for unexpanded parameter packs.
2333 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2336 if (isa<CapturingScopeInfo>(getCurFunction()))
2337 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2340 QualType RelatedRetType;
2341 if (const FunctionDecl *FD = getCurFunctionDecl()) {
2342 FnRetType = FD->getResultType();
2343 if (FD->hasAttr<NoReturnAttr>() ||
2344 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
2345 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2346 << FD->getDeclName();
2347 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2348 FnRetType = MD->getResultType();
2349 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2350 // In the implementation of a method with a related return type, the
2351 // type used to type-check the validity of return statements within the
2352 // method body is a pointer to the type of the class being implemented.
2353 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2354 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2356 } else // If we don't have a function/method context, bail.
2359 ReturnStmt *Result = 0;
2360 if (FnRetType->isVoidType()) {
2362 if (isa<InitListExpr>(RetValExp)) {
2363 // We simply never allow init lists as the return value of void
2364 // functions. This is compatible because this was never allowed before,
2365 // so there's no legacy code to deal with.
2366 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2367 int FunctionKind = 0;
2368 if (isa<ObjCMethodDecl>(CurDecl))
2370 else if (isa<CXXConstructorDecl>(CurDecl))
2372 else if (isa<CXXDestructorDecl>(CurDecl))
2375 Diag(ReturnLoc, diag::err_return_init_list)
2376 << CurDecl->getDeclName() << FunctionKind
2377 << RetValExp->getSourceRange();
2379 // Drop the expression.
2381 } else if (!RetValExp->isTypeDependent()) {
2382 // C99 6.8.6.4p1 (ext_ since GCC warns)
2383 unsigned D = diag::ext_return_has_expr;
2384 if (RetValExp->getType()->isVoidType())
2385 D = diag::ext_return_has_void_expr;
2387 ExprResult Result = Owned(RetValExp);
2388 Result = IgnoredValueConversions(Result.take());
2389 if (Result.isInvalid())
2391 RetValExp = Result.take();
2392 RetValExp = ImpCastExprToType(RetValExp,
2393 Context.VoidTy, CK_ToVoid).take();
2396 // return (some void expression); is legal in C++.
2397 if (D != diag::ext_return_has_void_expr ||
2398 !getLangOpts().CPlusPlus) {
2399 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2401 int FunctionKind = 0;
2402 if (isa<ObjCMethodDecl>(CurDecl))
2404 else if (isa<CXXConstructorDecl>(CurDecl))
2406 else if (isa<CXXDestructorDecl>(CurDecl))
2410 << CurDecl->getDeclName() << FunctionKind
2411 << RetValExp->getSourceRange();
2416 CheckImplicitConversions(RetValExp, ReturnLoc);
2417 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2421 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2422 } else if (!RetValExp && !FnRetType->isDependentType()) {
2423 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2424 // C99 6.8.6.4p1 (ext_ since GCC warns)
2425 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2427 if (FunctionDecl *FD = getCurFunctionDecl())
2428 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2430 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2431 Result = new (Context) ReturnStmt(ReturnLoc);
2433 const VarDecl *NRVOCandidate = 0;
2434 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2435 // we have a non-void function with an expression, continue checking
2437 if (!RelatedRetType.isNull()) {
2438 // If we have a related result type, perform an extra conversion here.
2439 // FIXME: The diagnostics here don't really describe what is happening.
2440 InitializedEntity Entity =
2441 InitializedEntity::InitializeTemporary(RelatedRetType);
2443 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2445 if (Res.isInvalid()) {
2446 // FIXME: Cleanup temporaries here, anyway?
2449 RetValExp = Res.takeAs<Expr>();
2452 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2453 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2456 // In C++ the return statement is handled via a copy initialization,
2457 // the C version of which boils down to CheckSingleAssignmentConstraints.
2458 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2459 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2461 NRVOCandidate != 0);
2462 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2463 FnRetType, RetValExp);
2464 if (Res.isInvalid()) {
2465 // FIXME: Cleanup temporaries here, anyway?
2469 RetValExp = Res.takeAs<Expr>();
2471 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2475 CheckImplicitConversions(RetValExp, ReturnLoc);
2476 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2478 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2481 // If we need to check for the named return value optimization, save the
2482 // return statement in our scope for later processing.
2483 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2484 !CurContext->isDependentContext())
2485 FunctionScopes.back()->Returns.push_back(Result);
2487 return Owned(Result);
2490 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2491 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
2492 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2493 /// provide a strong guidance to not use it.
2495 /// This method checks to see if the argument is an acceptable l-value and
2496 /// returns false if it is a case we can handle.
2497 static bool CheckAsmLValue(const Expr *E, Sema &S) {
2498 // Type dependent expressions will be checked during instantiation.
2499 if (E->isTypeDependent())
2503 return false; // Cool, this is an lvalue.
2505 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2506 // are supposed to allow.
2507 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
2508 if (E != E2 && E2->isLValue()) {
2509 if (!S.getLangOpts().HeinousExtensions)
2510 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2511 << E->getSourceRange();
2513 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2514 << E->getSourceRange();
2515 // Accept, even if we emitted an error diagnostic.
2519 // None of the above, just randomly invalid non-lvalue.
2523 /// isOperandMentioned - Return true if the specified operand # is mentioned
2524 /// anywhere in the decomposed asm string.
2525 static bool isOperandMentioned(unsigned OpNo,
2526 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
2527 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2528 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2529 if (!Piece.isOperand()) continue;
2531 // If this is a reference to the input and if the input was the smaller
2532 // one, then we have to reject this asm.
2533 if (Piece.getOperandNo() == OpNo)
2539 StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2540 bool IsVolatile, unsigned NumOutputs,
2541 unsigned NumInputs, IdentifierInfo **Names,
2542 MultiExprArg constraints, MultiExprArg exprs,
2543 Expr *asmString, MultiExprArg clobbers,
2544 SourceLocation RParenLoc, bool MSAsm) {
2545 unsigned NumClobbers = clobbers.size();
2546 StringLiteral **Constraints =
2547 reinterpret_cast<StringLiteral**>(constraints.get());
2548 Expr **Exprs = exprs.get();
2549 StringLiteral *AsmString = cast<StringLiteral>(asmString);
2550 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2552 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2554 // The parser verifies that there is a string literal here.
2555 if (!AsmString->isAscii())
2556 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2557 << AsmString->getSourceRange());
2559 for (unsigned i = 0; i != NumOutputs; i++) {
2560 StringLiteral *Literal = Constraints[i];
2561 if (!Literal->isAscii())
2562 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2563 << Literal->getSourceRange());
2565 StringRef OutputName;
2567 OutputName = Names[i]->getName();
2569 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
2570 if (!Context.getTargetInfo().validateOutputConstraint(Info))
2571 return StmtError(Diag(Literal->getLocStart(),
2572 diag::err_asm_invalid_output_constraint)
2573 << Info.getConstraintStr());
2575 // Check that the output exprs are valid lvalues.
2576 Expr *OutputExpr = Exprs[i];
2577 if (CheckAsmLValue(OutputExpr, *this)) {
2578 return StmtError(Diag(OutputExpr->getLocStart(),
2579 diag::err_asm_invalid_lvalue_in_output)
2580 << OutputExpr->getSourceRange());
2583 OutputConstraintInfos.push_back(Info);
2586 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2588 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
2589 StringLiteral *Literal = Constraints[i];
2590 if (!Literal->isAscii())
2591 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2592 << Literal->getSourceRange());
2594 StringRef InputName;
2596 InputName = Names[i]->getName();
2598 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
2599 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
2600 NumOutputs, Info)) {
2601 return StmtError(Diag(Literal->getLocStart(),
2602 diag::err_asm_invalid_input_constraint)
2603 << Info.getConstraintStr());
2606 Expr *InputExpr = Exprs[i];
2608 // Only allow void types for memory constraints.
2609 if (Info.allowsMemory() && !Info.allowsRegister()) {
2610 if (CheckAsmLValue(InputExpr, *this))
2611 return StmtError(Diag(InputExpr->getLocStart(),
2612 diag::err_asm_invalid_lvalue_in_input)
2613 << Info.getConstraintStr()
2614 << InputExpr->getSourceRange());
2617 if (Info.allowsRegister()) {
2618 if (InputExpr->getType()->isVoidType()) {
2619 return StmtError(Diag(InputExpr->getLocStart(),
2620 diag::err_asm_invalid_type_in_input)
2621 << InputExpr->getType() << Info.getConstraintStr()
2622 << InputExpr->getSourceRange());
2626 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2627 if (Result.isInvalid())
2630 Exprs[i] = Result.take();
2631 InputConstraintInfos.push_back(Info);
2634 // Check that the clobbers are valid.
2635 for (unsigned i = 0; i != NumClobbers; i++) {
2636 StringLiteral *Literal = Clobbers[i];
2637 if (!Literal->isAscii())
2638 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2639 << Literal->getSourceRange());
2641 StringRef Clobber = Literal->getString();
2643 if (!Context.getTargetInfo().isValidClobber(Clobber))
2644 return StmtError(Diag(Literal->getLocStart(),
2645 diag::err_asm_unknown_register_name) << Clobber);
2649 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2650 NumOutputs, NumInputs, Names, Constraints, Exprs,
2651 AsmString, NumClobbers, Clobbers, RParenLoc);
2652 // Validate the asm string, ensuring it makes sense given the operands we
2654 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
2656 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
2657 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2658 << AsmString->getSourceRange();
2662 // Validate tied input operands for type mismatches.
2663 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2664 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2666 // If this is a tied constraint, verify that the output and input have
2667 // either exactly the same type, or that they are int/ptr operands with the
2668 // same size (int/long, int*/long, are ok etc).
2669 if (!Info.hasTiedOperand()) continue;
2671 unsigned TiedTo = Info.getTiedOperand();
2672 unsigned InputOpNo = i+NumOutputs;
2673 Expr *OutputExpr = Exprs[TiedTo];
2674 Expr *InputExpr = Exprs[InputOpNo];
2676 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2679 QualType InTy = InputExpr->getType();
2680 QualType OutTy = OutputExpr->getType();
2681 if (Context.hasSameType(InTy, OutTy))
2682 continue; // All types can be tied to themselves.
2684 // Decide if the input and output are in the same domain (integer/ptr or
2687 AD_Int, AD_FP, AD_Other
2688 } InputDomain, OutputDomain;
2690 if (InTy->isIntegerType() || InTy->isPointerType())
2691 InputDomain = AD_Int;
2692 else if (InTy->isRealFloatingType())
2693 InputDomain = AD_FP;
2695 InputDomain = AD_Other;
2697 if (OutTy->isIntegerType() || OutTy->isPointerType())
2698 OutputDomain = AD_Int;
2699 else if (OutTy->isRealFloatingType())
2700 OutputDomain = AD_FP;
2702 OutputDomain = AD_Other;
2704 // They are ok if they are the same size and in the same domain. This
2705 // allows tying things like:
2707 // void* to int if they are the same size.
2708 // double to long double if they are the same size.
2710 uint64_t OutSize = Context.getTypeSize(OutTy);
2711 uint64_t InSize = Context.getTypeSize(InTy);
2712 if (OutSize == InSize && InputDomain == OutputDomain &&
2713 InputDomain != AD_Other)
2716 // If the smaller input/output operand is not mentioned in the asm string,
2717 // then we can promote the smaller one to a larger input and the asm string
2719 bool SmallerValueMentioned = false;
2721 // If this is a reference to the input and if the input was the smaller
2722 // one, then we have to reject this asm.
2723 if (isOperandMentioned(InputOpNo, Pieces)) {
2724 // This is a use in the asm string of the smaller operand. Since we
2725 // codegen this by promoting to a wider value, the asm will get printed
2727 SmallerValueMentioned |= InSize < OutSize;
2729 if (isOperandMentioned(TiedTo, Pieces)) {
2730 // If this is a reference to the output, and if the output is the larger
2731 // value, then it's ok because we'll promote the input to the larger type.
2732 SmallerValueMentioned |= OutSize < InSize;
2735 // If the smaller value wasn't mentioned in the asm string, and if the
2736 // output was a register, just extend the shorter one to the size of the
2738 if (!SmallerValueMentioned && InputDomain != AD_Other &&
2739 OutputConstraintInfos[TiedTo].allowsRegister())
2742 // Either both of the operands were mentioned or the smaller one was
2743 // mentioned. One more special case that we'll allow: if the tied input is
2744 // integer, unmentioned, and is a constant, then we'll allow truncating it
2745 // down to the size of the destination.
2746 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2747 !isOperandMentioned(InputOpNo, Pieces) &&
2748 InputExpr->isEvaluatable(Context)) {
2750 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2751 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
2752 Exprs[InputOpNo] = InputExpr;
2753 NS->setInputExpr(i, InputExpr);
2757 Diag(InputExpr->getLocStart(),
2758 diag::err_asm_tying_incompatible_types)
2759 << InTy << OutTy << OutputExpr->getSourceRange()
2760 << InputExpr->getSourceRange();
2767 static void patchMSAsmStrings(Sema &SemaRef, bool &IsSimple,
2768 SourceLocation AsmLoc,
2769 ArrayRef<Token> AsmToks,
2770 const TargetInfo &TI,
2771 std::vector<llvm::BitVector> &AsmRegs,
2772 std::vector<llvm::BitVector> &AsmNames,
2773 std::vector<std::string> &AsmStrings) {
2774 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
2776 // Assume simple asm stmt until we parse a non-register identifer.
2779 SmallString<512> Asm;
2780 unsigned NumAsmStrings = 0;
2781 for (unsigned i = 0, e = AsmToks.size(); i != e; ++i) {
2783 // Determine if this should be considered a new asm.
2784 bool isNewAsm = i == 0 || AsmToks[i].isAtStartOfLine() ||
2785 AsmToks[i].is(tok::kw_asm);
2787 // Emit the previous asm string.
2788 if (i && isNewAsm) {
2789 AsmStrings[NumAsmStrings++] = Asm.c_str();
2790 if (AsmToks[i].is(tok::kw_asm)) {
2792 assert (i != e && "Expected another token.");
2796 // Start a new asm string with the opcode.
2798 AsmRegs[NumAsmStrings].resize(AsmToks.size());
2799 AsmNames[NumAsmStrings].resize(AsmToks.size());
2800 Asm = AsmToks[i].getIdentifierInfo()->getName().str();
2804 if (i && AsmToks[i].hasLeadingSpace())
2807 // Check the operand(s).
2808 switch (AsmToks[i].getKind()) {
2810 //llvm_unreachable("Unknown token.");
2812 case tok::comma: Asm += ","; break;
2813 case tok::colon: Asm += ":"; break;
2814 case tok::l_square: Asm += "["; break;
2815 case tok::r_square: Asm += "]"; break;
2816 case tok::l_brace: Asm += "{"; break;
2817 case tok::r_brace: Asm += "}"; break;
2818 case tok::numeric_constant: {
2819 SmallString<32> TokenBuf;
2820 TokenBuf.resize(32);
2821 bool StringInvalid = false;
2822 Asm += SemaRef.PP.getSpelling(AsmToks[i], TokenBuf, &StringInvalid);
2823 assert (!StringInvalid && "Expected valid string!");
2826 case tok::identifier: {
2827 IdentifierInfo *II = AsmToks[i].getIdentifierInfo();
2828 StringRef Name = II->getName();
2831 if (TI.isValidGCCRegisterName(Name)) {
2832 AsmRegs[NumAsmStrings].set(i);
2839 // FIXME: Why are we missing this segment register?
2845 // Lookup the identifier.
2846 // TODO: Someone with more experience with clang should verify this the
2847 // proper way of doing a symbol lookup.
2848 DeclarationName DeclName(II);
2849 Scope *CurScope = SemaRef.getCurScope();
2850 LookupResult R(SemaRef, DeclName, AsmLoc, Sema::LookupOrdinaryName);
2851 if (!SemaRef.LookupName(R, CurScope, false/*AllowBuiltinCreation*/))
2854 assert (R.isSingleResult() && "Expected a single result?!");
2855 NamedDecl *Decl = R.getFoundDecl();
2856 switch (Decl->getKind()) {
2858 assert(0 && "Unknown decl kind.");
2862 AsmNames[NumAsmStrings].set(i);
2864 VarDecl *Var = cast<VarDecl>(Decl);
2865 QualType Ty = Var->getType();
2866 (void)Ty; // Avoid warning.
2867 // TODO: Patch identifier with valid operand. One potential idea is to
2868 // probe the backend with type information to guess the possible
2878 // Emit the final (and possibly only) asm string.
2879 AsmStrings[NumAsmStrings] = Asm.c_str();
2882 // Build the unmodified MSAsmString.
2883 static std::string buildMSAsmString(Sema &SemaRef,
2884 ArrayRef<Token> AsmToks,
2885 unsigned &NumAsmStrings) {
2886 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!");
2887 SmallString<512> Asm;
2888 SmallString<512> TokenBuf;
2889 TokenBuf.resize(512);
2892 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
2893 bool isNewAsm = i == 0 || AsmToks[i].isAtStartOfLine() ||
2894 AsmToks[i].is(tok::kw_asm);
2900 if (AsmToks[i].is(tok::kw_asm)) {
2902 assert (i != e && "Expected another token");
2906 if (i && AsmToks[i].hasLeadingSpace() && !isNewAsm)
2909 bool StringInvalid = false;
2910 Asm += SemaRef.PP.getSpelling(AsmToks[i], TokenBuf, &StringInvalid);
2911 assert (!StringInvalid && "Expected valid string!");
2916 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
2917 SourceLocation LBraceLoc,
2918 ArrayRef<Token> AsmToks,
2919 SourceLocation EndLoc) {
2920 // MS-style inline assembly is not fully supported, so emit a warning.
2921 Diag(AsmLoc, diag::warn_unsupported_msasm);
2922 SmallVector<StringRef,4> Clobbers;
2923 std::set<std::string> ClobberRegs;
2924 SmallVector<IdentifierInfo*, 4> Inputs;
2925 SmallVector<IdentifierInfo*, 4> Outputs;
2927 // Empty asm statements don't need to instantiate the AsmParser, etc.
2928 if (AsmToks.empty()) {
2929 StringRef AsmString;
2931 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
2932 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
2933 AsmString, Clobbers, EndLoc);
2937 unsigned NumAsmStrings;
2938 std::string AsmString = buildMSAsmString(*this, AsmToks, NumAsmStrings);
2941 std::vector<llvm::BitVector> Regs;
2942 std::vector<llvm::BitVector> Names;
2943 std::vector<std::string> PatchedAsmStrings;
2945 Regs.resize(NumAsmStrings);
2946 Names.resize(NumAsmStrings);
2947 PatchedAsmStrings.resize(NumAsmStrings);
2949 // Rewrite operands to appease the AsmParser.
2950 patchMSAsmStrings(*this, IsSimple, AsmLoc, AsmToks,
2951 Context.getTargetInfo(), Regs, Names, PatchedAsmStrings);
2953 // patchMSAsmStrings doesn't correctly patch non-simple asm statements.
2956 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, /*IsSimple*/ true,
2957 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
2958 AsmString, Clobbers, EndLoc);
2962 // Initialize targets and assembly printers/parsers.
2963 llvm::InitializeAllTargetInfos();
2964 llvm::InitializeAllTargetMCs();
2965 llvm::InitializeAllAsmParsers();
2967 // Get the target specific parser.
2969 const std::string &TT = Context.getTargetInfo().getTriple().getTriple();
2970 const llvm::Target *TheTarget(llvm::TargetRegistry::lookupTarget(TT, Error));
2972 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TT));
2973 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
2974 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
2975 OwningPtr<llvm::MCSubtargetInfo>
2976 STI(TheTarget->createMCSubtargetInfo(TT, "", ""));
2978 for (unsigned i = 0, e = PatchedAsmStrings.size(); i != e; ++i) {
2979 llvm::SourceMgr SrcMgr;
2980 llvm::MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
2981 llvm::MemoryBuffer *Buffer =
2982 llvm::MemoryBuffer::getMemBuffer(PatchedAsmStrings[i], "<inline asm>");
2984 // Tell SrcMgr about this buffer, which is what the parser will pick up.
2985 SrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc());
2987 OwningPtr<llvm::MCStreamer> Str;
2988 OwningPtr<llvm::MCAsmParser>
2989 Parser(createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
2990 OwningPtr<llvm::MCTargetAsmParser>
2991 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser));
2992 // Change to the Intel dialect.
2993 Parser->setAssemblerDialect(1);
2994 Parser->setTargetParser(*TargetParser.get());
2999 // Parse the opcode.
3001 Parser->ParseIdentifier(IDVal);
3003 // Canonicalize the opcode to lower case.
3004 SmallString<128> Opcode;
3005 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
3006 Opcode.push_back(tolower(IDVal[i]));
3008 // Parse the operands.
3010 SmallVector<llvm::MCParsedAsmOperand*, 8> Operands;
3011 bool HadError = TargetParser->ParseInstruction(Opcode.str(), IDLoc,
3013 assert (!HadError && "Unexpected error parsing instruction");
3015 // Match the MCInstr.
3016 SmallVector<llvm::MCInst, 2> Instrs;
3017 HadError = TargetParser->MatchInstruction(IDLoc, Operands, Instrs);
3018 assert (!HadError && "Unexpected error matching instruction");
3019 assert ((Instrs.size() == 1) && "Expected only a single instruction.");
3021 // Get the instruction descriptor.
3022 llvm::MCInst Inst = Instrs[0];
3023 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo();
3024 const llvm::MCInstrDesc &Desc = MII->get(Inst.getOpcode());
3025 llvm::MCInstPrinter *IP =
3026 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI);
3028 // Build the list of clobbers.
3029 for (unsigned i = 0, e = Desc.getNumDefs(); i != e; ++i) {
3030 const llvm::MCOperand &Op = Inst.getOperand(i);
3035 llvm::raw_string_ostream OS(Reg);
3036 IP->printRegName(OS, Op.getReg());
3038 StringRef Clobber(OS.str());
3039 if (!Context.getTargetInfo().isValidClobber(Clobber))
3040 return StmtError(Diag(AsmLoc, diag::err_asm_unknown_register_name) <<
3042 ClobberRegs.insert(Reg);
3045 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3046 E = ClobberRegs.end(); I != E; ++I)
3047 Clobbers.push_back(*I);
3050 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
3051 /*IsVolatile*/ true, AsmToks, Inputs, Outputs,
3052 AsmString, Clobbers, EndLoc);
3057 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3058 SourceLocation RParen, Decl *Parm,
3060 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3061 if (Var && Var->isInvalidDecl())
3064 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
3068 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3069 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
3073 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3074 MultiStmtArg CatchStmts, Stmt *Finally) {
3075 if (!getLangOpts().ObjCExceptions)
3076 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3078 getCurFunction()->setHasBranchProtectedScope();
3079 unsigned NumCatchStmts = CatchStmts.size();
3080 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
3081 CatchStmts.release(),
3086 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3088 ExprResult Result = DefaultLvalueConversion(Throw);
3089 if (Result.isInvalid())
3092 Throw = MaybeCreateExprWithCleanups(Result.take());
3093 QualType ThrowType = Throw->getType();
3094 // Make sure the expression type is an ObjC pointer or "void *".
3095 if (!ThrowType->isDependentType() &&
3096 !ThrowType->isObjCObjectPointerType()) {
3097 const PointerType *PT = ThrowType->getAs<PointerType>();
3098 if (!PT || !PT->getPointeeType()->isVoidType())
3099 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3100 << Throw->getType() << Throw->getSourceRange());
3104 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
3108 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3110 if (!getLangOpts().ObjCExceptions)
3111 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3114 // @throw without an expression designates a rethrow (which much occur
3115 // in the context of an @catch clause).
3116 Scope *AtCatchParent = CurScope;
3117 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3118 AtCatchParent = AtCatchParent->getParent();
3120 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3122 return BuildObjCAtThrowStmt(AtLoc, Throw);
3126 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3127 ExprResult result = DefaultLvalueConversion(operand);
3128 if (result.isInvalid())
3130 operand = result.take();
3132 // Make sure the expression type is an ObjC pointer or "void *".
3133 QualType type = operand->getType();
3134 if (!type->isDependentType() &&
3135 !type->isObjCObjectPointerType()) {
3136 const PointerType *pointerType = type->getAs<PointerType>();
3137 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3138 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3139 << type << operand->getSourceRange();
3142 // The operand to @synchronized is a full-expression.
3143 return MaybeCreateExprWithCleanups(operand);
3147 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3149 // We can't jump into or indirect-jump out of a @synchronized block.
3150 getCurFunction()->setHasBranchProtectedScope();
3151 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
3154 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3155 /// and creates a proper catch handler from them.
3157 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3158 Stmt *HandlerBlock) {
3159 // There's nothing to test that ActOnExceptionDecl didn't already test.
3160 return Owned(new (Context) CXXCatchStmt(CatchLoc,
3161 cast_or_null<VarDecl>(ExDecl),
3166 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3167 getCurFunction()->setHasBranchProtectedScope();
3168 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3173 class TypeWithHandler {
3177 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3178 : t(type), stmt(statement) {}
3180 // An arbitrary order is fine as long as it places identical
3181 // types next to each other.
3182 bool operator<(const TypeWithHandler &y) const {
3183 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3185 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
3188 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3191 bool operator==(const TypeWithHandler& other) const {
3192 return t == other.t;
3195 CXXCatchStmt *getCatchStmt() const { return stmt; }
3196 SourceLocation getTypeSpecStartLoc() const {
3197 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3203 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3204 /// handlers and creates a try statement from them.
3206 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3207 MultiStmtArg RawHandlers) {
3208 // Don't report an error if 'try' is used in system headers.
3209 if (!getLangOpts().CXXExceptions &&
3210 !getSourceManager().isInSystemHeader(TryLoc))
3211 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3213 unsigned NumHandlers = RawHandlers.size();
3214 assert(NumHandlers > 0 &&
3215 "The parser shouldn't call this if there are no handlers.");
3216 Stmt **Handlers = RawHandlers.get();
3218 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3220 for (unsigned i = 0; i < NumHandlers; ++i) {
3221 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3222 if (!Handler->getExceptionDecl()) {
3223 if (i < NumHandlers - 1)
3224 return StmtError(Diag(Handler->getLocStart(),
3225 diag::err_early_catch_all));
3230 const QualType CaughtType = Handler->getCaughtType();
3231 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3232 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3235 // Detect handlers for the same type as an earlier one.
3236 if (NumHandlers > 1) {
3237 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3239 TypeWithHandler prev = TypesWithHandlers[0];
3240 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3241 TypeWithHandler curr = TypesWithHandlers[i];
3244 Diag(curr.getTypeSpecStartLoc(),
3245 diag::warn_exception_caught_by_earlier_handler)
3246 << curr.getCatchStmt()->getCaughtType().getAsString();
3247 Diag(prev.getTypeSpecStartLoc(),
3248 diag::note_previous_exception_handler)
3249 << prev.getCatchStmt()->getCaughtType().getAsString();
3256 getCurFunction()->setHasBranchProtectedScope();
3258 // FIXME: We should detect handlers that cannot catch anything because an
3259 // earlier handler catches a superclass. Need to find a method that is not
3260 // quadratic for this.
3261 // Neither of these are explicitly forbidden, but every compiler detects them
3264 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
3265 Handlers, NumHandlers));
3269 Sema::ActOnSEHTryBlock(bool IsCXXTry,
3270 SourceLocation TryLoc,
3273 assert(TryBlock && Handler);
3275 getCurFunction()->setHasBranchProtectedScope();
3277 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3281 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3284 assert(FilterExpr && Block);
3286 if(!FilterExpr->getType()->isIntegerType()) {
3287 return StmtError(Diag(FilterExpr->getExprLoc(),
3288 diag::err_filter_expression_integral)
3289 << FilterExpr->getType());
3292 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3296 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3299 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3302 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3304 NestedNameSpecifierLoc QualifierLoc,
3305 DeclarationNameInfo NameInfo,
3308 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3309 QualifierLoc, NameInfo,
3310 cast<CompoundStmt>(Nested));
3314 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3317 UnqualifiedId &Name,
3319 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3320 SS.getWithLocInContext(Context),
3321 GetNameFromUnqualifiedId(Name),