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