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