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