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