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