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