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