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