clang  3.7.0
SemaStmt.cpp
Go to the documentation of this file.
1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for statements.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/SmallVector.h"
40 using namespace clang;
41 using namespace sema;
42 
44  if (FE.isInvalid())
45  return StmtError();
46 
47  FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
48  /*DiscardedValue*/ true);
49  if (FE.isInvalid())
50  return StmtError();
51 
52  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
53  // void expression for its side effects. Conversion to void allows any
54  // operand, even incomplete types.
55 
56  // Same thing in for stmt first clause (when expr) and third clause.
57  return StmtResult(FE.getAs<Stmt>());
58 }
59 
60 
62  DiscardCleanupsInEvaluationContext();
63  return StmtError();
64 }
65 
67  bool HasLeadingEmptyMacro) {
68  return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
69 }
70 
72  SourceLocation EndLoc) {
73  DeclGroupRef DG = dg.get();
74 
75  // If we have an invalid decl, just return an error.
76  if (DG.isNull()) return StmtError();
77 
78  return new (Context) DeclStmt(DG, StartLoc, EndLoc);
79 }
80 
82  DeclGroupRef DG = dg.get();
83 
84  // If we don't have a declaration, or we have an invalid declaration,
85  // just return.
86  if (DG.isNull() || !DG.isSingleDecl())
87  return;
88 
89  Decl *decl = DG.getSingleDecl();
90  if (!decl || decl->isInvalidDecl())
91  return;
92 
93  // Only variable declarations are permitted.
94  VarDecl *var = dyn_cast<VarDecl>(decl);
95  if (!var) {
96  Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
97  decl->setInvalidDecl();
98  return;
99  }
100 
101  // foreach variables are never actually initialized in the way that
102  // the parser came up with.
103  var->setInit(nullptr);
104 
105  // In ARC, we don't need to retain the iteration variable of a fast
106  // enumeration loop. Rather than actually trying to catch that
107  // during declaration processing, we remove the consequences here.
108  if (getLangOpts().ObjCAutoRefCount) {
109  QualType type = var->getType();
110 
111  // Only do this if we inferred the lifetime. Inferred lifetime
112  // will show up as a local qualifier because explicit lifetime
113  // should have shown up as an AttributedType instead.
115  // Add 'const' and mark the variable as pseudo-strong.
116  var->setType(type.withConst());
117  var->setARCPseudoStrong(true);
118  }
119  }
120 }
121 
122 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
123 /// For '==' and '!=', suggest fixits for '=' or '|='.
124 ///
125 /// Adding a cast to void (or other expression wrappers) will prevent the
126 /// warning from firing.
127 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
128  SourceLocation Loc;
129  bool IsNotEqual, CanAssign, IsRelational;
130 
131  if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
132  if (!Op->isComparisonOp())
133  return false;
134 
135  IsRelational = Op->isRelationalOp();
136  Loc = Op->getOperatorLoc();
137  IsNotEqual = Op->getOpcode() == BO_NE;
138  CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
139  } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
140  switch (Op->getOperator()) {
141  default:
142  return false;
143  case OO_EqualEqual:
144  case OO_ExclaimEqual:
145  IsRelational = false;
146  break;
147  case OO_Less:
148  case OO_Greater:
149  case OO_GreaterEqual:
150  case OO_LessEqual:
151  IsRelational = true;
152  break;
153  }
154 
155  Loc = Op->getOperatorLoc();
156  IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
157  CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
158  } else {
159  // Not a typo-prone comparison.
160  return false;
161  }
162 
163  // Suppress warnings when the operator, suspicious as it may be, comes from
164  // a macro expansion.
165  if (S.SourceMgr.isMacroBodyExpansion(Loc))
166  return false;
167 
168  S.Diag(Loc, diag::warn_unused_comparison)
169  << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
170 
171  // If the LHS is a plausible entity to assign to, provide a fixit hint to
172  // correct common typos.
173  if (!IsRelational && CanAssign) {
174  if (IsNotEqual)
175  S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
176  << FixItHint::CreateReplacement(Loc, "|=");
177  else
178  S.Diag(Loc, diag::note_equality_comparison_to_assign)
179  << FixItHint::CreateReplacement(Loc, "=");
180  }
181 
182  return true;
183 }
184 
186  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
187  return DiagnoseUnusedExprResult(Label->getSubStmt());
188 
189  const Expr *E = dyn_cast_or_null<Expr>(S);
190  if (!E)
191  return;
192 
193  // If we are in an unevaluated expression context, then there can be no unused
194  // results because the results aren't expected to be used in the first place.
195  if (isUnevaluatedContext())
196  return;
197 
198  SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
199  // In most cases, we don't want to warn if the expression is written in a
200  // macro body, or if the macro comes from a system header. If the offending
201  // expression is a call to a function with the warn_unused_result attribute,
202  // we warn no matter the location. Because of the order in which the various
203  // checks need to happen, we factor out the macro-related test here.
204  bool ShouldSuppress =
205  SourceMgr.isMacroBodyExpansion(ExprLoc) ||
206  SourceMgr.isInSystemMacro(ExprLoc);
207 
208  const Expr *WarnExpr;
209  SourceLocation Loc;
210  SourceRange R1, R2;
211  if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
212  return;
213 
214  // If this is a GNU statement expression expanded from a macro, it is probably
215  // unused because it is a function-like macro that can be used as either an
216  // expression or statement. Don't warn, because it is almost certainly a
217  // false positive.
218  if (isa<StmtExpr>(E) && Loc.isMacroID())
219  return;
220 
221  // Okay, we have an unused result. Depending on what the base expression is,
222  // we might want to make a more specific diagnostic. Check for one of these
223  // cases now.
224  unsigned DiagID = diag::warn_unused_expr;
225  if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
226  E = Temps->getSubExpr();
227  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
228  E = TempExpr->getSubExpr();
229 
230  if (DiagnoseUnusedComparison(*this, E))
231  return;
232 
233  E = WarnExpr;
234  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
235  if (E->getType()->isVoidType())
236  return;
237 
238  // If the callee has attribute pure, const, or warn_unused_result, warn with
239  // a more specific message to make it clear what is happening. If the call
240  // is written in a macro body, only warn if it has the warn_unused_result
241  // attribute.
242  if (const Decl *FD = CE->getCalleeDecl()) {
243  const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
244  if (Func ? Func->hasUnusedResultAttr()
245  : FD->hasAttr<WarnUnusedResultAttr>()) {
246  Diag(Loc, diag::warn_unused_result) << R1 << R2;
247  return;
248  }
249  if (ShouldSuppress)
250  return;
251  if (FD->hasAttr<PureAttr>()) {
252  Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
253  return;
254  }
255  if (FD->hasAttr<ConstAttr>()) {
256  Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
257  return;
258  }
259  }
260  } else if (ShouldSuppress)
261  return;
262 
263  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
264  if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
265  Diag(Loc, diag::err_arc_unused_init_message) << R1;
266  return;
267  }
268  const ObjCMethodDecl *MD = ME->getMethodDecl();
269  if (MD) {
270  if (MD->hasAttr<WarnUnusedResultAttr>()) {
271  Diag(Loc, diag::warn_unused_result) << R1 << R2;
272  return;
273  }
274  }
275  } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
276  const Expr *Source = POE->getSyntacticForm();
277  if (isa<ObjCSubscriptRefExpr>(Source))
278  DiagID = diag::warn_unused_container_subscript_expr;
279  else
280  DiagID = diag::warn_unused_property_expr;
281  } else if (const CXXFunctionalCastExpr *FC
282  = dyn_cast<CXXFunctionalCastExpr>(E)) {
283  if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
284  isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
285  return;
286  }
287  // Diagnose "(void*) blah" as a typo for "(void) blah".
288  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
289  TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
290  QualType T = TI->getType();
291 
292  // We really do want to use the non-canonical type here.
293  if (T == Context.VoidPtrTy) {
295 
296  Diag(Loc, diag::warn_unused_voidptr)
298  return;
299  }
300  }
301 
302  if (E->isGLValue() && E->getType().isVolatileQualified()) {
303  Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
304  return;
305  }
306 
307  DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
308 }
309 
311  PushCompoundScope();
312 }
313 
315  PopCompoundScope();
316 }
317 
319  return getCurFunction()->CompoundScopes.back();
320 }
321 
323  ArrayRef<Stmt *> Elts, bool isStmtExpr) {
324  const unsigned NumElts = Elts.size();
325 
326  // If we're in C89 mode, check that we don't have any decls after stmts. If
327  // so, emit an extension diagnostic.
328  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
329  // Note that __extension__ can be around a decl.
330  unsigned i = 0;
331  // Skip over all declarations.
332  for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
333  /*empty*/;
334 
335  // We found the end of the list or a statement. Scan for another declstmt.
336  for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
337  /*empty*/;
338 
339  if (i != NumElts) {
340  Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
341  Diag(D->getLocation(), diag::ext_mixed_decls_code);
342  }
343  }
344  // Warn about unused expressions in statements.
345  for (unsigned i = 0; i != NumElts; ++i) {
346  // Ignore statements that are last in a statement expression.
347  if (isStmtExpr && i == NumElts - 1)
348  continue;
349 
350  DiagnoseUnusedExprResult(Elts[i]);
351  }
352 
353  // Check for suspicious empty body (null statement) in `for' and `while'
354  // statements. Don't do anything for template instantiations, this just adds
355  // noise.
356  if (NumElts != 0 && !CurrentInstantiationScope &&
357  getCurCompoundScope().HasEmptyLoopBodies) {
358  for (unsigned i = 0; i != NumElts - 1; ++i)
359  DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
360  }
361 
362  return new (Context) CompoundStmt(Context, Elts, L, R);
363 }
364 
367  SourceLocation DotDotDotLoc, Expr *RHSVal,
369  assert(LHSVal && "missing expression in case statement");
370 
371  if (getCurFunction()->SwitchStack.empty()) {
372  Diag(CaseLoc, diag::err_case_not_in_switch);
373  return StmtError();
374  }
375 
376  ExprResult LHS =
377  CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
378  if (!getLangOpts().CPlusPlus11)
379  return VerifyIntegerConstantExpression(E);
380  if (Expr *CondExpr =
381  getCurFunction()->SwitchStack.back()->getCond()) {
382  QualType CondType = CondExpr->getType();
383  llvm::APSInt TempVal;
384  return CheckConvertedConstantExpression(E, CondType, TempVal,
385  CCEK_CaseValue);
386  }
387  return ExprError();
388  });
389  if (LHS.isInvalid())
390  return StmtError();
391  LHSVal = LHS.get();
392 
393  if (!getLangOpts().CPlusPlus11) {
394  // C99 6.8.4.2p3: The expression shall be an integer constant.
395  // However, GCC allows any evaluatable integer expression.
396  if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
397  LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
398  if (!LHSVal)
399  return StmtError();
400  }
401 
402  // GCC extension: The expression shall be an integer constant.
403 
404  if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
405  RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
406  // Recover from an error by just forgetting about it.
407  }
408  }
409 
410  LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
411  getLangOpts().CPlusPlus11);
412  if (LHS.isInvalid())
413  return StmtError();
414 
415  auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
416  getLangOpts().CPlusPlus11)
417  : ExprResult();
418  if (RHS.isInvalid())
419  return StmtError();
420 
421  CaseStmt *CS = new (Context)
422  CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
423  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
424  return CS;
425 }
426 
427 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
429  DiagnoseUnusedExprResult(SubStmt);
430 
431  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
432  CS->setSubStmt(SubStmt);
433 }
434 
437  Stmt *SubStmt, Scope *CurScope) {
438  DiagnoseUnusedExprResult(SubStmt);
439 
440  if (getCurFunction()->SwitchStack.empty()) {
441  Diag(DefaultLoc, diag::err_default_not_in_switch);
442  return SubStmt;
443  }
444 
445  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
446  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
447  return DS;
448 }
449 
452  SourceLocation ColonLoc, Stmt *SubStmt) {
453  // If the label was multiply defined, reject it now.
454  if (TheDecl->getStmt()) {
455  Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
456  Diag(TheDecl->getLocation(), diag::note_previous_definition);
457  return SubStmt;
458  }
459 
460  // Otherwise, things are good. Fill in the declaration and return it.
461  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
462  TheDecl->setStmt(LS);
463  if (!TheDecl->isGnuLocal()) {
464  TheDecl->setLocStart(IdentLoc);
465  if (!TheDecl->isMSAsmLabel()) {
466  // Don't update the location of MS ASM labels. These will result in
467  // a diagnostic, and changing the location here will mess that up.
468  TheDecl->setLocation(IdentLoc);
469  }
470  }
471  return LS;
472 }
473 
475  ArrayRef<const Attr*> Attrs,
476  Stmt *SubStmt) {
477  // Fill in the declaration and return it.
478  AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
479  return LS;
480 }
481 
484  Stmt *thenStmt, SourceLocation ElseLoc,
485  Stmt *elseStmt) {
486  // If the condition was invalid, discard the if statement. We could recover
487  // better by replacing it with a valid expr, but don't do that yet.
488  if (!CondVal.get() && !CondVar) {
489  getCurFunction()->setHasDroppedStmt();
490  return StmtError();
491  }
492 
493  ExprResult CondResult(CondVal.release());
494 
495  VarDecl *ConditionVar = nullptr;
496  if (CondVar) {
497  ConditionVar = cast<VarDecl>(CondVar);
498  CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
499  CondResult = ActOnFinishFullExpr(CondResult.get(), IfLoc);
500  if (CondResult.isInvalid())
501  return StmtError();
502  }
503  Expr *ConditionExpr = CondResult.getAs<Expr>();
504  if (!ConditionExpr)
505  return StmtError();
506 
507  DiagnoseUnusedExprResult(thenStmt);
508 
509  if (!elseStmt) {
510  DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
511  diag::warn_empty_if_body);
512  }
513 
514  DiagnoseUnusedExprResult(elseStmt);
515 
516  return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
517  thenStmt, ElseLoc, elseStmt);
518 }
519 
520 namespace {
521  struct CaseCompareFunctor {
522  bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
523  const llvm::APSInt &RHS) {
524  return LHS.first < RHS;
525  }
526  bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
527  const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
528  return LHS.first < RHS.first;
529  }
530  bool operator()(const llvm::APSInt &LHS,
531  const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
532  return LHS < RHS.first;
533  }
534  };
535 }
536 
537 /// CmpCaseVals - Comparison predicate for sorting case values.
538 ///
539 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
540  const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
541  if (lhs.first < rhs.first)
542  return true;
543 
544  if (lhs.first == rhs.first &&
545  lhs.second->getCaseLoc().getRawEncoding()
546  < rhs.second->getCaseLoc().getRawEncoding())
547  return true;
548  return false;
549 }
550 
551 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
552 ///
553 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
554  const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
555 {
556  return lhs.first < rhs.first;
557 }
558 
559 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
560 ///
561 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
562  const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
563 {
564  return lhs.first == rhs.first;
565 }
566 
567 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
568 /// potentially integral-promoted expression @p expr.
570  if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
571  expr = cleanups->getSubExpr();
572  while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
573  if (impcast->getCastKind() != CK_IntegralCast) break;
574  expr = impcast->getSubExpr();
575  }
576  return expr->getType();
577 }
578 
581  Decl *CondVar) {
582  ExprResult CondResult;
583 
584  VarDecl *ConditionVar = nullptr;
585  if (CondVar) {
586  ConditionVar = cast<VarDecl>(CondVar);
587  CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
588  if (CondResult.isInvalid())
589  return StmtError();
590 
591  Cond = CondResult.get();
592  }
593 
594  if (!Cond)
595  return StmtError();
596 
597  class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
598  Expr *Cond;
599 
600  public:
601  SwitchConvertDiagnoser(Expr *Cond)
602  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
603  Cond(Cond) {}
604 
605  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
606  QualType T) override {
607  return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
608  }
609 
610  SemaDiagnosticBuilder diagnoseIncomplete(
611  Sema &S, SourceLocation Loc, QualType T) override {
612  return S.Diag(Loc, diag::err_switch_incomplete_class_type)
613  << T << Cond->getSourceRange();
614  }
615 
616  SemaDiagnosticBuilder diagnoseExplicitConv(
617  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
618  return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
619  }
620 
621  SemaDiagnosticBuilder noteExplicitConv(
622  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
623  return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
624  << ConvTy->isEnumeralType() << ConvTy;
625  }
626 
627  SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
628  QualType T) override {
629  return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
630  }
631 
632  SemaDiagnosticBuilder noteAmbiguous(
633  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
634  return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
635  << ConvTy->isEnumeralType() << ConvTy;
636  }
637 
638  SemaDiagnosticBuilder diagnoseConversion(
639  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
640  llvm_unreachable("conversion functions are permitted");
641  }
642  } SwitchDiagnoser(Cond);
643 
644  CondResult =
645  PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
646  if (CondResult.isInvalid()) return StmtError();
647  Cond = CondResult.get();
648 
649  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
650  CondResult = UsualUnaryConversions(Cond);
651  if (CondResult.isInvalid()) return StmtError();
652  Cond = CondResult.get();
653 
654  CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
655  if (CondResult.isInvalid())
656  return StmtError();
657  Cond = CondResult.get();
658 
659  getCurFunction()->setHasBranchIntoScope();
660 
661  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
662  getCurFunction()->SwitchStack.push_back(SS);
663  return SS;
664 }
665 
666 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
667  Val = Val.extOrTrunc(BitWidth);
668  Val.setIsSigned(IsSigned);
669 }
670 
671 /// Check the specified case value is in range for the given unpromoted switch
672 /// type.
673 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
674  unsigned UnpromotedWidth, bool UnpromotedSign) {
675  // If the case value was signed and negative and the switch expression is
676  // unsigned, don't bother to warn: this is implementation-defined behavior.
677  // FIXME: Introduce a second, default-ignored warning for this case?
678  if (UnpromotedWidth < Val.getBitWidth()) {
679  llvm::APSInt ConvVal(Val);
680  AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
681  AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
682  // FIXME: Use different diagnostics for overflow in conversion to promoted
683  // type versus "switch expression cannot have this value". Use proper
684  // IntRange checking rather than just looking at the unpromoted type here.
685  if (ConvVal != Val)
686  S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
687  << ConvVal.toString(10);
688  }
689 }
690 
692 
693 /// Returns true if we should emit a diagnostic about this case expression not
694 /// being a part of the enum used in the switch controlling expression.
696  const EnumDecl *ED,
697  const Expr *CaseExpr,
698  EnumValsTy::iterator &EI,
699  EnumValsTy::iterator &EIEnd,
700  const llvm::APSInt &Val) {
701  bool FlagType = ED->hasAttr<FlagEnumAttr>();
702 
703  if (const DeclRefExpr *DRE =
704  dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
705  if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
706  QualType VarType = VD->getType();
708  if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
709  S.Context.hasSameUnqualifiedType(EnumType, VarType))
710  return false;
711  }
712  }
713 
714  if (FlagType) {
715  return !S.IsValueInFlagEnum(ED, Val, false);
716  } else {
717  while (EI != EIEnd && EI->first < Val)
718  EI++;
719 
720  if (EI != EIEnd && EI->first == Val)
721  return false;
722  }
723 
724  return true;
725 }
726 
729  Stmt *BodyStmt) {
730  SwitchStmt *SS = cast<SwitchStmt>(Switch);
731  assert(SS == getCurFunction()->SwitchStack.back() &&
732  "switch stack missing push/pop!");
733 
734  getCurFunction()->SwitchStack.pop_back();
735 
736  if (!BodyStmt) return StmtError();
737  SS->setBody(BodyStmt, SwitchLoc);
738 
739  Expr *CondExpr = SS->getCond();
740  if (!CondExpr) return StmtError();
741 
742  QualType CondType = CondExpr->getType();
743 
744  Expr *CondExprBeforePromotion = CondExpr;
745  QualType CondTypeBeforePromotion =
746  GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
747 
748  // C++ 6.4.2.p2:
749  // Integral promotions are performed (on the switch condition).
750  //
751  // A case value unrepresentable by the original switch condition
752  // type (before the promotion) doesn't make sense, even when it can
753  // be represented by the promoted type. Therefore we need to find
754  // the pre-promotion type of the switch condition.
755  if (!CondExpr->isTypeDependent()) {
756  // We have already converted the expression to an integral or enumeration
757  // type, when we started the switch statement. If we don't have an
758  // appropriate type now, just return an error.
759  if (!CondType->isIntegralOrEnumerationType())
760  return StmtError();
761 
762  if (CondExpr->isKnownToHaveBooleanValue()) {
763  // switch(bool_expr) {...} is often a programmer error, e.g.
764  // switch(n && mask) { ... } // Doh - should be "n & mask".
765  // One can always use an if statement instead of switch(bool_expr).
766  Diag(SwitchLoc, diag::warn_bool_switch_condition)
767  << CondExpr->getSourceRange();
768  }
769  }
770 
771  // Get the bitwidth of the switched-on value after promotions. We must
772  // convert the integer case values to this width before comparison.
773  bool HasDependentValue
774  = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
775  unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
776  bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
777 
778  // Get the width and signedness that the condition might actually have, for
779  // warning purposes.
780  // FIXME: Grab an IntRange for the condition rather than using the unpromoted
781  // type.
782  unsigned CondWidthBeforePromotion
783  = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
784  bool CondIsSignedBeforePromotion
785  = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
786 
787  // Accumulate all of the case values in a vector so that we can sort them
788  // and detect duplicates. This vector contains the APInt for the case after
789  // it has been converted to the condition type.
790  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
791  CaseValsTy CaseVals;
792 
793  // Keep track of any GNU case ranges we see. The APSInt is the low value.
794  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
795  CaseRangesTy CaseRanges;
796 
797  DefaultStmt *TheDefaultStmt = nullptr;
798 
799  bool CaseListIsErroneous = false;
800 
801  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
802  SC = SC->getNextSwitchCase()) {
803 
804  if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
805  if (TheDefaultStmt) {
806  Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
807  Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
808 
809  // FIXME: Remove the default statement from the switch block so that
810  // we'll return a valid AST. This requires recursing down the AST and
811  // finding it, not something we are set up to do right now. For now,
812  // just lop the entire switch stmt out of the AST.
813  CaseListIsErroneous = true;
814  }
815  TheDefaultStmt = DS;
816 
817  } else {
818  CaseStmt *CS = cast<CaseStmt>(SC);
819 
820  Expr *Lo = CS->getLHS();
821 
822  if (Lo->isTypeDependent() || Lo->isValueDependent()) {
823  HasDependentValue = true;
824  break;
825  }
826 
827  llvm::APSInt LoVal;
828 
829  if (getLangOpts().CPlusPlus11) {
830  // C++11 [stmt.switch]p2: the constant-expression shall be a converted
831  // constant expression of the promoted type of the switch condition.
832  ExprResult ConvLo =
833  CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
834  if (ConvLo.isInvalid()) {
835  CaseListIsErroneous = true;
836  continue;
837  }
838  Lo = ConvLo.get();
839  } else {
840  // We already verified that the expression has a i-c-e value (C99
841  // 6.8.4.2p3) - get that value now.
842  LoVal = Lo->EvaluateKnownConstInt(Context);
843 
844  // If the LHS is not the same type as the condition, insert an implicit
845  // cast.
846  Lo = DefaultLvalueConversion(Lo).get();
847  Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
848  }
849 
850  // Check the unconverted value is within the range of possible values of
851  // the switch expression.
852  checkCaseValue(*this, Lo->getLocStart(), LoVal,
853  CondWidthBeforePromotion, CondIsSignedBeforePromotion);
854 
855  // Convert the value to the same width/sign as the condition.
856  AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
857 
858  CS->setLHS(Lo);
859 
860  // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
861  if (CS->getRHS()) {
862  if (CS->getRHS()->isTypeDependent() ||
863  CS->getRHS()->isValueDependent()) {
864  HasDependentValue = true;
865  break;
866  }
867  CaseRanges.push_back(std::make_pair(LoVal, CS));
868  } else
869  CaseVals.push_back(std::make_pair(LoVal, CS));
870  }
871  }
872 
873  if (!HasDependentValue) {
874  // If we don't have a default statement, check whether the
875  // condition is constant.
876  llvm::APSInt ConstantCondValue;
877  bool HasConstantCond = false;
878  if (!HasDependentValue && !TheDefaultStmt) {
879  HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
881  assert(!HasConstantCond ||
882  (ConstantCondValue.getBitWidth() == CondWidth &&
883  ConstantCondValue.isSigned() == CondIsSigned));
884  }
885  bool ShouldCheckConstantCond = HasConstantCond;
886 
887  // Sort all the scalar case values so we can easily detect duplicates.
888  std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
889 
890  if (!CaseVals.empty()) {
891  for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
892  if (ShouldCheckConstantCond &&
893  CaseVals[i].first == ConstantCondValue)
894  ShouldCheckConstantCond = false;
895 
896  if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
897  // If we have a duplicate, report it.
898  // First, determine if either case value has a name
899  StringRef PrevString, CurrString;
900  Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
901  Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
902  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
903  PrevString = DeclRef->getDecl()->getName();
904  }
905  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
906  CurrString = DeclRef->getDecl()->getName();
907  }
908  SmallString<16> CaseValStr;
909  CaseVals[i-1].first.toString(CaseValStr);
910 
911  if (PrevString == CurrString)
912  Diag(CaseVals[i].second->getLHS()->getLocStart(),
913  diag::err_duplicate_case) <<
914  (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
915  else
916  Diag(CaseVals[i].second->getLHS()->getLocStart(),
917  diag::err_duplicate_case_differing_expr) <<
918  (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
919  (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
920  CaseValStr;
921 
922  Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
923  diag::note_duplicate_case_prev);
924  // FIXME: We really want to remove the bogus case stmt from the
925  // substmt, but we have no way to do this right now.
926  CaseListIsErroneous = true;
927  }
928  }
929  }
930 
931  // Detect duplicate case ranges, which usually don't exist at all in
932  // the first place.
933  if (!CaseRanges.empty()) {
934  // Sort all the case ranges by their low value so we can easily detect
935  // overlaps between ranges.
936  std::stable_sort(CaseRanges.begin(), CaseRanges.end());
937 
938  // Scan the ranges, computing the high values and removing empty ranges.
939  std::vector<llvm::APSInt> HiVals;
940  for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
941  llvm::APSInt &LoVal = CaseRanges[i].first;
942  CaseStmt *CR = CaseRanges[i].second;
943  Expr *Hi = CR->getRHS();
944  llvm::APSInt HiVal;
945 
946  if (getLangOpts().CPlusPlus11) {
947  // C++11 [stmt.switch]p2: the constant-expression shall be a converted
948  // constant expression of the promoted type of the switch condition.
949  ExprResult ConvHi =
950  CheckConvertedConstantExpression(Hi, CondType, HiVal,
951  CCEK_CaseValue);
952  if (ConvHi.isInvalid()) {
953  CaseListIsErroneous = true;
954  continue;
955  }
956  Hi = ConvHi.get();
957  } else {
958  HiVal = Hi->EvaluateKnownConstInt(Context);
959 
960  // If the RHS is not the same type as the condition, insert an
961  // implicit cast.
962  Hi = DefaultLvalueConversion(Hi).get();
963  Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
964  }
965 
966  // Check the unconverted value is within the range of possible values of
967  // the switch expression.
968  checkCaseValue(*this, Hi->getLocStart(), HiVal,
969  CondWidthBeforePromotion, CondIsSignedBeforePromotion);
970 
971  // Convert the value to the same width/sign as the condition.
972  AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
973 
974  CR->setRHS(Hi);
975 
976  // If the low value is bigger than the high value, the case is empty.
977  if (LoVal > HiVal) {
978  Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
979  << SourceRange(CR->getLHS()->getLocStart(),
980  Hi->getLocEnd());
981  CaseRanges.erase(CaseRanges.begin()+i);
982  --i, --e;
983  continue;
984  }
985 
986  if (ShouldCheckConstantCond &&
987  LoVal <= ConstantCondValue &&
988  ConstantCondValue <= HiVal)
989  ShouldCheckConstantCond = false;
990 
991  HiVals.push_back(HiVal);
992  }
993 
994  // Rescan the ranges, looking for overlap with singleton values and other
995  // ranges. Since the range list is sorted, we only need to compare case
996  // ranges with their neighbors.
997  for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
998  llvm::APSInt &CRLo = CaseRanges[i].first;
999  llvm::APSInt &CRHi = HiVals[i];
1000  CaseStmt *CR = CaseRanges[i].second;
1001 
1002  // Check to see whether the case range overlaps with any
1003  // singleton cases.
1004  CaseStmt *OverlapStmt = nullptr;
1005  llvm::APSInt OverlapVal(32);
1006 
1007  // Find the smallest value >= the lower bound. If I is in the
1008  // case range, then we have overlap.
1009  CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1010  CaseVals.end(), CRLo,
1011  CaseCompareFunctor());
1012  if (I != CaseVals.end() && I->first < CRHi) {
1013  OverlapVal = I->first; // Found overlap with scalar.
1014  OverlapStmt = I->second;
1015  }
1016 
1017  // Find the smallest value bigger than the upper bound.
1018  I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1019  if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1020  OverlapVal = (I-1)->first; // Found overlap with scalar.
1021  OverlapStmt = (I-1)->second;
1022  }
1023 
1024  // Check to see if this case stmt overlaps with the subsequent
1025  // case range.
1026  if (i && CRLo <= HiVals[i-1]) {
1027  OverlapVal = HiVals[i-1]; // Found overlap with range.
1028  OverlapStmt = CaseRanges[i-1].second;
1029  }
1030 
1031  if (OverlapStmt) {
1032  // If we have a duplicate, report it.
1033  Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1034  << OverlapVal.toString(10);
1035  Diag(OverlapStmt->getLHS()->getLocStart(),
1036  diag::note_duplicate_case_prev);
1037  // FIXME: We really want to remove the bogus case stmt from the
1038  // substmt, but we have no way to do this right now.
1039  CaseListIsErroneous = true;
1040  }
1041  }
1042  }
1043 
1044  // Complain if we have a constant condition and we didn't find a match.
1045  if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1046  // TODO: it would be nice if we printed enums as enums, chars as
1047  // chars, etc.
1048  Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1049  << ConstantCondValue.toString(10)
1050  << CondExpr->getSourceRange();
1051  }
1052 
1053  // Check to see if switch is over an Enum and handles all of its
1054  // values. We only issue a warning if there is not 'default:', but
1055  // we still do the analysis to preserve this information in the AST
1056  // (which can be used by flow-based analyes).
1057  //
1058  const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1059 
1060  // If switch has default case, then ignore it.
1061  if (!CaseListIsErroneous && !HasConstantCond && ET) {
1062  const EnumDecl *ED = ET->getDecl();
1063  EnumValsTy EnumVals;
1064 
1065  // Gather all enum values, set their type and sort them,
1066  // allowing easier comparison with CaseVals.
1067  for (auto *EDI : ED->enumerators()) {
1068  llvm::APSInt Val = EDI->getInitVal();
1069  AdjustAPSInt(Val, CondWidth, CondIsSigned);
1070  EnumVals.push_back(std::make_pair(Val, EDI));
1071  }
1072  std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1073  auto EI = EnumVals.begin(), EIEnd =
1074  std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1075 
1076  // See which case values aren't in enum.
1077  for (CaseValsTy::const_iterator CI = CaseVals.begin();
1078  CI != CaseVals.end(); CI++) {
1079  Expr *CaseExpr = CI->second->getLHS();
1080  if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1081  CI->first))
1082  Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1083  << CondTypeBeforePromotion;
1084  }
1085 
1086  // See which of case ranges aren't in enum
1087  EI = EnumVals.begin();
1088  for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1089  RI != CaseRanges.end(); RI++) {
1090  Expr *CaseExpr = RI->second->getLHS();
1091  if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1092  RI->first))
1093  Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1094  << CondTypeBeforePromotion;
1095 
1096  llvm::APSInt Hi =
1097  RI->second->getRHS()->EvaluateKnownConstInt(Context);
1098  AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1099 
1100  CaseExpr = RI->second->getRHS();
1101  if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1102  Hi))
1103  Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1104  << CondTypeBeforePromotion;
1105  }
1106 
1107  // Check which enum vals aren't in switch
1108  auto CI = CaseVals.begin();
1109  auto RI = CaseRanges.begin();
1110  bool hasCasesNotInSwitch = false;
1111 
1112  SmallVector<DeclarationName,8> UnhandledNames;
1113 
1114  for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1115  // Drop unneeded case values
1116  while (CI != CaseVals.end() && CI->first < EI->first)
1117  CI++;
1118 
1119  if (CI != CaseVals.end() && CI->first == EI->first)
1120  continue;
1121 
1122  // Drop unneeded case ranges
1123  for (; RI != CaseRanges.end(); RI++) {
1124  llvm::APSInt Hi =
1125  RI->second->getRHS()->EvaluateKnownConstInt(Context);
1126  AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1127  if (EI->first <= Hi)
1128  break;
1129  }
1130 
1131  if (RI == CaseRanges.end() || EI->first < RI->first) {
1132  hasCasesNotInSwitch = true;
1133  UnhandledNames.push_back(EI->second->getDeclName());
1134  }
1135  }
1136 
1137  if (TheDefaultStmt && UnhandledNames.empty())
1138  Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1139 
1140  // Produce a nice diagnostic if multiple values aren't handled.
1141  if (!UnhandledNames.empty()) {
1142  DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1143  TheDefaultStmt ? diag::warn_def_missing_case
1144  : diag::warn_missing_case)
1145  << (int)UnhandledNames.size();
1146 
1147  for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1148  I != E; ++I)
1149  DB << UnhandledNames[I];
1150  }
1151 
1152  if (!hasCasesNotInSwitch)
1153  SS->setAllEnumCasesCovered();
1154  }
1155  }
1156 
1157  if (BodyStmt)
1158  DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1159  diag::warn_empty_switch_body);
1160 
1161  // FIXME: If the case list was broken is some way, we don't have a good system
1162  // to patch it up. Instead, just return the whole substmt as broken.
1163  if (CaseListIsErroneous)
1164  return StmtError();
1165 
1166  return SS;
1167 }
1168 
1169 void
1171  Expr *SrcExpr) {
1172  if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1173  return;
1174 
1175  if (const EnumType *ET = DstType->getAs<EnumType>())
1176  if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1177  SrcType->isIntegerType()) {
1178  if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1179  SrcExpr->isIntegerConstantExpr(Context)) {
1180  // Get the bitwidth of the enum value before promotions.
1181  unsigned DstWidth = Context.getIntWidth(DstType);
1182  bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1183 
1184  llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1185  AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1186  const EnumDecl *ED = ET->getDecl();
1187 
1188  if (ED->hasAttr<FlagEnumAttr>()) {
1189  if (!IsValueInFlagEnum(ED, RhsVal, true))
1190  Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1191  << DstType.getUnqualifiedType();
1192  } else {
1194  EnumValsTy;
1195  EnumValsTy EnumVals;
1196 
1197  // Gather all enum values, set their type and sort them,
1198  // allowing easier comparison with rhs constant.
1199  for (auto *EDI : ED->enumerators()) {
1200  llvm::APSInt Val = EDI->getInitVal();
1201  AdjustAPSInt(Val, DstWidth, DstIsSigned);
1202  EnumVals.push_back(std::make_pair(Val, EDI));
1203  }
1204  if (EnumVals.empty())
1205  return;
1206  std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1207  EnumValsTy::iterator EIend =
1208  std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1209 
1210  // See which values aren't in the enum.
1211  EnumValsTy::const_iterator EI = EnumVals.begin();
1212  while (EI != EIend && EI->first < RhsVal)
1213  EI++;
1214  if (EI == EIend || EI->first != RhsVal) {
1215  Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1216  << DstType.getUnqualifiedType();
1217  }
1218  }
1219  }
1220  }
1221 }
1222 
1223 StmtResult
1225  Decl *CondVar, Stmt *Body) {
1226  ExprResult CondResult(Cond.release());
1227 
1228  VarDecl *ConditionVar = nullptr;
1229  if (CondVar) {
1230  ConditionVar = cast<VarDecl>(CondVar);
1231  CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1232  CondResult = ActOnFinishFullExpr(CondResult.get(), WhileLoc);
1233  if (CondResult.isInvalid())
1234  return StmtError();
1235  }
1236  Expr *ConditionExpr = CondResult.get();
1237  if (!ConditionExpr)
1238  return StmtError();
1239  CheckBreakContinueBinding(ConditionExpr);
1240 
1241  DiagnoseUnusedExprResult(Body);
1242 
1243  if (isa<NullStmt>(Body))
1244  getCurCompoundScope().setHasEmptyLoopBodies();
1245 
1246  return new (Context)
1247  WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
1248 }
1249 
1250 StmtResult
1252  SourceLocation WhileLoc, SourceLocation CondLParen,
1253  Expr *Cond, SourceLocation CondRParen) {
1254  assert(Cond && "ActOnDoStmt(): missing expression");
1255 
1256  CheckBreakContinueBinding(Cond);
1257  ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1258  if (CondResult.isInvalid())
1259  return StmtError();
1260  Cond = CondResult.get();
1261 
1262  CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1263  if (CondResult.isInvalid())
1264  return StmtError();
1265  Cond = CondResult.get();
1266 
1267  DiagnoseUnusedExprResult(Body);
1268 
1269  return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1270 }
1271 
1272 namespace {
1273  // This visitor will traverse a conditional statement and store all
1274  // the evaluated decls into a vector. Simple is set to true if none
1275  // of the excluded constructs are used.
1276  class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1277  llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1279  bool Simple;
1280  public:
1281  typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1282 
1283  DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1285  Inherited(S.Context),
1286  Decls(Decls),
1287  Ranges(Ranges),
1288  Simple(true) {}
1289 
1290  bool isSimple() { return Simple; }
1291 
1292  // Replaces the method in EvaluatedExprVisitor.
1293  void VisitMemberExpr(MemberExpr* E) {
1294  Simple = false;
1295  }
1296 
1297  // Any Stmt not whitelisted will cause the condition to be marked complex.
1298  void VisitStmt(Stmt *S) {
1299  Simple = false;
1300  }
1301 
1302  void VisitBinaryOperator(BinaryOperator *E) {
1303  Visit(E->getLHS());
1304  Visit(E->getRHS());
1305  }
1306 
1307  void VisitCastExpr(CastExpr *E) {
1308  Visit(E->getSubExpr());
1309  }
1310 
1311  void VisitUnaryOperator(UnaryOperator *E) {
1312  // Skip checking conditionals with derefernces.
1313  if (E->getOpcode() == UO_Deref)
1314  Simple = false;
1315  else
1316  Visit(E->getSubExpr());
1317  }
1318 
1319  void VisitConditionalOperator(ConditionalOperator *E) {
1320  Visit(E->getCond());
1321  Visit(E->getTrueExpr());
1322  Visit(E->getFalseExpr());
1323  }
1324 
1325  void VisitParenExpr(ParenExpr *E) {
1326  Visit(E->getSubExpr());
1327  }
1328 
1329  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1330  Visit(E->getOpaqueValue()->getSourceExpr());
1331  Visit(E->getFalseExpr());
1332  }
1333 
1334  void VisitIntegerLiteral(IntegerLiteral *E) { }
1335  void VisitFloatingLiteral(FloatingLiteral *E) { }
1336  void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1337  void VisitCharacterLiteral(CharacterLiteral *E) { }
1338  void VisitGNUNullExpr(GNUNullExpr *E) { }
1339  void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1340 
1341  void VisitDeclRefExpr(DeclRefExpr *E) {
1342  VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1343  if (!VD) return;
1344 
1345  Ranges.push_back(E->getSourceRange());
1346 
1347  Decls.insert(VD);
1348  }
1349 
1350  }; // end class DeclExtractor
1351 
1352  // DeclMatcher checks to see if the decls are used in a non-evauluated
1353  // context.
1354  class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1355  llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1356  bool FoundDecl;
1357 
1358  public:
1359  typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1360 
1361  DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1362  Stmt *Statement) :
1363  Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1364  if (!Statement) return;
1365 
1366  Visit(Statement);
1367  }
1368 
1369  void VisitReturnStmt(ReturnStmt *S) {
1370  FoundDecl = true;
1371  }
1372 
1373  void VisitBreakStmt(BreakStmt *S) {
1374  FoundDecl = true;
1375  }
1376 
1377  void VisitGotoStmt(GotoStmt *S) {
1378  FoundDecl = true;
1379  }
1380 
1381  void VisitCastExpr(CastExpr *E) {
1382  if (E->getCastKind() == CK_LValueToRValue)
1383  CheckLValueToRValueCast(E->getSubExpr());
1384  else
1385  Visit(E->getSubExpr());
1386  }
1387 
1388  void CheckLValueToRValueCast(Expr *E) {
1389  E = E->IgnoreParenImpCasts();
1390 
1391  if (isa<DeclRefExpr>(E)) {
1392  return;
1393  }
1394 
1395  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1396  Visit(CO->getCond());
1397  CheckLValueToRValueCast(CO->getTrueExpr());
1398  CheckLValueToRValueCast(CO->getFalseExpr());
1399  return;
1400  }
1401 
1402  if (BinaryConditionalOperator *BCO =
1403  dyn_cast<BinaryConditionalOperator>(E)) {
1404  CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1405  CheckLValueToRValueCast(BCO->getFalseExpr());
1406  return;
1407  }
1408 
1409  Visit(E);
1410  }
1411 
1412  void VisitDeclRefExpr(DeclRefExpr *E) {
1413  if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1414  if (Decls.count(VD))
1415  FoundDecl = true;
1416  }
1417 
1418  bool FoundDeclInUse() { return FoundDecl; }
1419 
1420  }; // end class DeclMatcher
1421 
1422  void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1423  Expr *Third, Stmt *Body) {
1424  // Condition is empty
1425  if (!Second) return;
1426 
1427  if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1428  Second->getLocStart()))
1429  return;
1430 
1431  PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1432  llvm::SmallPtrSet<VarDecl*, 8> Decls;
1434  DeclExtractor DE(S, Decls, Ranges);
1435  DE.Visit(Second);
1436 
1437  // Don't analyze complex conditionals.
1438  if (!DE.isSimple()) return;
1439 
1440  // No decls found.
1441  if (Decls.size() == 0) return;
1442 
1443  // Don't warn on volatile, static, or global variables.
1444  for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1445  E = Decls.end();
1446  I != E; ++I)
1447  if ((*I)->getType().isVolatileQualified() ||
1448  (*I)->hasGlobalStorage()) return;
1449 
1450  if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1451  DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1452  DeclMatcher(S, Decls, Body).FoundDeclInUse())
1453  return;
1454 
1455  // Load decl names into diagnostic.
1456  if (Decls.size() > 4)
1457  PDiag << 0;
1458  else {
1459  PDiag << Decls.size();
1460  for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1461  E = Decls.end();
1462  I != E; ++I)
1463  PDiag << (*I)->getDeclName();
1464  }
1465 
1466  // Load SourceRanges into diagnostic if there is room.
1467  // Otherwise, load the SourceRange of the conditional expression.
1468  if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1469  for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1470  E = Ranges.end();
1471  I != E; ++I)
1472  PDiag << *I;
1473  else
1474  PDiag << Second->getSourceRange();
1475 
1476  S.Diag(Ranges.begin()->getBegin(), PDiag);
1477  }
1478 
1479  // If Statement is an incemement or decrement, return true and sets the
1480  // variables Increment and DRE.
1481  bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1482  DeclRefExpr *&DRE) {
1483  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1484  switch (UO->getOpcode()) {
1485  default: return false;
1486  case UO_PostInc:
1487  case UO_PreInc:
1488  Increment = true;
1489  break;
1490  case UO_PostDec:
1491  case UO_PreDec:
1492  Increment = false;
1493  break;
1494  }
1495  DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1496  return DRE;
1497  }
1498 
1499  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1500  FunctionDecl *FD = Call->getDirectCallee();
1501  if (!FD || !FD->isOverloadedOperator()) return false;
1502  switch (FD->getOverloadedOperator()) {
1503  default: return false;
1504  case OO_PlusPlus:
1505  Increment = true;
1506  break;
1507  case OO_MinusMinus:
1508  Increment = false;
1509  break;
1510  }
1511  DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1512  return DRE;
1513  }
1514 
1515  return false;
1516  }
1517 
1518  // A visitor to determine if a continue or break statement is a
1519  // subexpression.
1520  class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1521  SourceLocation BreakLoc;
1522  SourceLocation ContinueLoc;
1523  public:
1524  BreakContinueFinder(Sema &S, Stmt* Body) :
1525  Inherited(S.Context) {
1526  Visit(Body);
1527  }
1528 
1530 
1531  void VisitContinueStmt(ContinueStmt* E) {
1532  ContinueLoc = E->getContinueLoc();
1533  }
1534 
1535  void VisitBreakStmt(BreakStmt* E) {
1536  BreakLoc = E->getBreakLoc();
1537  }
1538 
1539  bool ContinueFound() { return ContinueLoc.isValid(); }
1540  bool BreakFound() { return BreakLoc.isValid(); }
1541  SourceLocation GetContinueLoc() { return ContinueLoc; }
1542  SourceLocation GetBreakLoc() { return BreakLoc; }
1543 
1544  }; // end class BreakContinueFinder
1545 
1546  // Emit a warning when a loop increment/decrement appears twice per loop
1547  // iteration. The conditions which trigger this warning are:
1548  // 1) The last statement in the loop body and the third expression in the
1549  // for loop are both increment or both decrement of the same variable
1550  // 2) No continue statements in the loop body.
1551  void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1552  // Return when there is nothing to check.
1553  if (!Body || !Third) return;
1554 
1555  if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1556  Third->getLocStart()))
1557  return;
1558 
1559  // Get the last statement from the loop body.
1560  CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1561  if (!CS || CS->body_empty()) return;
1562  Stmt *LastStmt = CS->body_back();
1563  if (!LastStmt) return;
1564 
1565  bool LoopIncrement, LastIncrement;
1566  DeclRefExpr *LoopDRE, *LastDRE;
1567 
1568  if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1569  if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1570 
1571  // Check that the two statements are both increments or both decrements
1572  // on the same variable.
1573  if (LoopIncrement != LastIncrement ||
1574  LoopDRE->getDecl() != LastDRE->getDecl()) return;
1575 
1576  if (BreakContinueFinder(S, Body).ContinueFound()) return;
1577 
1578  S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1579  << LastDRE->getDecl() << LastIncrement;
1580  S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1581  << LoopIncrement;
1582  }
1583 
1584 } // end namespace
1585 
1586 
1587 void Sema::CheckBreakContinueBinding(Expr *E) {
1588  if (!E || getLangOpts().CPlusPlus)
1589  return;
1590  BreakContinueFinder BCFinder(*this, E);
1591  Scope *BreakParent = CurScope->getBreakParent();
1592  if (BCFinder.BreakFound() && BreakParent) {
1593  if (BreakParent->getFlags() & Scope::SwitchScope) {
1594  Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1595  } else {
1596  Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1597  << "break";
1598  }
1599  } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1600  Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1601  << "continue";
1602  }
1603 }
1604 
1605 StmtResult
1607  Stmt *First, FullExprArg second, Decl *secondVar,
1608  FullExprArg third,
1609  SourceLocation RParenLoc, Stmt *Body) {
1610  if (!getLangOpts().CPlusPlus) {
1611  if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1612  // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1613  // declare identifiers for objects having storage class 'auto' or
1614  // 'register'.
1615  for (auto *DI : DS->decls()) {
1616  VarDecl *VD = dyn_cast<VarDecl>(DI);
1617  if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1618  VD = nullptr;
1619  if (!VD) {
1620  Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1621  DI->setInvalidDecl();
1622  }
1623  }
1624  }
1625  }
1626 
1627  CheckBreakContinueBinding(second.get());
1628  CheckBreakContinueBinding(third.get());
1629 
1630  CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1631  CheckForRedundantIteration(*this, third.get(), Body);
1632 
1633  ExprResult SecondResult(second.release());
1634  VarDecl *ConditionVar = nullptr;
1635  if (secondVar) {
1636  ConditionVar = cast<VarDecl>(secondVar);
1637  SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1638  SecondResult = ActOnFinishFullExpr(SecondResult.get(), ForLoc);
1639  if (SecondResult.isInvalid())
1640  return StmtError();
1641  }
1642 
1643  Expr *Third = third.release().getAs<Expr>();
1644 
1645  DiagnoseUnusedExprResult(First);
1646  DiagnoseUnusedExprResult(Third);
1647  DiagnoseUnusedExprResult(Body);
1648 
1649  if (isa<NullStmt>(Body))
1650  getCurCompoundScope().setHasEmptyLoopBodies();
1651 
1652  return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1653  Third, Body, ForLoc, LParenLoc, RParenLoc);
1654 }
1655 
1656 /// In an Objective C collection iteration statement:
1657 /// for (x in y)
1658 /// x can be an arbitrary l-value expression. Bind it up as a
1659 /// full-expression.
1661  // Reduce placeholder expressions here. Note that this rejects the
1662  // use of pseudo-object l-values in this position.
1663  ExprResult result = CheckPlaceholderExpr(E);
1664  if (result.isInvalid()) return StmtError();
1665  E = result.get();
1666 
1667  ExprResult FullExpr = ActOnFinishFullExpr(E);
1668  if (FullExpr.isInvalid())
1669  return StmtError();
1670  return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1671 }
1672 
1673 ExprResult
1675  if (!collection)
1676  return ExprError();
1677 
1678  ExprResult result = CorrectDelayedTyposInExpr(collection);
1679  if (!result.isUsable())
1680  return ExprError();
1681  collection = result.get();
1682 
1683  // Bail out early if we've got a type-dependent expression.
1684  if (collection->isTypeDependent()) return collection;
1685 
1686  // Perform normal l-value conversion.
1687  result = DefaultFunctionArrayLvalueConversion(collection);
1688  if (result.isInvalid())
1689  return ExprError();
1690  collection = result.get();
1691 
1692  // The operand needs to have object-pointer type.
1693  // TODO: should we do a contextual conversion?
1694  const ObjCObjectPointerType *pointerType =
1695  collection->getType()->getAs<ObjCObjectPointerType>();
1696  if (!pointerType)
1697  return Diag(forLoc, diag::err_collection_expr_type)
1698  << collection->getType() << collection->getSourceRange();
1699 
1700  // Check that the operand provides
1701  // - countByEnumeratingWithState:objects:count:
1702  const ObjCObjectType *objectType = pointerType->getObjectType();
1703  ObjCInterfaceDecl *iface = objectType->getInterface();
1704 
1705  // If we have a forward-declared type, we can't do this check.
1706  // Under ARC, it is an error not to have a forward-declared class.
1707  if (iface &&
1708  RequireCompleteType(forLoc, QualType(objectType, 0),
1709  getLangOpts().ObjCAutoRefCount
1710  ? diag::err_arc_collection_forward
1711  : 0,
1712  collection)) {
1713  // Otherwise, if we have any useful type information, check that
1714  // the type declares the appropriate method.
1715  } else if (iface || !objectType->qual_empty()) {
1716  IdentifierInfo *selectorIdents[] = {
1717  &Context.Idents.get("countByEnumeratingWithState"),
1718  &Context.Idents.get("objects"),
1719  &Context.Idents.get("count")
1720  };
1721  Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1722 
1723  ObjCMethodDecl *method = nullptr;
1724 
1725  // If there's an interface, look in both the public and private APIs.
1726  if (iface) {
1727  method = iface->lookupInstanceMethod(selector);
1728  if (!method) method = iface->lookupPrivateMethod(selector);
1729  }
1730 
1731  // Also check protocol qualifiers.
1732  if (!method)
1733  method = LookupMethodInQualifiedType(selector, pointerType,
1734  /*instance*/ true);
1735 
1736  // If we didn't find it anywhere, give up.
1737  if (!method) {
1738  Diag(forLoc, diag::warn_collection_expr_type)
1739  << collection->getType() << selector << collection->getSourceRange();
1740  }
1741 
1742  // TODO: check for an incompatible signature?
1743  }
1744 
1745  // Wrap up any cleanups in the expression.
1746  return collection;
1747 }
1748 
1749 StmtResult
1751  Stmt *First, Expr *collection,
1752  SourceLocation RParenLoc) {
1753 
1754  ExprResult CollectionExprResult =
1755  CheckObjCForCollectionOperand(ForLoc, collection);
1756 
1757  if (First) {
1758  QualType FirstType;
1759  if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1760  if (!DS->isSingleDecl())
1761  return StmtError(Diag((*DS->decl_begin())->getLocation(),
1762  diag::err_toomany_element_decls));
1763 
1764  VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1765  if (!D || D->isInvalidDecl())
1766  return StmtError();
1767 
1768  FirstType = D->getType();
1769  // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1770  // declare identifiers for objects having storage class 'auto' or
1771  // 'register'.
1772  if (!D->hasLocalStorage())
1773  return StmtError(Diag(D->getLocation(),
1774  diag::err_non_local_variable_decl_in_for));
1775 
1776  // If the type contained 'auto', deduce the 'auto' to 'id'.
1777  if (FirstType->getContainedAutoType()) {
1779  VK_RValue);
1780  Expr *DeducedInit = &OpaqueId;
1781  if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1782  DAR_Failed)
1783  DiagnoseAutoDeductionFailure(D, DeducedInit);
1784  if (FirstType.isNull()) {
1785  D->setInvalidDecl();
1786  return StmtError();
1787  }
1788 
1789  D->setType(FirstType);
1790 
1791  if (ActiveTemplateInstantiations.empty()) {
1792  SourceLocation Loc =
1794  Diag(Loc, diag::warn_auto_var_is_id)
1795  << D->getDeclName();
1796  }
1797  }
1798 
1799  } else {
1800  Expr *FirstE = cast<Expr>(First);
1801  if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1802  return StmtError(Diag(First->getLocStart(),
1803  diag::err_selector_element_not_lvalue)
1804  << First->getSourceRange());
1805 
1806  FirstType = static_cast<Expr*>(First)->getType();
1807  if (FirstType.isConstQualified())
1808  Diag(ForLoc, diag::err_selector_element_const_type)
1809  << FirstType << First->getSourceRange();
1810  }
1811  if (!FirstType->isDependentType() &&
1812  !FirstType->isObjCObjectPointerType() &&
1813  !FirstType->isBlockPointerType())
1814  return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1815  << FirstType << First->getSourceRange());
1816  }
1817 
1818  if (CollectionExprResult.isInvalid())
1819  return StmtError();
1820 
1821  CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1822  if (CollectionExprResult.isInvalid())
1823  return StmtError();
1824 
1825  return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1826  nullptr, ForLoc, RParenLoc);
1827 }
1828 
1829 /// Finish building a variable declaration for a for-range statement.
1830 /// \return true if an error occurs.
1831 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1832  SourceLocation Loc, int DiagID) {
1833  if (Decl->getType()->isUndeducedType()) {
1834  ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1835  if (!Res.isUsable()) {
1836  Decl->setInvalidDecl();
1837  return true;
1838  }
1839  Init = Res.get();
1840  }
1841 
1842  // Deduce the type for the iterator variable now rather than leaving it to
1843  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1844  QualType InitType;
1845  if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1846  SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1848  SemaRef.Diag(Loc, DiagID) << Init->getType();
1849  if (InitType.isNull()) {
1850  Decl->setInvalidDecl();
1851  return true;
1852  }
1853  Decl->setType(InitType);
1854 
1855  // In ARC, infer lifetime.
1856  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1857  // we're doing the equivalent of fast iteration.
1858  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1859  SemaRef.inferObjCARCLifetime(Decl))
1860  Decl->setInvalidDecl();
1861 
1862  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1863  /*TypeMayContainAuto=*/false);
1864  SemaRef.FinalizeDeclaration(Decl);
1865  SemaRef.CurContext->addHiddenDecl(Decl);
1866  return false;
1867 }
1868 
1869 namespace {
1870 
1871 /// Produce a note indicating which begin/end function was implicitly called
1872 /// by a C++11 for-range statement. This is often not obvious from the code,
1873 /// nor from the diagnostics produced when analysing the implicit expressions
1874 /// required in a for-range statement.
1875 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1876  Sema::BeginEndFunction BEF) {
1877  CallExpr *CE = dyn_cast<CallExpr>(E);
1878  if (!CE)
1879  return;
1880  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1881  if (!D)
1882  return;
1883  SourceLocation Loc = D->getLocation();
1884 
1885  std::string Description;
1886  bool IsTemplate = false;
1887  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1888  Description = SemaRef.getTemplateArgumentBindingsText(
1889  FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1890  IsTemplate = true;
1891  }
1892 
1893  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1894  << BEF << IsTemplate << Description << E->getType();
1895 }
1896 
1897 /// Build a variable declaration for a for-range statement.
1898 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1899  QualType Type, const char *Name) {
1900  DeclContext *DC = SemaRef.CurContext;
1901  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1902  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1903  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1904  TInfo, SC_None);
1905  Decl->setImplicit();
1906  return Decl;
1907 }
1908 
1909 }
1910 
1911 static bool ObjCEnumerationCollection(Expr *Collection) {
1912  return !Collection->isTypeDependent()
1913  && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1914 }
1915 
1916 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1917 ///
1918 /// C++11 [stmt.ranged]:
1919 /// A range-based for statement is equivalent to
1920 ///
1921 /// {
1922 /// auto && __range = range-init;
1923 /// for ( auto __begin = begin-expr,
1924 /// __end = end-expr;
1925 /// __begin != __end;
1926 /// ++__begin ) {
1927 /// for-range-declaration = *__begin;
1928 /// statement
1929 /// }
1930 /// }
1931 ///
1932 /// The body of the loop is not available yet, since it cannot be analysed until
1933 /// we have determined the type of the for-range-declaration.
1934 StmtResult
1936  Stmt *First, SourceLocation ColonLoc, Expr *Range,
1937  SourceLocation RParenLoc, BuildForRangeKind Kind) {
1938  if (!First)
1939  return StmtError();
1940 
1941  if (Range && ObjCEnumerationCollection(Range))
1942  return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1943 
1944  DeclStmt *DS = dyn_cast<DeclStmt>(First);
1945  assert(DS && "first part of for range not a decl stmt");
1946 
1947  if (!DS->isSingleDecl()) {
1948  Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1949  return StmtError();
1950  }
1951 
1952  Decl *LoopVar = DS->getSingleDecl();
1953  if (LoopVar->isInvalidDecl() || !Range ||
1954  DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1955  LoopVar->setInvalidDecl();
1956  return StmtError();
1957  }
1958 
1959  // Build auto && __range = range-init
1960  SourceLocation RangeLoc = Range->getLocStart();
1961  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1963  "__range");
1964  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1965  diag::err_for_range_deduction_failure)) {
1966  LoopVar->setInvalidDecl();
1967  return StmtError();
1968  }
1969 
1970  // Claim the type doesn't contain auto: we've already done the checking.
1971  DeclGroupPtrTy RangeGroup =
1972  BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1973  /*TypeMayContainAuto=*/ false);
1974  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1975  if (RangeDecl.isInvalid()) {
1976  LoopVar->setInvalidDecl();
1977  return StmtError();
1978  }
1979 
1980  return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1981  /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1982  /*Inc=*/nullptr, DS, RParenLoc, Kind);
1983 }
1984 
1985 /// \brief Create the initialization, compare, and increment steps for
1986 /// the range-based for loop expression.
1987 /// This function does not handle array-based for loops,
1988 /// which are created in Sema::BuildCXXForRangeStmt.
1989 ///
1990 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
1991 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1992 /// CandidateSet and BEF are set and some non-success value is returned on
1993 /// failure.
1995  Expr *BeginRange, Expr *EndRange,
1996  QualType RangeType,
1997  VarDecl *BeginVar,
1998  VarDecl *EndVar,
2000  OverloadCandidateSet *CandidateSet,
2001  ExprResult *BeginExpr,
2002  ExprResult *EndExpr,
2003  Sema::BeginEndFunction *BEF) {
2004  DeclarationNameInfo BeginNameInfo(
2005  &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2006  DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2007  ColonLoc);
2008 
2009  LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2011  LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2012 
2013  if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2014  // - if _RangeT is a class type, the unqualified-ids begin and end are
2015  // looked up in the scope of class _RangeT as if by class member access
2016  // lookup (3.4.5), and if either (or both) finds at least one
2017  // declaration, begin-expr and end-expr are __range.begin() and
2018  // __range.end(), respectively;
2019  SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2020  SemaRef.LookupQualifiedName(EndMemberLookup, D);
2021 
2022  if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2023  SourceLocation RangeLoc = BeginVar->getLocation();
2024  *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2025 
2026  SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2027  << RangeLoc << BeginRange->getType() << *BEF;
2029  }
2030  } else {
2031  // - otherwise, begin-expr and end-expr are begin(__range) and
2032  // end(__range), respectively, where begin and end are looked up with
2033  // argument-dependent lookup (3.4.2). For the purposes of this name
2034  // lookup, namespace std is an associated namespace.
2035 
2036  }
2037 
2038  *BEF = Sema::BEF_begin;
2039  Sema::ForRangeStatus RangeStatus =
2040  SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2041  Sema::BEF_begin, BeginNameInfo,
2042  BeginMemberLookup, CandidateSet,
2043  BeginRange, BeginExpr);
2044 
2045  if (RangeStatus != Sema::FRS_Success)
2046  return RangeStatus;
2047  if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2048  diag::err_for_range_iter_deduction_failure)) {
2049  NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2051  }
2052 
2053  *BEF = Sema::BEF_end;
2054  RangeStatus =
2055  SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2056  Sema::BEF_end, EndNameInfo,
2057  EndMemberLookup, CandidateSet,
2058  EndRange, EndExpr);
2059  if (RangeStatus != Sema::FRS_Success)
2060  return RangeStatus;
2061  if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2062  diag::err_for_range_iter_deduction_failure)) {
2063  NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2065  }
2066  return Sema::FRS_Success;
2067 }
2068 
2069 /// Speculatively attempt to dereference an invalid range expression.
2070 /// If the attempt fails, this function will return a valid, null StmtResult
2071 /// and emit no diagnostics.
2073  SourceLocation ForLoc,
2074  Stmt *LoopVarDecl,
2076  Expr *Range,
2077  SourceLocation RangeLoc,
2078  SourceLocation RParenLoc) {
2079  // Determine whether we can rebuild the for-range statement with a
2080  // dereferenced range expression.
2081  ExprResult AdjustedRange;
2082  {
2083  Sema::SFINAETrap Trap(SemaRef);
2084 
2085  AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2086  if (AdjustedRange.isInvalid())
2087  return StmtResult();
2088 
2089  StmtResult SR =
2090  SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2091  AdjustedRange.get(), RParenLoc,
2093  if (SR.isInvalid())
2094  return StmtResult();
2095  }
2096 
2097  // The attempt to dereference worked well enough that it could produce a valid
2098  // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2099  // case there are any other (non-fatal) problems with it.
2100  SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2101  << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2102  return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2103  AdjustedRange.get(), RParenLoc,
2105 }
2106 
2107 namespace {
2108 /// RAII object to automatically invalidate a declaration if an error occurs.
2109 struct InvalidateOnErrorScope {
2110  InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2111  : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2112  ~InvalidateOnErrorScope() {
2113  if (Enabled && Trap.hasErrorOccurred())
2114  D->setInvalidDecl();
2115  }
2116 
2117  DiagnosticErrorTrap Trap;
2118  Decl *D;
2119  bool Enabled;
2120 };
2121 }
2122 
2123 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2124 StmtResult
2126  Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2127  Expr *Inc, Stmt *LoopVarDecl,
2128  SourceLocation RParenLoc, BuildForRangeKind Kind) {
2129  Scope *S = getCurScope();
2130 
2131  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2132  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2133  QualType RangeVarType = RangeVar->getType();
2134 
2135  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2136  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2137 
2138  // If we hit any errors, mark the loop variable as invalid if its type
2139  // contains 'auto'.
2140  InvalidateOnErrorScope Invalidate(*this, LoopVar,
2141  LoopVar->getType()->isUndeducedType());
2142 
2143  StmtResult BeginEndDecl = BeginEnd;
2144  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2145 
2146  if (RangeVarType->isDependentType()) {
2147  // The range is implicitly used as a placeholder when it is dependent.
2148  RangeVar->markUsed(Context);
2149 
2150  // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2151  // them in properly when we instantiate the loop.
2152  if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2153  LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2154  } else if (!BeginEndDecl.get()) {
2155  SourceLocation RangeLoc = RangeVar->getLocation();
2156 
2157  const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2158 
2159  ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2160  VK_LValue, ColonLoc);
2161  if (BeginRangeRef.isInvalid())
2162  return StmtError();
2163 
2164  ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2165  VK_LValue, ColonLoc);
2166  if (EndRangeRef.isInvalid())
2167  return StmtError();
2168 
2170  Expr *Range = RangeVar->getInit();
2171  if (!Range)
2172  return StmtError();
2173  QualType RangeType = Range->getType();
2174 
2175  if (RequireCompleteType(RangeLoc, RangeType,
2176  diag::err_for_range_incomplete_type))
2177  return StmtError();
2178 
2179  // Build auto __begin = begin-expr, __end = end-expr.
2180  VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2181  "__begin");
2182  VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2183  "__end");
2184 
2185  // Build begin-expr and end-expr and attach to __begin and __end variables.
2186  ExprResult BeginExpr, EndExpr;
2187  if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2188  // - if _RangeT is an array type, begin-expr and end-expr are __range and
2189  // __range + __bound, respectively, where __bound is the array bound. If
2190  // _RangeT is an array of unknown size or an array of incomplete type,
2191  // the program is ill-formed;
2192 
2193  // begin-expr is __range.
2194  BeginExpr = BeginRangeRef;
2195  if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2196  diag::err_for_range_iter_deduction_failure)) {
2197  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2198  return StmtError();
2199  }
2200 
2201  // Find the array bound.
2202  ExprResult BoundExpr;
2203  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2204  BoundExpr = IntegerLiteral::Create(
2205  Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2206  else if (const VariableArrayType *VAT =
2207  dyn_cast<VariableArrayType>(UnqAT))
2208  BoundExpr = VAT->getSizeExpr();
2209  else {
2210  // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2211  // UnqAT is not incomplete and Range is not type-dependent.
2212  llvm_unreachable("Unexpected array type in for-range");
2213  }
2214 
2215  // end-expr is __range + __bound.
2216  EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2217  BoundExpr.get());
2218  if (EndExpr.isInvalid())
2219  return StmtError();
2220  if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2221  diag::err_for_range_iter_deduction_failure)) {
2222  NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2223  return StmtError();
2224  }
2225  } else {
2226  OverloadCandidateSet CandidateSet(RangeLoc,
2228  Sema::BeginEndFunction BEFFailure;
2229  ForRangeStatus RangeStatus =
2230  BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2231  EndRangeRef.get(), RangeType,
2232  BeginVar, EndVar, ColonLoc, &CandidateSet,
2233  &BeginExpr, &EndExpr, &BEFFailure);
2234 
2235  if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2236  BEFFailure == BEF_begin) {
2237  // If the range is being built from an array parameter, emit a
2238  // a diagnostic that it is being treated as a pointer.
2239  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2240  if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2241  QualType ArrayTy = PVD->getOriginalType();
2242  QualType PointerTy = PVD->getType();
2243  if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2244  Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2245  << RangeLoc << PVD << ArrayTy << PointerTy;
2246  Diag(PVD->getLocation(), diag::note_declared_at);
2247  return StmtError();
2248  }
2249  }
2250  }
2251 
2252  // If building the range failed, try dereferencing the range expression
2253  // unless a diagnostic was issued or the end function is problematic.
2254  StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2255  LoopVarDecl, ColonLoc,
2256  Range, RangeLoc,
2257  RParenLoc);
2258  if (SR.isInvalid() || SR.isUsable())
2259  return SR;
2260  }
2261 
2262  // Otherwise, emit diagnostics if we haven't already.
2263  if (RangeStatus == FRS_NoViableFunction) {
2264  Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2265  Diag(Range->getLocStart(), diag::err_for_range_invalid)
2266  << RangeLoc << Range->getType() << BEFFailure;
2267  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2268  }
2269  // Return an error if no fix was discovered.
2270  if (RangeStatus != FRS_Success)
2271  return StmtError();
2272  }
2273 
2274  assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2275  "invalid range expression in for loop");
2276 
2277  // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2278  QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2279  if (!Context.hasSameType(BeginType, EndType)) {
2280  Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2281  << BeginType << EndType;
2282  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2283  NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2284  }
2285 
2286  Decl *BeginEndDecls[] = { BeginVar, EndVar };
2287  // Claim the type doesn't contain auto: we've already done the checking.
2288  DeclGroupPtrTy BeginEndGroup =
2289  BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
2290  /*TypeMayContainAuto=*/ false);
2291  BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2292 
2293  const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2294  ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2295  VK_LValue, ColonLoc);
2296  if (BeginRef.isInvalid())
2297  return StmtError();
2298 
2299  ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2300  VK_LValue, ColonLoc);
2301  if (EndRef.isInvalid())
2302  return StmtError();
2303 
2304  // Build and check __begin != __end expression.
2305  NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2306  BeginRef.get(), EndRef.get());
2307  NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2308  NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2309  if (NotEqExpr.isInvalid()) {
2310  Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2311  << RangeLoc << 0 << BeginRangeRef.get()->getType();
2312  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2313  if (!Context.hasSameType(BeginType, EndType))
2314  NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2315  return StmtError();
2316  }
2317 
2318  // Build and check ++__begin expression.
2319  BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2320  VK_LValue, ColonLoc);
2321  if (BeginRef.isInvalid())
2322  return StmtError();
2323 
2324  IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2325  IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2326  if (IncrExpr.isInvalid()) {
2327  Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2328  << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2329  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2330  return StmtError();
2331  }
2332 
2333  // Build and check *__begin expression.
2334  BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2335  VK_LValue, ColonLoc);
2336  if (BeginRef.isInvalid())
2337  return StmtError();
2338 
2339  ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2340  if (DerefExpr.isInvalid()) {
2341  Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2342  << RangeLoc << 1 << BeginRangeRef.get()->getType();
2343  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2344  return StmtError();
2345  }
2346 
2347  // Attach *__begin as initializer for VD. Don't touch it if we're just
2348  // trying to determine whether this would be a valid range.
2349  if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2350  AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2351  /*TypeMayContainAuto=*/true);
2352  if (LoopVar->isInvalidDecl())
2353  NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2354  }
2355  }
2356 
2357  // Don't bother to actually allocate the result if we're just trying to
2358  // determine whether it would be valid.
2359  if (Kind == BFRK_Check)
2360  return StmtResult();
2361 
2362  return new (Context) CXXForRangeStmt(
2363  RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2364  IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
2365 }
2366 
2367 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2368 /// statement.
2370  if (!S || !B)
2371  return StmtError();
2372  ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2373 
2374  ForStmt->setBody(B);
2375  return S;
2376 }
2377 
2378 // Warn when the loop variable is a const reference that creates a copy.
2379 // Suggest using the non-reference type for copies. If a copy can be prevented
2380 // suggest the const reference type that would do so.
2381 // For instance, given "for (const &Foo : Range)", suggest
2382 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2383 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2384 // the copy altogether.
2386  const VarDecl *VD,
2387  QualType RangeInitType) {
2388  const Expr *InitExpr = VD->getInit();
2389  if (!InitExpr)
2390  return;
2391 
2392  QualType VariableType = VD->getType();
2393 
2394  const MaterializeTemporaryExpr *MTE =
2395  dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2396 
2397  // No copy made.
2398  if (!MTE)
2399  return;
2400 
2401  const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2402 
2403  // Searching for either UnaryOperator for dereference of a pointer or
2404  // CXXOperatorCallExpr for handling iterators.
2405  while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2406  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2407  E = CCE->getArg(0);
2408  } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2409  const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2410  E = ME->getBase();
2411  } else {
2412  const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2413  E = MTE->GetTemporaryExpr();
2414  }
2415  E = E->IgnoreImpCasts();
2416  }
2417 
2418  bool ReturnsReference = false;
2419  if (isa<UnaryOperator>(E)) {
2420  ReturnsReference = true;
2421  } else {
2422  const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2423  const FunctionDecl *FD = Call->getDirectCallee();
2424  QualType ReturnType = FD->getReturnType();
2425  ReturnsReference = ReturnType->isReferenceType();
2426  }
2427 
2428  if (ReturnsReference) {
2429  // Loop variable creates a temporary. Suggest either to go with
2430  // non-reference loop variable to indiciate a copy is made, or
2431  // the correct time to bind a const reference.
2432  SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2433  << VD << VariableType << E->getType();
2434  QualType NonReferenceType = VariableType.getNonReferenceType();
2435  NonReferenceType.removeLocalConst();
2436  QualType NewReferenceType =
2438  SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2439  << NonReferenceType << NewReferenceType << VD->getSourceRange();
2440  } else {
2441  // The range always returns a copy, so a temporary is always created.
2442  // Suggest removing the reference from the loop variable.
2443  SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2444  << VD << RangeInitType;
2445  QualType NonReferenceType = VariableType.getNonReferenceType();
2446  NonReferenceType.removeLocalConst();
2447  SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2448  << NonReferenceType << VD->getSourceRange();
2449  }
2450 }
2451 
2452 // Warns when the loop variable can be changed to a reference type to
2453 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2454 // "for (const Foo &x : Range)" if this form does not make a copy.
2456  const VarDecl *VD) {
2457  const Expr *InitExpr = VD->getInit();
2458  if (!InitExpr)
2459  return;
2460 
2461  QualType VariableType = VD->getType();
2462 
2463  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2464  if (!CE->getConstructor()->isCopyConstructor())
2465  return;
2466  } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2467  if (CE->getCastKind() != CK_LValueToRValue)
2468  return;
2469  } else {
2470  return;
2471  }
2472 
2473  // TODO: Determine a maximum size that a POD type can be before a diagnostic
2474  // should be emitted. Also, only ignore POD types with trivial copy
2475  // constructors.
2476  if (VariableType.isPODType(SemaRef.Context))
2477  return;
2478 
2479  // Suggest changing from a const variable to a const reference variable
2480  // if doing so will prevent a copy.
2481  SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2482  << VD << VariableType << InitExpr->getType();
2483  SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2484  << SemaRef.Context.getLValueReferenceType(VariableType)
2485  << VD->getSourceRange();
2486 }
2487 
2488 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2489 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2490 /// using "const foo x" to show that a copy is made
2491 /// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2492 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2493 /// prevent the copy.
2494 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2495 /// Suggest "const foo &x" to prevent the copy.
2497  const CXXForRangeStmt *ForStmt) {
2498  if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2499  ForStmt->getLocStart()) &&
2500  SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2501  ForStmt->getLocStart()) &&
2502  SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2503  ForStmt->getLocStart())) {
2504  return;
2505  }
2506 
2507  const VarDecl *VD = ForStmt->getLoopVariable();
2508  if (!VD)
2509  return;
2510 
2511  QualType VariableType = VD->getType();
2512 
2513  if (VariableType->isIncompleteType())
2514  return;
2515 
2516  const Expr *InitExpr = VD->getInit();
2517  if (!InitExpr)
2518  return;
2519 
2520  if (VariableType->isReferenceType()) {
2522  ForStmt->getRangeInit()->getType());
2523  } else if (VariableType.isConstQualified()) {
2525  }
2526 }
2527 
2528 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2529 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2530 /// body cannot be performed until after the type of the range variable is
2531 /// determined.
2533  if (!S || !B)
2534  return StmtError();
2535 
2536  if (isa<ObjCForCollectionStmt>(S))
2537  return FinishObjCForCollectionStmt(S, B);
2538 
2539  CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2540  ForStmt->setBody(B);
2541 
2542  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2543  diag::warn_empty_range_based_for_body);
2544 
2545  DiagnoseForRangeVariableCopies(*this, ForStmt);
2546 
2547  return S;
2548 }
2549 
2551  SourceLocation LabelLoc,
2552  LabelDecl *TheDecl) {
2553  getCurFunction()->setHasBranchIntoScope();
2554  TheDecl->markUsed(Context);
2555  return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2556 }
2557 
2558 StmtResult
2560  Expr *E) {
2561  // Convert operand to void*
2562  if (!E->isTypeDependent()) {
2563  QualType ETy = E->getType();
2565  ExprResult ExprRes = E;
2566  AssignConvertType ConvTy =
2567  CheckSingleAssignmentConstraints(DestTy, ExprRes);
2568  if (ExprRes.isInvalid())
2569  return StmtError();
2570  E = ExprRes.get();
2571  if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2572  return StmtError();
2573  }
2574 
2575  ExprResult ExprRes = ActOnFinishFullExpr(E);
2576  if (ExprRes.isInvalid())
2577  return StmtError();
2578  E = ExprRes.get();
2579 
2580  getCurFunction()->setHasIndirectGoto();
2581 
2582  return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2583 }
2584 
2586  const Scope &DestScope) {
2587  if (!S.CurrentSEHFinally.empty() &&
2588  DestScope.Contains(*S.CurrentSEHFinally.back())) {
2589  S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2590  }
2591 }
2592 
2593 StmtResult
2595  Scope *S = CurScope->getContinueParent();
2596  if (!S) {
2597  // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2598  return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2599  }
2600  CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2601 
2602  return new (Context) ContinueStmt(ContinueLoc);
2603 }
2604 
2605 StmtResult
2607  Scope *S = CurScope->getBreakParent();
2608  if (!S) {
2609  // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2610  return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2611  }
2612  if (S->isOpenMPLoopScope())
2613  return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2614  << "break");
2615  CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2616 
2617  return new (Context) BreakStmt(BreakLoc);
2618 }
2619 
2620 /// \brief Determine whether the given expression is a candidate for
2621 /// copy elision in either a return statement or a throw expression.
2622 ///
2623 /// \param ReturnType If we're determining the copy elision candidate for
2624 /// a return statement, this is the return type of the function. If we're
2625 /// determining the copy elision candidate for a throw expression, this will
2626 /// be a NULL type.
2627 ///
2628 /// \param E The expression being returned from the function or block, or
2629 /// being thrown.
2630 ///
2631 /// \param AllowFunctionParameter Whether we allow function parameters to
2632 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2633 /// we re-use this logic to determine whether we should try to move as part of
2634 /// a return or throw (which does allow function parameters).
2635 ///
2636 /// \returns The NRVO candidate variable, if the return statement may use the
2637 /// NRVO, or NULL if there is no such candidate.
2639  Expr *E,
2640  bool AllowFunctionParameter) {
2641  if (!getLangOpts().CPlusPlus)
2642  return nullptr;
2643 
2644  // - in a return statement in a function [where] ...
2645  // ... the expression is the name of a non-volatile automatic object ...
2646  DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2647  if (!DR || DR->refersToEnclosingVariableOrCapture())
2648  return nullptr;
2649  VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2650  if (!VD)
2651  return nullptr;
2652 
2653  if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2654  return VD;
2655  return nullptr;
2656 }
2657 
2658 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2659  bool AllowFunctionParameter) {
2660  QualType VDType = VD->getType();
2661  // - in a return statement in a function with ...
2662  // ... a class return type ...
2663  if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2664  if (!ReturnType->isRecordType())
2665  return false;
2666  // ... the same cv-unqualified type as the function return type ...
2667  if (!VDType->isDependentType() &&
2668  !Context.hasSameUnqualifiedType(ReturnType, VDType))
2669  return false;
2670  }
2671 
2672  // ...object (other than a function or catch-clause parameter)...
2673  if (VD->getKind() != Decl::Var &&
2674  !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2675  return false;
2676  if (VD->isExceptionVariable()) return false;
2677 
2678  // ...automatic...
2679  if (!VD->hasLocalStorage()) return false;
2680 
2681  // ...non-volatile...
2682  if (VD->getType().isVolatileQualified()) return false;
2683 
2684  // __block variables can't be allocated in a way that permits NRVO.
2685  if (VD->hasAttr<BlocksAttr>()) return false;
2686 
2687  // Variables with higher required alignment than their type's ABI
2688  // alignment cannot use NRVO.
2689  if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2691  return false;
2692 
2693  return true;
2694 }
2695 
2696 /// \brief Perform the initialization of a potentially-movable value, which
2697 /// is the result of return value.
2698 ///
2699 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2700 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2701 /// then falls back to treating them as lvalues if that failed.
2702 ExprResult
2704  const VarDecl *NRVOCandidate,
2705  QualType ResultType,
2706  Expr *Value,
2707  bool AllowNRVO) {
2708  // C++0x [class.copy]p33:
2709  // When the criteria for elision of a copy operation are met or would
2710  // be met save for the fact that the source object is a function
2711  // parameter, and the object to be copied is designated by an lvalue,
2712  // overload resolution to select the constructor for the copy is first
2713  // performed as if the object were designated by an rvalue.
2714  ExprResult Res = ExprError();
2715  if (AllowNRVO &&
2716  (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2718  Value->getType(), CK_NoOp, Value, VK_XValue);
2719 
2720  Expr *InitExpr = &AsRvalue;
2722  = InitializationKind::CreateCopy(Value->getLocStart(),
2723  Value->getLocStart());
2724  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2725 
2726  // [...] If overload resolution fails, or if the type of the first
2727  // parameter of the selected constructor is not an rvalue reference
2728  // to the object's type (possibly cv-qualified), overload resolution
2729  // is performed again, considering the object as an lvalue.
2730  if (Seq) {
2731  for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2732  StepEnd = Seq.step_end();
2733  Step != StepEnd; ++Step) {
2735  continue;
2736 
2737  CXXConstructorDecl *Constructor
2738  = cast<CXXConstructorDecl>(Step->Function.Function);
2739 
2740  const RValueReferenceType *RRefType
2741  = Constructor->getParamDecl(0)->getType()
2743 
2744  // If we don't meet the criteria, break out now.
2745  if (!RRefType ||
2746  !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2747  Context.getTypeDeclType(Constructor->getParent())))
2748  break;
2749 
2750  // Promote "AsRvalue" to the heap, since we now need this
2751  // expression node to persist.
2752  Value = ImplicitCastExpr::Create(Context, Value->getType(),
2753  CK_NoOp, Value, nullptr, VK_XValue);
2754 
2755  // Complete type-checking the initialization of the return type
2756  // using the constructor we found.
2757  Res = Seq.Perform(*this, Entity, Kind, Value);
2758  }
2759  }
2760  }
2761 
2762  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2763  // above, or overload resolution failed. Either way, we need to try
2764  // (again) now with the return value expression as written.
2765  if (Res.isInvalid())
2766  Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2767 
2768  return Res;
2769 }
2770 
2771 /// \brief Determine whether the declared return type of the specified function
2772 /// contains 'auto'.
2774  const FunctionProtoType *FPT =
2776  return FPT->getReturnType()->isUndeducedType();
2777 }
2778 
2779 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2780 /// for capturing scopes.
2781 ///
2782 StmtResult
2784  // If this is the first return we've seen, infer the return type.
2785  // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2786  CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2787  QualType FnRetType = CurCap->ReturnType;
2788  LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2789 
2790  if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2791  // In C++1y, the return type may involve 'auto'.
2792  // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2793  FunctionDecl *FD = CurLambda->CallOperator;
2794  if (CurCap->ReturnType.isNull())
2795  CurCap->ReturnType = FD->getReturnType();
2796 
2797  AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2798  assert(AT && "lost auto type from lambda return type");
2799  if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2800  FD->setInvalidDecl();
2801  return StmtError();
2802  }
2803  CurCap->ReturnType = FnRetType = FD->getReturnType();
2804  } else if (CurCap->HasImplicitReturnType) {
2805  // For blocks/lambdas with implicit return types, we check each return
2806  // statement individually, and deduce the common return type when the block
2807  // or lambda is completed.
2808  // FIXME: Fold this into the 'auto' codepath above.
2809  if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2810  ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2811  if (Result.isInvalid())
2812  return StmtError();
2813  RetValExp = Result.get();
2814 
2815  // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2816  // when deducing a return type for a lambda-expression (or by extension
2817  // for a block). These rules differ from the stated C++11 rules only in
2818  // that they remove top-level cv-qualifiers.
2819  if (!CurContext->isDependentContext())
2820  FnRetType = RetValExp->getType().getUnqualifiedType();
2821  else
2822  FnRetType = CurCap->ReturnType = Context.DependentTy;
2823  } else {
2824  if (RetValExp) {
2825  // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2826  // initializer list, because it is not an expression (even
2827  // though we represent it as one). We still deduce 'void'.
2828  Diag(ReturnLoc, diag::err_lambda_return_init_list)
2829  << RetValExp->getSourceRange();
2830  }
2831 
2832  FnRetType = Context.VoidTy;
2833  }
2834 
2835  // Although we'll properly infer the type of the block once it's completed,
2836  // make sure we provide a return type now for better error recovery.
2837  if (CurCap->ReturnType.isNull())
2838  CurCap->ReturnType = FnRetType;
2839  }
2840  assert(!FnRetType.isNull());
2841 
2842  if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2843  if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2844  Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2845  return StmtError();
2846  }
2847  } else if (CapturedRegionScopeInfo *CurRegion =
2848  dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2849  Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2850  return StmtError();
2851  } else {
2852  assert(CurLambda && "unknown kind of captured scope");
2853  if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2854  ->getNoReturnAttr()) {
2855  Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2856  return StmtError();
2857  }
2858  }
2859 
2860  // Otherwise, verify that this result type matches the previous one. We are
2861  // pickier with blocks than for normal functions because we don't have GCC
2862  // compatibility to worry about here.
2863  const VarDecl *NRVOCandidate = nullptr;
2864  if (FnRetType->isDependentType()) {
2865  // Delay processing for now. TODO: there are lots of dependent
2866  // types we can conclusively prove aren't void.
2867  } else if (FnRetType->isVoidType()) {
2868  if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2869  !(getLangOpts().CPlusPlus &&
2870  (RetValExp->isTypeDependent() ||
2871  RetValExp->getType()->isVoidType()))) {
2872  if (!getLangOpts().CPlusPlus &&
2873  RetValExp->getType()->isVoidType())
2874  Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2875  else {
2876  Diag(ReturnLoc, diag::err_return_block_has_expr);
2877  RetValExp = nullptr;
2878  }
2879  }
2880  } else if (!RetValExp) {
2881  return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2882  } else if (!RetValExp->isTypeDependent()) {
2883  // we have a non-void block with an expression, continue checking
2884 
2885  // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2886  // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2887  // function return.
2888 
2889  // In C++ the return statement is handled via a copy initialization.
2890  // the C version of which boils down to CheckSingleAssignmentConstraints.
2891  NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2893  FnRetType,
2894  NRVOCandidate != nullptr);
2895  ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2896  FnRetType, RetValExp);
2897  if (Res.isInvalid()) {
2898  // FIXME: Cleanup temporaries here, anyway?
2899  return StmtError();
2900  }
2901  RetValExp = Res.get();
2902  CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
2903  } else {
2904  NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2905  }
2906 
2907  if (RetValExp) {
2908  ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2909  if (ER.isInvalid())
2910  return StmtError();
2911  RetValExp = ER.get();
2912  }
2913  ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2914  NRVOCandidate);
2915 
2916  // If we need to check for the named return value optimization,
2917  // or if we need to infer the return type,
2918  // save the return statement in our scope for later processing.
2919  if (CurCap->HasImplicitReturnType || NRVOCandidate)
2920  FunctionScopes.back()->Returns.push_back(Result);
2921 
2922  return Result;
2923 }
2924 
2925 namespace {
2926 /// \brief Marks all typedefs in all local classes in a type referenced.
2927 ///
2928 /// In a function like
2929 /// auto f() {
2930 /// struct S { typedef int a; };
2931 /// return S();
2932 /// }
2933 ///
2934 /// the local type escapes and could be referenced in some TUs but not in
2935 /// others. Pretend that all local typedefs are always referenced, to not warn
2936 /// on this. This isn't necessary if f has internal linkage, or the typedef
2937 /// is private.
2938 class LocalTypedefNameReferencer
2939  : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2940 public:
2941  LocalTypedefNameReferencer(Sema &S) : S(S) {}
2942  bool VisitRecordType(const RecordType *RT);
2943 private:
2944  Sema &S;
2945 };
2946 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2947  auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2948  if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2949  R->isDependentType())
2950  return true;
2951  for (auto *TmpD : R->decls())
2952  if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2953  if (T->getAccess() != AS_private || R->hasFriends())
2954  S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2955  return true;
2956 }
2957 }
2958 
2961  while (auto ATL = TL.getAs<AttributedTypeLoc>())
2962  TL = ATL.getModifiedLoc().IgnoreParens();
2963  return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
2964 }
2965 
2966 /// Deduce the return type for a function from a returned expression, per
2967 /// C++1y [dcl.spec.auto]p6.
2969  SourceLocation ReturnLoc,
2970  Expr *&RetExpr,
2971  AutoType *AT) {
2972  TypeLoc OrigResultType = getReturnTypeLoc(FD);
2973  QualType Deduced;
2974 
2975  if (RetExpr && isa<InitListExpr>(RetExpr)) {
2976  // If the deduction is for a return statement and the initializer is
2977  // a braced-init-list, the program is ill-formed.
2978  Diag(RetExpr->getExprLoc(),
2979  getCurLambda() ? diag::err_lambda_return_init_list
2980  : diag::err_auto_fn_return_init_list)
2981  << RetExpr->getSourceRange();
2982  return true;
2983  }
2984 
2985  if (FD->isDependentContext()) {
2986  // C++1y [dcl.spec.auto]p12:
2987  // Return type deduction [...] occurs when the definition is
2988  // instantiated even if the function body contains a return
2989  // statement with a non-type-dependent operand.
2990  assert(AT->isDeduced() && "should have deduced to dependent type");
2991  return false;
2992  } else if (RetExpr) {
2993  // If the deduction is for a return statement and the initializer is
2994  // a braced-init-list, the program is ill-formed.
2995  if (isa<InitListExpr>(RetExpr)) {
2996  Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2997  return true;
2998  }
2999 
3000  // Otherwise, [...] deduce a value for U using the rules of template
3001  // argument deduction.
3002  DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3003 
3004  if (DAR == DAR_Failed && !FD->isInvalidDecl())
3005  Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3006  << OrigResultType.getType() << RetExpr->getType();
3007 
3008  if (DAR != DAR_Succeeded)
3009  return true;
3010 
3011  // If a local type is part of the returned type, mark its fields as
3012  // referenced.
3013  LocalTypedefNameReferencer Referencer(*this);
3014  Referencer.TraverseType(RetExpr->getType());
3015  } else {
3016  // In the case of a return with no operand, the initializer is considered
3017  // to be void().
3018  //
3019  // Deduction here can only succeed if the return type is exactly 'cv auto'
3020  // or 'decltype(auto)', so just check for that case directly.
3021  if (!OrigResultType.getType()->getAs<AutoType>()) {
3022  Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3023  << OrigResultType.getType();
3024  return true;
3025  }
3026  // We always deduce U = void in this case.
3027  Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3028  if (Deduced.isNull())
3029  return true;
3030  }
3031 
3032  // If a function with a declared return type that contains a placeholder type
3033  // has multiple return statements, the return type is deduced for each return
3034  // statement. [...] if the type deduced is not the same in each deduction,
3035  // the program is ill-formed.
3036  if (AT->isDeduced() && !FD->isInvalidDecl()) {
3037  AutoType *NewAT = Deduced->getContainedAutoType();
3038  if (!FD->isDependentContext() &&
3039  !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
3040  const LambdaScopeInfo *LambdaSI = getCurLambda();
3041  if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3042  Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3043  << NewAT->getDeducedType() << AT->getDeducedType()
3044  << true /*IsLambda*/;
3045  } else {
3046  Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3047  << (AT->isDecltypeAuto() ? 1 : 0)
3048  << NewAT->getDeducedType() << AT->getDeducedType();
3049  }
3050  return true;
3051  }
3052  } else if (!FD->isInvalidDecl()) {
3053  // Update all declarations of the function to have the deduced return type.
3055  }
3056 
3057  return false;
3058 }
3059 
3060 StmtResult
3062  Scope *CurScope) {
3063  StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3064  if (R.isInvalid()) {
3065  return R;
3066  }
3067 
3068  if (VarDecl *VD =
3069  const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3070  CurScope->addNRVOCandidate(VD);
3071  } else {
3072  CurScope->setNoNRVO();
3073  }
3074 
3075  CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3076 
3077  return R;
3078 }
3079 
3081  // Check for unexpanded parameter packs.
3082  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3083  return StmtError();
3084 
3085  if (isa<CapturingScopeInfo>(getCurFunction()))
3086  return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3087 
3088  QualType FnRetType;
3089  QualType RelatedRetType;
3090  const AttrVec *Attrs = nullptr;
3091  bool isObjCMethod = false;
3092 
3093  if (const FunctionDecl *FD = getCurFunctionDecl()) {
3094  FnRetType = FD->getReturnType();
3095  if (FD->hasAttrs())
3096  Attrs = &FD->getAttrs();
3097  if (FD->isNoReturn())
3098  Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3099  << FD->getDeclName();
3100  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3101  FnRetType = MD->getReturnType();
3102  isObjCMethod = true;
3103  if (MD->hasAttrs())
3104  Attrs = &MD->getAttrs();
3105  if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3106  // In the implementation of a method with a related return type, the
3107  // type used to type-check the validity of return statements within the
3108  // method body is a pointer to the type of the class being implemented.
3109  RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3110  RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3111  }
3112  } else // If we don't have a function/method context, bail.
3113  return StmtError();
3114 
3115  // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3116  // deduction.
3117  if (getLangOpts().CPlusPlus14) {
3118  if (AutoType *AT = FnRetType->getContainedAutoType()) {
3119  FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3120  if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3121  FD->setInvalidDecl();
3122  return StmtError();
3123  } else {
3124  FnRetType = FD->getReturnType();
3125  }
3126  }
3127  }
3128 
3129  bool HasDependentReturnType = FnRetType->isDependentType();
3130 
3131  ReturnStmt *Result = nullptr;
3132  if (FnRetType->isVoidType()) {
3133  if (RetValExp) {
3134  if (isa<InitListExpr>(RetValExp)) {
3135  // We simply never allow init lists as the return value of void
3136  // functions. This is compatible because this was never allowed before,
3137  // so there's no legacy code to deal with.
3138  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3139  int FunctionKind = 0;
3140  if (isa<ObjCMethodDecl>(CurDecl))
3141  FunctionKind = 1;
3142  else if (isa<CXXConstructorDecl>(CurDecl))
3143  FunctionKind = 2;
3144  else if (isa<CXXDestructorDecl>(CurDecl))
3145  FunctionKind = 3;
3146 
3147  Diag(ReturnLoc, diag::err_return_init_list)
3148  << CurDecl->getDeclName() << FunctionKind
3149  << RetValExp->getSourceRange();
3150 
3151  // Drop the expression.
3152  RetValExp = nullptr;
3153  } else if (!RetValExp->isTypeDependent()) {
3154  // C99 6.8.6.4p1 (ext_ since GCC warns)
3155  unsigned D = diag::ext_return_has_expr;
3156  if (RetValExp->getType()->isVoidType()) {
3157  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3158  if (isa<CXXConstructorDecl>(CurDecl) ||
3159  isa<CXXDestructorDecl>(CurDecl))
3160  D = diag::err_ctor_dtor_returns_void;
3161  else
3162  D = diag::ext_return_has_void_expr;
3163  }
3164  else {
3165  ExprResult Result = RetValExp;
3166  Result = IgnoredValueConversions(Result.get());
3167  if (Result.isInvalid())
3168  return StmtError();
3169  RetValExp = Result.get();
3170  RetValExp = ImpCastExprToType(RetValExp,
3171  Context.VoidTy, CK_ToVoid).get();
3172  }
3173  // return of void in constructor/destructor is illegal in C++.
3174  if (D == diag::err_ctor_dtor_returns_void) {
3175  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3176  Diag(ReturnLoc, D)
3177  << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3178  << RetValExp->getSourceRange();
3179  }
3180  // return (some void expression); is legal in C++.
3181  else if (D != diag::ext_return_has_void_expr ||
3182  !getLangOpts().CPlusPlus) {
3183  NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3184 
3185  int FunctionKind = 0;
3186  if (isa<ObjCMethodDecl>(CurDecl))
3187  FunctionKind = 1;
3188  else if (isa<CXXConstructorDecl>(CurDecl))
3189  FunctionKind = 2;
3190  else if (isa<CXXDestructorDecl>(CurDecl))
3191  FunctionKind = 3;
3192 
3193  Diag(ReturnLoc, D)
3194  << CurDecl->getDeclName() << FunctionKind
3195  << RetValExp->getSourceRange();
3196  }
3197  }
3198 
3199  if (RetValExp) {
3200  ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3201  if (ER.isInvalid())
3202  return StmtError();
3203  RetValExp = ER.get();
3204  }
3205  }
3206 
3207  Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3208  } else if (!RetValExp && !HasDependentReturnType) {
3209  FunctionDecl *FD = getCurFunctionDecl();
3210 
3211  unsigned DiagID;
3212  if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3213  // C++11 [stmt.return]p2
3214  DiagID = diag::err_constexpr_return_missing_expr;
3215  FD->setInvalidDecl();
3216  } else if (getLangOpts().C99) {
3217  // C99 6.8.6.4p1 (ext_ since GCC warns)
3218  DiagID = diag::ext_return_missing_expr;
3219  } else {
3220  // C90 6.6.6.4p4
3221  DiagID = diag::warn_return_missing_expr;
3222  }
3223 
3224  if (FD)
3225  Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3226  else
3227  Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3228 
3229  Result = new (Context) ReturnStmt(ReturnLoc);
3230  } else {
3231  assert(RetValExp || HasDependentReturnType);
3232  const VarDecl *NRVOCandidate = nullptr;
3233 
3234  QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3235 
3236  // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3237  // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3238  // function return.
3239 
3240  // In C++ the return statement is handled via a copy initialization,
3241  // the C version of which boils down to CheckSingleAssignmentConstraints.
3242  if (RetValExp)
3243  NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3244  if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3245  // we have a non-void function with an expression, continue checking
3247  RetType,
3248  NRVOCandidate != nullptr);
3249  ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3250  RetType, RetValExp);
3251  if (Res.isInvalid()) {
3252  // FIXME: Clean up temporaries here anyway?
3253  return StmtError();
3254  }
3255  RetValExp = Res.getAs<Expr>();
3256 
3257  // If we have a related result type, we need to implicitly
3258  // convert back to the formal result type. We can't pretend to
3259  // initialize the result again --- we might end double-retaining
3260  // --- so instead we initialize a notional temporary.
3261  if (!RelatedRetType.isNull()) {
3262  Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3263  FnRetType);
3264  Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3265  if (Res.isInvalid()) {
3266  // FIXME: Clean up temporaries here anyway?
3267  return StmtError();
3268  }
3269  RetValExp = Res.getAs<Expr>();
3270  }
3271 
3272  CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3273  getCurFunctionDecl());
3274  }
3275 
3276  if (RetValExp) {
3277  ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3278  if (ER.isInvalid())
3279  return StmtError();
3280  RetValExp = ER.get();
3281  }
3282  Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3283  }
3284 
3285  // If we need to check for the named return value optimization, save the
3286  // return statement in our scope for later processing.
3287  if (Result->getNRVOCandidate())
3288  FunctionScopes.back()->Returns.push_back(Result);
3289 
3290  return Result;
3291 }
3292 
3293 StmtResult
3295  SourceLocation RParen, Decl *Parm,
3296  Stmt *Body) {
3297  VarDecl *Var = cast_or_null<VarDecl>(Parm);
3298  if (Var && Var->isInvalidDecl())
3299  return StmtError();
3300 
3301  return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3302 }
3303 
3304 StmtResult
3306  return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3307 }
3308 
3309 StmtResult
3311  MultiStmtArg CatchStmts, Stmt *Finally) {
3312  if (!getLangOpts().ObjCExceptions)
3313  Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3314 
3315  getCurFunction()->setHasBranchProtectedScope();
3316  unsigned NumCatchStmts = CatchStmts.size();
3317  return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3318  NumCatchStmts, Finally);
3319 }
3320 
3322  if (Throw) {
3323  ExprResult Result = DefaultLvalueConversion(Throw);
3324  if (Result.isInvalid())
3325  return StmtError();
3326 
3327  Result = ActOnFinishFullExpr(Result.get());
3328  if (Result.isInvalid())
3329  return StmtError();
3330  Throw = Result.get();
3331 
3332  QualType ThrowType = Throw->getType();
3333  // Make sure the expression type is an ObjC pointer or "void *".
3334  if (!ThrowType->isDependentType() &&
3335  !ThrowType->isObjCObjectPointerType()) {
3336  const PointerType *PT = ThrowType->getAs<PointerType>();
3337  if (!PT || !PT->getPointeeType()->isVoidType())
3338  return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3339  << Throw->getType() << Throw->getSourceRange());
3340  }
3341  }
3342 
3343  return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3344 }
3345 
3346 StmtResult
3348  Scope *CurScope) {
3349  if (!getLangOpts().ObjCExceptions)
3350  Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3351 
3352  if (!Throw) {
3353  // @throw without an expression designates a rethrow (which must occur
3354  // in the context of an @catch clause).
3355  Scope *AtCatchParent = CurScope;
3356  while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3357  AtCatchParent = AtCatchParent->getParent();
3358  if (!AtCatchParent)
3359  return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3360  }
3361  return BuildObjCAtThrowStmt(AtLoc, Throw);
3362 }
3363 
3364 ExprResult
3366  ExprResult result = DefaultLvalueConversion(operand);
3367  if (result.isInvalid())
3368  return ExprError();
3369  operand = result.get();
3370 
3371  // Make sure the expression type is an ObjC pointer or "void *".
3372  QualType type = operand->getType();
3373  if (!type->isDependentType() &&
3374  !type->isObjCObjectPointerType()) {
3375  const PointerType *pointerType = type->getAs<PointerType>();
3376  if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3377  if (getLangOpts().CPlusPlus) {
3378  if (RequireCompleteType(atLoc, type,
3379  diag::err_incomplete_receiver_type))
3380  return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3381  << type << operand->getSourceRange();
3382 
3383  ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3384  if (!result.isUsable())
3385  return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3386  << type << operand->getSourceRange();
3387 
3388  operand = result.get();
3389  } else {
3390  return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3391  << type << operand->getSourceRange();
3392  }
3393  }
3394  }
3395 
3396  // The operand to @synchronized is a full-expression.
3397  return ActOnFinishFullExpr(operand);
3398 }
3399 
3400 StmtResult
3402  Stmt *SyncBody) {
3403  // We can't jump into or indirect-jump out of a @synchronized block.
3404  getCurFunction()->setHasBranchProtectedScope();
3405  return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3406 }
3407 
3408 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3409 /// and creates a proper catch handler from them.
3410 StmtResult
3412  Stmt *HandlerBlock) {
3413  // There's nothing to test that ActOnExceptionDecl didn't already test.
3414  return new (Context)
3415  CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3416 }
3417 
3418 StmtResult
3420  getCurFunction()->setHasBranchProtectedScope();
3421  return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3422 }
3423 
3424 namespace {
3425 class CatchHandlerType {
3426  QualType QT;
3427  unsigned IsPointer : 1;
3428 
3429  // This is a special constructor to be used only with DenseMapInfo's
3430  // getEmptyKey() and getTombstoneKey() functions.
3431  friend struct llvm::DenseMapInfo<CatchHandlerType>;
3432  enum Unique { ForDenseMap };
3433  CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3434 
3435 public:
3436  /// Used when creating a CatchHandlerType from a handler type; will determine
3437  /// whether the type is a pointer or reference and will strip off the top
3438  /// level pointer and cv-qualifiers.
3439  CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3440  if (QT->isPointerType())
3441  IsPointer = true;
3442 
3443  if (IsPointer || QT->isReferenceType())
3444  QT = QT->getPointeeType();
3445  QT = QT.getUnqualifiedType();
3446  }
3447 
3448  /// Used when creating a CatchHandlerType from a base class type; pretends the
3449  /// type passed in had the pointer qualifier, does not need to get an
3450  /// unqualified type.
3451  CatchHandlerType(QualType QT, bool IsPointer)
3452  : QT(QT), IsPointer(IsPointer) {}
3453 
3454  QualType underlying() const { return QT; }
3455  bool isPointer() const { return IsPointer; }
3456 
3457  friend bool operator==(const CatchHandlerType &LHS,
3458  const CatchHandlerType &RHS) {
3459  // If the pointer qualification does not match, we can return early.
3460  if (LHS.IsPointer != RHS.IsPointer)
3461  return false;
3462  // Otherwise, check the underlying type without cv-qualifiers.
3463  return LHS.QT == RHS.QT;
3464  }
3465 };
3466 } // namespace
3467 
3468 namespace llvm {
3469 template <> struct DenseMapInfo<CatchHandlerType> {
3470  static CatchHandlerType getEmptyKey() {
3471  return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3472  CatchHandlerType::ForDenseMap);
3473  }
3474 
3475  static CatchHandlerType getTombstoneKey() {
3476  return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3477  CatchHandlerType::ForDenseMap);
3478  }
3479 
3480  static unsigned getHashValue(const CatchHandlerType &Base) {
3481  return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3482  }
3483 
3484  static bool isEqual(const CatchHandlerType &LHS,
3485  const CatchHandlerType &RHS) {
3486  return LHS == RHS;
3487  }
3488 };
3489 
3490 // It's OK to treat CatchHandlerType as a POD type.
3491 template <> struct isPodLike<CatchHandlerType> {
3492  static const bool value = true;
3493 };
3494 }
3495 
3496 namespace {
3497 class CatchTypePublicBases {
3498  ASTContext &Ctx;
3499  const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3500  const bool CheckAgainstPointer;
3501 
3502  CXXCatchStmt *FoundHandler;
3503  CanQualType FoundHandlerType;
3504 
3505 public:
3506  CatchTypePublicBases(
3507  ASTContext &Ctx,
3508  const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3509  : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3510  FoundHandler(nullptr) {}
3511 
3512  CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3513  CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3514 
3515  static bool FindPublicBasesOfType(const CXXBaseSpecifier *S, CXXBasePath &,
3516  void *User) {
3517  auto &PBOT = *reinterpret_cast<CatchTypePublicBases *>(User);
3519  CatchHandlerType Check(S->getType(), PBOT.CheckAgainstPointer);
3520  auto M = PBOT.TypesToCheck;
3521  auto I = M.find(Check);
3522  if (I != M.end()) {
3523  PBOT.FoundHandler = I->second;
3524  PBOT.FoundHandlerType = PBOT.Ctx.getCanonicalType(S->getType());
3525  return true;
3526  }
3527  }
3528  return false;
3529  }
3530 };
3531 }
3532 
3533 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3534 /// handlers and creates a try statement from them.
3536  ArrayRef<Stmt *> Handlers) {
3537  // Don't report an error if 'try' is used in system headers.
3538  if (!getLangOpts().CXXExceptions &&
3539  !getSourceManager().isInSystemHeader(TryLoc))
3540  Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3541 
3542  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3543  Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3544 
3545  sema::FunctionScopeInfo *FSI = getCurFunction();
3546 
3547  // C++ try is incompatible with SEH __try.
3548  if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
3549  Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3550  Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
3551  }
3552 
3553  const unsigned NumHandlers = Handlers.size();
3554  assert(!Handlers.empty() &&
3555  "The parser shouldn't call this if there are no handlers.");
3556 
3557  llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
3558  for (unsigned i = 0; i < NumHandlers; ++i) {
3559  CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
3560 
3561  // Diagnose when the handler is a catch-all handler, but it isn't the last
3562  // handler for the try block. [except.handle]p5. Also, skip exception
3563  // declarations that are invalid, since we can't usefully report on them.
3564  if (!H->getExceptionDecl()) {
3565  if (i < NumHandlers - 1)
3566  return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
3567  continue;
3568  } else if (H->getExceptionDecl()->isInvalidDecl())
3569  continue;
3570 
3571  // Walk the type hierarchy to diagnose when this type has already been
3572  // handled (duplication), or cannot be handled (derivation inversion). We
3573  // ignore top-level cv-qualifiers, per [except.handle]p3
3574  CatchHandlerType HandlerCHT =
3576 
3577  // We can ignore whether the type is a reference or a pointer; we need the
3578  // underlying declaration type in order to get at the underlying record
3579  // decl, if there is one.
3580  QualType Underlying = HandlerCHT.underlying();
3581  if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3582  if (!RD->hasDefinition())
3583  continue;
3584  // Check that none of the public, unambiguous base classes are in the
3585  // map ([except.handle]p1). Give the base classes the same pointer
3586  // qualification as the original type we are basing off of. This allows
3587  // comparison against the handler type using the same top-level pointer
3588  // as the original type.
3589  CXXBasePaths Paths;
3590  Paths.setOrigin(RD);
3591  CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3592  if (RD->lookupInBases(CatchTypePublicBases::FindPublicBasesOfType, &CTPB,
3593  Paths)) {
3594  const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3595  if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3597  diag::warn_exception_caught_by_earlier_handler)
3598  << H->getCaughtType();
3600  diag::note_previous_exception_handler)
3601  << Problem->getCaughtType();
3602  }
3603  }
3604  }
3605 
3606  // Add the type the list of ones we have handled; diagnose if we've already
3607  // handled it.
3608  auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3609  if (!R.second) {
3610  const CXXCatchStmt *Problem = R.first->second;
3612  diag::warn_exception_caught_by_earlier_handler)
3613  << H->getCaughtType();
3615  diag::note_previous_exception_handler)
3616  << Problem->getCaughtType();
3617  }
3618  }
3619 
3620  FSI->setHasCXXTry(TryLoc);
3621 
3622  return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3623 }
3624 
3626  Stmt *TryBlock, Stmt *Handler) {
3627  assert(TryBlock && Handler);
3628 
3629  sema::FunctionScopeInfo *FSI = getCurFunction();
3630 
3631  // SEH __try is incompatible with C++ try. Borland appears to support this,
3632  // however.
3633  if (!getLangOpts().Borland) {
3634  if (FSI->FirstCXXTryLoc.isValid()) {
3635  Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3636  Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3637  }
3638  }
3639 
3640  FSI->setHasSEHTry(TryLoc);
3641 
3642  // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3643  // track if they use SEH.
3644  DeclContext *DC = CurContext;
3645  while (DC && !DC->isFunctionOrMethod())
3646  DC = DC->getParent();
3647  FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3648  if (FD)
3649  FD->setUsesSEHTry(true);
3650  else
3651  Diag(TryLoc, diag::err_seh_try_outside_functions);
3652 
3653  // Reject __try on unsupported targets.
3655  Diag(TryLoc, diag::err_seh_try_unsupported);
3656 
3657  return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
3658 }
3659 
3660 StmtResult
3662  Expr *FilterExpr,
3663  Stmt *Block) {
3664  assert(FilterExpr && Block);
3665 
3666  if(!FilterExpr->getType()->isIntegerType()) {
3667  return StmtError(Diag(FilterExpr->getExprLoc(),
3668  diag::err_filter_expression_integral)
3669  << FilterExpr->getType());
3670  }
3671 
3672  return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3673 }
3674 
3676  CurrentSEHFinally.push_back(CurScope);
3677 }
3678 
3680  CurrentSEHFinally.pop_back();
3681 }
3682 
3684  assert(Block);
3685  CurrentSEHFinally.pop_back();
3686  return SEHFinallyStmt::Create(Context, Loc, Block);
3687 }
3688 
3689 StmtResult
3691  Scope *SEHTryParent = CurScope;
3692  while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3693  SEHTryParent = SEHTryParent->getParent();
3694  if (!SEHTryParent)
3695  return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3696  CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
3697 
3698  return new (Context) SEHLeaveStmt(Loc);
3699 }
3700 
3702  bool IsIfExists,
3703  NestedNameSpecifierLoc QualifierLoc,
3704  DeclarationNameInfo NameInfo,
3705  Stmt *Nested)
3706 {
3707  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3708  QualifierLoc, NameInfo,
3709  cast<CompoundStmt>(Nested));
3710 }
3711 
3712 
3714  bool IsIfExists,
3715  CXXScopeSpec &SS,
3716  UnqualifiedId &Name,
3717  Stmt *Nested) {
3718  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3720  GetNameFromUnqualifiedId(Name),
3721  Nested);
3722 }
3723 
3724 RecordDecl*
3726  unsigned NumParams) {
3727  DeclContext *DC = CurContext;
3728  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3729  DC = DC->getParent();
3730 
3731  RecordDecl *RD = nullptr;
3732  if (getLangOpts().CPlusPlus)
3733  RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3734  /*Id=*/nullptr);
3735  else
3736  RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3737 
3738  RD->setCapturedRecord();
3739  DC->addDecl(RD);
3740  RD->setImplicit();
3741  RD->startDefinition();
3742 
3743  assert(NumParams > 0 && "CapturedStmt requires context parameter");
3744  CD = CapturedDecl::Create(Context, CurContext, NumParams);
3745  DC->addDecl(CD);
3746  return RD;
3747 }
3748 
3751  SmallVectorImpl<Expr *> &CaptureInits,
3753 
3755  for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3756 
3757  if (Cap->isThisCapture()) {
3758  Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3760  CaptureInits.push_back(Cap->getInitExpr());
3761  continue;
3762  } else if (Cap->isVLATypeCapture()) {
3763  Captures.push_back(
3764  CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3765  CaptureInits.push_back(nullptr);
3766  continue;
3767  }
3768 
3769  assert(Cap->isReferenceCapture() &&
3770  "non-reference capture not yet implemented");
3771 
3772  Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3774  Cap->getVariable()));
3775  CaptureInits.push_back(Cap->getInitExpr());
3776  }
3777 }
3778 
3781  unsigned NumParams) {
3782  CapturedDecl *CD = nullptr;
3783  RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3784 
3785  // Build the context parameter
3787  IdentifierInfo *ParamName = &Context.Idents.get("__context");
3789  ImplicitParamDecl *Param
3790  = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3791  DC->addDecl(Param);
3792 
3793  CD->setContextParam(0, Param);
3794 
3795  // Enter the capturing scope for this captured region.
3796  PushCapturedRegionScope(CurScope, CD, RD, Kind);
3797 
3798  if (CurScope)
3799  PushDeclContext(CurScope, CD);
3800  else
3801  CurContext = CD;
3802 
3803  PushExpressionEvaluationContext(PotentiallyEvaluated);
3804 }
3805 
3809  CapturedDecl *CD = nullptr;
3810  RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3811 
3812  // Build the context parameter
3814  bool ContextIsFound = false;
3815  unsigned ParamNum = 0;
3816  for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3817  E = Params.end();
3818  I != E; ++I, ++ParamNum) {
3819  if (I->second.isNull()) {
3820  assert(!ContextIsFound &&
3821  "null type has been found already for '__context' parameter");
3822  IdentifierInfo *ParamName = &Context.Idents.get("__context");
3824  ImplicitParamDecl *Param
3825  = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3826  DC->addDecl(Param);
3827  CD->setContextParam(ParamNum, Param);
3828  ContextIsFound = true;
3829  } else {
3830  IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3831  ImplicitParamDecl *Param
3832  = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3833  DC->addDecl(Param);
3834  CD->setParam(ParamNum, Param);
3835  }
3836  }
3837  assert(ContextIsFound && "no null type for '__context' parameter");
3838  if (!ContextIsFound) {
3839  // Add __context implicitly if it is not specified.
3840  IdentifierInfo *ParamName = &Context.Idents.get("__context");
3842  ImplicitParamDecl *Param =
3843  ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3844  DC->addDecl(Param);
3845  CD->setContextParam(ParamNum, Param);
3846  }
3847  // Enter the capturing scope for this captured region.
3848  PushCapturedRegionScope(CurScope, CD, RD, Kind);
3849 
3850  if (CurScope)
3851  PushDeclContext(CurScope, CD);
3852  else
3853  CurContext = CD;
3854 
3855  PushExpressionEvaluationContext(PotentiallyEvaluated);
3856 }
3857 
3859  DiscardCleanupsInEvaluationContext();
3860  PopExpressionEvaluationContext();
3861 
3862  CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3863  RecordDecl *Record = RSI->TheRecordDecl;
3864  Record->setInvalidDecl();
3865 
3866  SmallVector<Decl*, 4> Fields(Record->fields());
3867  ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3868  SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
3869 
3870  PopDeclContext();
3871  PopFunctionScopeInfo();
3872 }
3873 
3875  CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3876 
3878  SmallVector<Expr *, 4> CaptureInits;
3879  buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3880 
3881  CapturedDecl *CD = RSI->TheCapturedDecl;
3882  RecordDecl *RD = RSI->TheRecordDecl;
3883 
3884  CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3885  RSI->CapRegionKind, Captures,
3886  CaptureInits, CD, RD);
3887 
3888  CD->setBody(Res->getCapturedStmt());
3889  RD->completeDefinition();
3890 
3891  DiscardCleanupsInEvaluationContext();
3892  PopExpressionEvaluationContext();
3893 
3894  PopDeclContext();
3895  PopFunctionScopeInfo();
3896 
3897  return Res;
3898 }
unsigned getFlags() const
Definition: Scope.h:207
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:54
bool qual_empty() const
Definition: Type.h:4627
Defines the clang::ASTContext interface.
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:667
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:5035
CastKind getCastKind() const
Definition: Expr.h:2709
void setImplicit(bool I=true)
Definition: DeclBase.h:504
Stmt * body_back()
Definition: Stmt.h:589
SourceLocation getLocStart() const LLVM_READONLY
Definition: StmtCXX.h:192
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchers.h:1110
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
void setOrigin(CXXRecordDecl *Rec)
Smart pointer class that efficiently represents Objective-C method names.
EvaluatedExprVisitor - This class visits 'Expr *'s.
CanQualType VoidPtrTy
Definition: ASTContext.h:831
bool isInvalid() const
Definition: Ownership.h:159
bool isNull() const
Definition: DeclGroup.h:83
bool isMacroID() const
static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned)
Definition: SemaStmt.cpp:666
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams)
Definition: SemaStmt.cpp:3779
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
BeginEndFunction
Definition: Sema.h:2481
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:252
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock)
Definition: SemaStmt.cpp:3411
bool operator==(CanQual< T > x, CanQual< U > y)
static unsigned getHashValue(const CatchHandlerType &Base)
Definition: SemaStmt.cpp:3480
bool hasUnusedResultAttr() const
Returns true if this function or its return type has the warn_unused_result attribute. If the return type has the attribute and this function is a method of the return type's class, then false will be returned to avoid spurious warnings on member methods such as assignment operators.
Definition: Decl.cpp:2839
IdentifierInfo * getIdentifier() const
Definition: Decl.h:163
const LangOptions & getLangOpts() const
Definition: Sema.h:1019
const Scope * getFnParent() const
Definition: Scope.h:220
SmallVectorImpl< Step >::const_iterator step_iterator
unsigned getIntWidth(QualType T) const
StmtResult ActOnExprStmt(ExprResult Arg)
Definition: SemaStmt.cpp:43
const Scope * getParent() const
Definition: Scope.h:215
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:3787
void setParam(unsigned i, ImplicitParamDecl *P)
Definition: Decl.h:3652
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc)
Definition: SemaStmt.cpp:1750
ActionResult< Expr * > ExprResult
Definition: Ownership.h:252
Expr * get() const
Definition: Sema.h:3181
SmallVector< Scope *, 2 > CurrentSEHFinally
Stack of active SEH __finally scopes. Can be empty.
Definition: Sema.h:356
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
Definition: SemaStmt.cpp:2959
bool isRecordType() const
Definition: Type.h:5289
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition: SemaStmt.cpp:322
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1088
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition: Decl.cpp:2569
void setType(QualType t)
Definition: Expr.h:126
AssignConvertType
Definition: Sema.h:8140
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1572
Represents a C++11 auto or C++1y decltype(auto) type.
Definition: Type.h:3874
Represents an attribute applied to a statement.
Definition: Stmt.h:833
bool isEnumeralType() const
Definition: Type.h:5292
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, bool AllowFunctionParameters)
Definition: SemaStmt.cpp:2658
PtrTy get() const
Definition: Ownership.h:163
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
static CapturedStmt * Create(const ASTContext &Context, Stmt *S, CapturedRegionKind Kind, ArrayRef< Capture > Captures, ArrayRef< Expr * > CaptureInits, CapturedDecl *CD, RecordDecl *RD)
Definition: Stmt.cpp:1115
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:313
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:851
ForRangeStatus
Definition: Sema.h:2473
const Expr * getInit() const
Definition: Decl.h:1068
const ObjCObjectType * getObjectType() const
Definition: Type.h:4820
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1075
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body)
Definition: SemaStmt.cpp:3294
virtual void completeDefinition()
Definition: Decl.cpp:3638
bool isDecltypeAuto() const
Definition: Type.h:3890
A container of type source information.
Definition: Decl.h:60
Wrapper for void* pointer.
Definition: Ownership.h:45
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope)
Definition: SemaStmt.cpp:2594
bool isBlockPointerType() const
Definition: Type.h:5238
Scope * getContinueParent()
Definition: Scope.h:230
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
bool isInSystemMacro(SourceLocation loc)
Returns whether Loc is expanded from a macro in a system header.
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2147
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:3746
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:80
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen)
Definition: SemaStmt.cpp:1251
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally)
Definition: SemaStmt.cpp:3310
DiagnosticsEngine & Diags
Definition: Sema.h:297
ObjCLifetime getObjCLifetime() const
Definition: Type.h:287
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl)
Definition: SemaStmt.cpp:81
SourceLocation getLocStart() const LLVM_READONLY
Definition: StmtCXX.h:44
static bool ObjCEnumerationCollection(Expr *Collection)
Definition: SemaStmt.cpp:1911
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:822
static InitializedEntity InitializeResult(SourceLocation ReturnLoc, QualType Type, bool NRVO)
Create the initialization entity for the result of a function.
Defines the Objective-C statement AST node classes.
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body)
Definition: SemaStmt.cpp:2369
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
Definition: SemaExpr.cpp:10799
bool body_empty() const
Definition: Stmt.h:579
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1334
Defines the clang::Expr interface and subclasses for C++ expressions.
SourceLocation getDefaultLoc() const
Definition: Stmt.h:767
SourceLocation getLocation() const
Definition: Expr.h:1002
CapturedDecl * TheCapturedDecl
The CapturedDecl for this statement.
Definition: ScopeInfo.h:582
bool isVoidType() const
Definition: Type.h:5426
QualType withConst() const
Retrieves a version of this type with const applied. Note that this does not always yield a canonical...
static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val, unsigned UnpromotedWidth, bool UnpromotedSign)
Definition: SemaStmt.cpp:673
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
Expr * IgnoreImpCasts() LLVM_READONLY
Definition: Expr.h:2803
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse)
Perform marking for a reference to an arbitrary declaration. It marks the declaration referenced...
Definition: SemaExpr.cpp:13367
const internal::VariadicDynCastAllOfMatcher< Stmt, CaseStmt > caseStmt
Matches case statements inside switch statements.
Definition: ASTMatchers.h:1304
void DiagnoseUnusedExprResult(const Stmt *S)
Definition: SemaStmt.cpp:185
bool hasAttr() const
Definition: DeclBase.h:487
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:3591
VarDecl * getCopyElisionCandidate(QualType ReturnType, Expr *E, bool AllowFunctionParameters)
Determine whether the given expression is a candidate for copy elision in either a return statement o...
Definition: SemaStmt.cpp:2638
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3073
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
A C++ nested-name-specifier augmented with source location information.
bool isReferenceType() const
Definition: Type.h:5241
QualType getReturnType() const
Definition: Decl.h:1997
static bool CmpCaseVals(const std::pair< llvm::APSInt, CaseStmt * > &lhs, const std::pair< llvm::APSInt, CaseStmt * > &rhs)
Definition: SemaStmt.cpp:539
void setLocStart(SourceLocation L)
Definition: Decl.h:382
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection)
Definition: SemaStmt.cpp:1674
bool isSEHTryScope() const
Determine whether this scope is a SEH '__try' block.
Definition: Scope.h:424
StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, FullExprArg Second, Decl *SecondVar, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:1606
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchers.h:258
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3419
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition: Scope.h:433
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:1871
void setNoNRVO()
Definition: Scope.h:462
Expr * getSubExpr()
Definition: Expr.h:2713
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1114
void setSubStmt(Stmt *S)
Definition: Stmt.h:729
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:1896
Scope * getBreakParent()
Definition: Scope.h:240
IdentifierTable & Idents
Definition: ASTContext.h:439
SourceLocation FirstSEHTryLoc
First SEH '__try' statement in the current function.
Definition: ScopeInfo.h:131
void ActOnAbortSEHFinallyBlock()
Definition: SemaStmt.cpp:3679
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:95
Expr * getLHS() const
Definition: Expr.h:2964
Represents Objective-C's @catch statement.
Definition: StmtObjC.h:74
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested)
Definition: SemaStmt.cpp:3701
void setBody(Stmt *S)
Definition: Stmt.h:992
const VarDecl * getNRVOCandidate() const
Retrieve the variable that might be used for the named return value optimization. ...
Definition: Stmt.h:1378
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:170
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef< Stmt * > Handlers)
Definition: SemaStmt.cpp:3535
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:869
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt)
Represents the results of name lookup.
Definition: Lookup.h:30
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:518
Decl * getSingleDecl()
Definition: DeclGroup.h:87
This is a scope that corresponds to a switch statement.
Definition: Scope.h:96
SmallVector< CharSourceRange, 8 > Ranges
Definition: Format.cpp:1554
void ActOnStartSEHFinallyBlock()
Definition: SemaStmt.cpp:3675
QualType getReturnType() const
Definition: Type.h:2952
const CXXRecordDecl * getParent() const
Definition: DeclCXX.h:1817
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:104
field_range fields() const
Definition: Decl.h:3349
RecordDecl * CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams)
Definition: SemaStmt.cpp:3725
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
StmtResult StmtError()
Definition: Ownership.h:268
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2918
bool isValueDependent() const
Definition: Expr.h:146
RecordDecl * getDecl() const
Definition: Type.h:3527
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, Stmt *tryBlock, ArrayRef< Stmt * > handlers)
Definition: Stmt.cpp:824
ObjCInterfaceDecl * getInterface() const
Definition: Type.h:4758
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope)
Definition: SemaStmt.cpp:2606
SmallVector< std::pair< llvm::APSInt, EnumConstantDecl * >, 64 > EnumValsTy
Definition: SemaStmt.cpp:691
bool isOverloadedOperator() const
Definition: Decl.h:2050
StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl)
Definition: SemaStmt.cpp:2550
LabelStmt * getStmt() const
Definition: Decl.h:378
Expr * IgnoreParenCasts() LLVM_READONLY
Definition: Expr.cpp:2439
void setLHS(Expr *Val)
Definition: Stmt.h:730
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *BeginEndDecl, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind)
BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
Definition: SemaStmt.cpp:2125
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:68
bool isOpenMPLoopScope() const
Determine whether this scope is a loop having OpenMP loop directive attached.
Definition: Scope.h:415
bool isIncompleteType(NamedDecl **Def=nullptr) const
Def If non-NULL, and the type refers to some kind of declaration that can be completed (such as a C s...
Definition: Type.cpp:1869
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1032
Preprocessor & PP
Definition: Sema.h:294
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1785
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:726
static CatchHandlerType getTombstoneKey()
Definition: SemaStmt.cpp:3475
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block)
Definition: SemaStmt.cpp:3683
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope)
Definition: SemaStmt.cpp:3690
Perform initialization via a constructor.
A class that does preorder depth-first traversal on the entire Clang AST and visits each node...
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3616
Represents an ObjC class declaration.
Definition: DeclObjC.h:851
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope)
Definition: SemaStmt.cpp:3347
QualType getType() const
Definition: Decl.h:538
void setStmt(LabelStmt *T)
Definition: Decl.h:379
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
static SEHTryStmt * Create(const ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
Definition: Stmt.cpp:1032
ObjCMethodDecl * lookupPrivateMethod(const Selector &Sel, bool Instance=true) const
Lookup a method in the classes implementation hierarchy.
Definition: DeclObjC.cpp:658
Contains information about the compound statement currently being parsed.
Definition: ScopeInfo.h:53
SourceLocation FirstCXXTryLoc
First C++ 'try' statement in the current function.
Definition: ScopeInfo.h:128
const ArrayType * getAsArrayTypeUnsafe() const
Definition: Type.h:5572
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
EnumDecl * getDecl() const
Definition: Type.h:3550
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:6740
static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S, Expr *BeginRange, Expr *EndRange, QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar, SourceLocation ColonLoc, OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr, ExprResult *EndExpr, Sema::BeginEndFunction *BEF)
Create the initialization, compare, and increment steps for the range-based for loop expression...
Definition: SemaStmt.cpp:1994
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:258
Expr * getFalseExpr() const
Definition: Expr.h:3231
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:866
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:71
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, bool TypeMayContainAuto)
Definition: SemaDecl.cpp:8838
Describes the capture of either a variable, or 'this', or variable-length array type.
Definition: Stmt.h:2001
Retains information about a captured region.
Definition: ScopeInfo.h:579
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:5261
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1737
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp)
Definition: SemaStmt.cpp:3080
StmtResult ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal)
Definition: SemaStmt.cpp:483
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1620
ASTContext * Context
void ActOnFinishOfCompoundStmt()
Definition: SemaStmt.cpp:314
Expr * getCond() const
Definition: Expr.h:3222
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef< const Attr * > Attrs, Stmt *SubStmt)
Definition: SemaStmt.cpp:474
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body)
Definition: SemaStmt.cpp:3305
bool isSignedIntegerOrEnumerationType() const
Definition: Type.cpp:1699
Allows QualTypes to be sorted and hence used in maps and sets.
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:552
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:626
Type source information for an attributed type.
Definition: TypeLoc.h:716
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
bool isAtCatchScope() const
isAtCatchScope - Return true if this scope is @catch.
Definition: Scope.h:373
bool isKnownToHaveBooleanValue() const
Definition: Expr.cpp:112
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:5495
static void buildCapturedStmtCaptureList(SmallVectorImpl< CapturedStmt::Capture > &Captures, SmallVectorImpl< Expr * > &CaptureInits, ArrayRef< CapturingScopeInfo::Capture > Candidates)
Definition: SemaStmt.cpp:3749
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope)
Definition: SemaStmt.cpp:436
SourceManager & SourceMgr
Definition: Format.cpp:1205
void setInit(Expr *I)
Definition: Decl.cpp:2047
void setInvalidDecl(bool Invalid=true)
Definition: DeclBase.cpp:96
static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef, const VarDecl *VD)
Definition: SemaStmt.cpp:2455
void setContextParam(unsigned i, ImplicitParamDecl *P)
Definition: Decl.h:3662
Defines the clang::Preprocessor interface.
ObjCMethodDecl * lookupInstanceMethod(Selector Sel) const
Lookup an instance method for a given selector.
Definition: DeclObjC.h:1513
Kind getKind() const
Definition: DeclBase.h:375
bool isGnuLocal() const
Definition: Decl.h:381
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:1968
Expr * getRHS()
Definition: Stmt.h:718
Represents Objective-C's @synchronized statement.
Definition: StmtObjC.h:262
void removeLocalConst()
Definition: Type.h:5110
bool isMSAsmLabel() const
Definition: Decl.h:388
Defines the clang::TypeLoc interface and its subclasses.
static DeclContext * castToDeclContext(const CapturedDecl *D)
Definition: Decl.h:3683
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, Decl *CondVar)
Definition: SemaStmt.cpp:580
const SwitchCase * getSwitchCaseList() const
Definition: Stmt.h:987
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:107
Expr * getSubExpr() const
Definition: Expr.h:1699
bool isDependentType() const
Definition: Type.h:1727
bool isExceptionVariable() const
Determine whether this variable is the exception variable in a C++ catch statememt or an Objective-C ...
Definition: Decl.h:1184
bool isFunctionOrMethod() const
Definition: DeclBase.h:1223
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition: Decl.cpp:3892
static bool isEqual(const CatchHandlerType &LHS, const CatchHandlerType &RHS)
Definition: SemaStmt.cpp:3484
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1174
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1510
StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro=false)
Definition: SemaStmt.cpp:66
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:858
void setLocation(SourceLocation L)
Definition: DeclBase.h:373
DeclarationName getDeclName() const
Definition: Decl.h:189
static AttributedStmt * Create(const ASTContext &C, SourceLocation Loc, ArrayRef< const Attr * > Attrs, Stmt *SubStmt)
Definition: Stmt.cpp:311
void setHasCXXTry(SourceLocation TryLoc)
Definition: ScopeInfo.h:330
ValueDecl * getDecl()
Definition: Expr.h:994
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2405
The result type of a method or function.
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:611
Expr * getTrueExpr() const
Definition: Expr.h:3226
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:1835
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:95
static SEHFinallyStmt * Create(const ASTContext &C, SourceLocation FinallyLoc, Stmt *Block)
Definition: Stmt.cpp:1068
AttrVec & getAttrs()
Definition: DeclBase.h:431
void setBody(Stmt *S)
Definition: StmtCXX.h:182
BuildForRangeKind
Definition: Sema.h:3299
static CatchHandlerType getEmptyKey()
Definition: SemaStmt.cpp:3470
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute. The C++11 [[noreturn]] attr...
Definition: Type.h:2959
void ActOnStartOfCompoundStmt()
Definition: SemaStmt.cpp:310
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:208
static QualType GetTypeBeforeIntegralPromotion(Expr *&expr)
Definition: SemaStmt.cpp:569
#define false
Definition: stdbool.h:33
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
The "struct" keyword.
Definition: Type.h:4130
SelectorTable & Selectors
Definition: ASTContext.h:440
Kind
This captures a statement into a function. For example, the following pragma annotated compound state...
Definition: Stmt.h:1989
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5476
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt)
ActOnCaseStmtBody - This installs a statement as the body of a case.
Definition: SemaStmt.cpp:428
void setHasSEHTry(SourceLocation TryLoc)
Definition: ScopeInfo.h:335
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
Definition: SemaDecl.cpp:13941
DeduceAutoResult
Result type of DeduceAutoType.
Definition: Sema.h:6329
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
enumerator_range enumerators() const
Definition: Decl.h:3087
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Expr * getSourceExpr() const
Definition: Expr.h:869
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
Definition: SemaStmt.cpp:1170
void FinalizeDeclaration(Decl *D)
Definition: SemaDecl.cpp:9850
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope)
Definition: SemaStmt.cpp:3061
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isSingleDecl() const
Definition: Stmt.h:463
Expr * getLHS()
Definition: Stmt.h:717
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt)
Definition: SemaStmt.cpp:451
bool isSEHTrySupported() const
Whether the target supports SEH __try.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:153
StmtResult ActOnForEachLValueExpr(Expr *E)
Definition: SemaStmt.cpp:1660
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1158
void setBody(Stmt *B)
Definition: Decl.h:3641
bool isLocalVarDecl() const
Definition: Decl.h:951
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:685
const Expr * getCond() const
Definition: Stmt.h:985
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
QualType withConst() const
Definition: Type.h:736
StmtResult ActOnCapturedRegionEnd(Stmt *S)
Definition: SemaStmt.cpp:3874
void setAllEnumCasesCovered()
Definition: Stmt.h:1014
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT)
Definition: SemaStmt.cpp:2968
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw)
Definition: SemaStmt.cpp:3321
StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
Definition: SemaStmt.cpp:3661
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
static bool CmpEnumVals(const std::pair< llvm::APSInt, EnumConstantDecl * > &lhs, const std::pair< llvm::APSInt, EnumConstantDecl * > &rhs)
Definition: SemaStmt.cpp:553
CanQualType VoidTy
Definition: ASTContext.h:817
Describes the kind of initialization being performed, along with location information for tokens rela...
SourceLocation getContinueLoc() const
Definition: Stmt.h:1299
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:486
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body)
Definition: SemaStmt.cpp:728
Stmt * getCapturedStmt()
Retrieve the statement being captured.
Definition: Stmt.h:2098
const T * castAs() const
Definition: Type.h:5586
bool isTypeDependent() const
Definition: Expr.h:166
Expr * getRangeInit()
Definition: Stmt.cpp:863
bool isFileContext() const
Definition: DeclBase.h:1239
PtrTy get() const
Definition: Ownership.h:74
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1825
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5086
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody)
Definition: SemaStmt.cpp:3401
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:645
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:68
__SIZE_TYPE__ size_t
Definition: stddef.h:62
Opcode getOpcode() const
Definition: Expr.h:1696
Representation of a Microsoft __if_exists or __if_not_exists statement with a dependent name...
Definition: StmtCXX.h:234
const Decl * getSingleDecl() const
Definition: Stmt.h:467
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.cpp:193
static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef, const VarDecl *VD, QualType RangeInitType)
Definition: SemaStmt.cpp:2385
QualType getPointeeType() const
Definition: Type.h:2139
QualType getType() const
Definition: Expr.h:125
void setCapturedRecord()
Mark the record as a record for captured variables in CapturedStmt construct.
Definition: Decl.cpp:3625
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3059
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body)
Definition: SemaStmt.cpp:3419
AccessSpecifier getAccessSpecifier() const
Returns the access specifier for this base specifier.
Definition: DeclCXX.h:233
CapturedRegionKind CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:590
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1184
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1639
void ActOnCapturedRegionError()
Definition: SemaStmt.cpp:3858
void addNRVOCandidate(VarDecl *VD)
Definition: Scope.h:451
bool isInvalidDecl() const
Definition: DeclBase.h:498
void setARCPseudoStrong(bool ps)
Definition: Decl.h:1227
StmtResult ActOnExprStmtError()
Definition: SemaStmt.cpp:61
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1044
* Step
Definition: OpenMPClause.h:304
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:104
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp)
Definition: SemaStmt.cpp:2559
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
bool isLValue() const
Definition: Expr.h:250
QualType getCaughtType() const
Definition: Stmt.cpp:678
static void DiagnoseForRangeVariableCopies(Sema &SemaRef, const CXXForRangeStmt *ForStmt)
Definition: SemaStmt.cpp:2496
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:633
bool hasAttrs() const
Definition: DeclBase.h:427
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
sema::CompoundScopeInfo & getCurCompoundScope() const
Definition: SemaStmt.cpp:318
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1855
Expr * IgnoreParenImpCasts() LLVM_READONLY
Definition: Expr.cpp:2526
QualType getNonReferenceType() const
Definition: Type.h:5182
Decl * getCalleeDecl()
Definition: Expr.cpp:1160
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested)
Definition: SemaStmt.cpp:3713
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:279
RecordDecl * TheRecordDecl
The captured record type.
Definition: ScopeInfo.h:584
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, SourceLocation DotDotDotLoc, Expr *RHSVal, SourceLocation ColonLoc)
Definition: SemaStmt.cpp:366
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>. Pointer - pointer requires t...
const T * getAs() const
Definition: Type.h:5555
static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S, SourceLocation ForLoc, Stmt *LoopVarDecl, SourceLocation ColonLoc, Expr *Range, SourceLocation RangeLoc, SourceLocation RParenLoc)
Definition: SemaStmt.cpp:2072
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T)
Definition: Decl.cpp:3850
Represents Objective-C's collection statement.
Definition: StmtObjC.h:24
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition: Expr.h:3301
void setRHS(Expr *Val)
Definition: Stmt.h:731
bool isDeduced() const
Definition: Type.h:3900
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
CanQualType DependentTy
Definition: ASTContext.h:832
static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S, const EnumDecl *ED, const Expr *CaseExpr, EnumValsTy::iterator &EI, EnumValsTy::iterator &EIEnd, const llvm::APSInt &Val)
Definition: SemaStmt.cpp:695
void setUsesSEHTry(bool UST)
Definition: Decl.h:1840
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:253
ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, SourceLocation RangeLoc, VarDecl *Decl, BeginEndFunction BEF, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1505
Represents Objective-C's @finally statement.
Definition: StmtObjC.h:120
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:78
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1228
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Represents a base class of a C++ class.
Definition: DeclCXX.h:157
static bool DiagnoseUnusedComparison(Sema &S, const Expr *E)
Diagnose unused comparisons, both builtin and overloaded operators. For '==' and '!=', suggest fixits for '=' or '|='.
Definition: SemaStmt.cpp:127
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:316
bool isUsable() const
Definition: Ownership.h:160
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:3317
Expr * getBase() const
Definition: Expr.h:2405
bool isPODType(ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:1922
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO=true)
Perform the initialization of a potentially-movable value, which is the result of return value...
Definition: SemaStmt.cpp:2703
const Expr * getSubExpr() const
Definition: Expr.h:1638
static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, QualType Type)
Create the initialization entity for a related result.
Describes the sequence of initializations required to initialize a given object or reference with a s...
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5096
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp)
Definition: SemaStmt.cpp:2783
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
bool isObjCObjectPointerType() const
Definition: Type.h:5304
static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, SourceLocation Loc, int DiagID)
Definition: SemaStmt.cpp:1831
SourceLocation getBreakLoc() const
Definition: Stmt.h:1327
VarDecl * getLoopVariable()
Definition: Stmt.cpp:874
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr.type.conv]).
Definition: ExprCXX.h:1241
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1202
StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind)
Definition: SemaStmt.cpp:1935
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult{return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:307
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:115
bool isArrayType() const
Definition: Type.h:5271
Defines the clang::TargetInfo interface.
Expr * getRHS() const
Definition: Expr.h:2966
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body)
Definition: SemaStmt.cpp:2532
bool HasImplicitReturnType
Whether the target type of return statements in this context is deduced (e.g. a lambda or block with ...
Definition: ScopeInfo.h:490
static bool EqEnumVals(const std::pair< llvm::APSInt, EnumConstantDecl * > &lhs, const std::pair< llvm::APSInt, EnumConstantDecl * > &rhs)
Definition: SemaStmt.cpp:561
ExprResult ExprError()
Definition: Ownership.h:267
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand)
Definition: SemaStmt.cpp:3365
bool isRecord() const
Definition: DeclBase.h:1247
VarDecl * getExceptionDecl() const
Definition: StmtCXX.h:50
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Definition: Expr.h:899
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1125
SourceManager & SourceMgr
Definition: Sema.h:298
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:17
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result)
#define true
Definition: stdbool.h:32
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:99
static bool hasDeducedReturnType(FunctionDecl *FD)
Determine whether the declared return type of the specified function contains 'auto'.
Definition: SemaStmt.cpp:2773
SourceLocation getRParenLoc() const
Definition: StmtCXX.h:189
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:372
ASTContext & Context
Definition: Sema.h:295
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:434
SourceLocation getStartLoc() const
Definition: Stmt.h:474
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5075
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
Definition: Type.h:633
Describes an entity that is being initialized.
ExprResult release()
Definition: Sema.h:3177
void setType(QualType newType)
Definition: Decl.h:539
Wrapper for source info for pointers.
Definition: TypeLoc.h:1122
SourceLocation ColonLoc
Location of ':'.
Definition: OpenMPClause.h:260
bool isSingleDecl() const
Definition: DeclGroup.h:84
Represents Objective-C's @autoreleasepool Statement.
Definition: StmtObjC.h:345
static SEHExceptStmt * Create(const ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block)
Definition: Stmt.cpp:1056
Declaration of a template function.
Definition: DeclTemplate.h:821
static ObjCAtTryStmt * Create(const ASTContext &Context, SourceLocation atTryLoc, Stmt *atTryStmt, Stmt **CatchStmts, unsigned NumCatchStmts, Stmt *atFinallyStmt)
Definition: Stmt.cpp:794
bool isIntegerType() const
Definition: Type.h:5448
bool hasLocalStorage() const
Definition: Decl.h:887
StmtResult ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
Definition: SemaStmt.cpp:3625
static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc, const Scope &DestScope)
Definition: SemaStmt.cpp:2585
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1049
Expr * IgnoreParens() LLVM_READONLY
Definition: Expr.cpp:2408
bool isPointerType() const
Definition: Type.h:5232
OverloadedOperatorKind getOverloadedOperator() const
Definition: Decl.cpp:2916
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, Decl *CondVar, Stmt *Body)
Definition: SemaStmt.cpp:1224
QualType getDeducedType() const
Get the type deduced for this auto type, or null if it's either not been deduced or was deduced to a ...
Definition: Type.h:3897