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