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