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