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