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