clang 19.0.0git
SemaStmt.cpp
Go to the documentation of this file.
1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for statements.
10//
11//===----------------------------------------------------------------------===//
12
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 E = Cast->getSubExpr()->IgnoreImpCasts();
286
287 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
288 if (E->getType()->isVoidType())
289 return;
290
291 if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
292 CE->getUnusedResultAttr(Context)),
293 Loc, R1, R2, /*isCtor=*/false))
294 return;
295
296 // If the callee has attribute pure, const, or warn_unused_result, warn with
297 // a more specific message to make it clear what is happening. If the call
298 // is written in a macro body, only warn if it has the warn_unused_result
299 // attribute.
300 if (const Decl *FD = CE->getCalleeDecl()) {
301 if (ShouldSuppress)
302 return;
303 if (FD->hasAttr<PureAttr>()) {
304 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
305 return;
306 }
307 if (FD->hasAttr<ConstAttr>()) {
308 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
309 return;
310 }
311 }
312 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
313 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
314 const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
315 A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
316 if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
317 return;
318 }
319 } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
320 if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
321
322 if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
323 R2, /*isCtor=*/false))
324 return;
325 }
326 } else if (ShouldSuppress)
327 return;
328
329 E = WarnExpr;
330 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
331 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
332 Diag(Loc, diag::err_arc_unused_init_message) << R1;
333 return;
334 }
335 const ObjCMethodDecl *MD = ME->getMethodDecl();
336 if (MD) {
337 if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
338 R2, /*isCtor=*/false))
339 return;
340 }
341 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
342 const Expr *Source = POE->getSyntacticForm();
343 // Handle the actually selected call of an OpenMP specialized call.
344 if (LangOpts.OpenMP && isa<CallExpr>(Source) &&
345 POE->getNumSemanticExprs() == 1 &&
346 isa<CallExpr>(POE->getSemanticExpr(0)))
347 return DiagnoseUnusedExprResult(POE->getSemanticExpr(0), DiagID);
348 if (isa<ObjCSubscriptRefExpr>(Source))
349 DiagID = diag::warn_unused_container_subscript_expr;
350 else if (isa<ObjCPropertyRefExpr>(Source))
351 DiagID = diag::warn_unused_property_expr;
352 } else if (const CXXFunctionalCastExpr *FC
353 = dyn_cast<CXXFunctionalCastExpr>(E)) {
354 const Expr *E = FC->getSubExpr();
355 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
356 E = TE->getSubExpr();
357 if (isa<CXXTemporaryObjectExpr>(E))
358 return;
359 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
360 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
361 if (!RD->getAttr<WarnUnusedAttr>())
362 return;
363 }
364 // Diagnose "(void*) blah" as a typo for "(void) blah".
365 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
366 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
367 QualType T = TI->getType();
368
369 // We really do want to use the non-canonical type here.
370 if (T == Context.VoidPtrTy) {
372
373 Diag(Loc, diag::warn_unused_voidptr)
375 return;
376 }
377 }
378
379 // Tell the user to assign it into a variable to force a volatile load if this
380 // isn't an array.
381 if (E->isGLValue() && E->getType().isVolatileQualified() &&
382 !E->getType()->isArrayType()) {
383 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
384 return;
385 }
386
387 // Do not diagnose use of a comma operator in a SFINAE context because the
388 // type of the left operand could be used for SFINAE, so technically it is
389 // *used*.
390 if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
391 DiagIfReachable(Loc, S ? llvm::ArrayRef(S) : std::nullopt,
392 PDiag(DiagID) << R1 << R2);
393}
394
395void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
396 PushCompoundScope(IsStmtExpr);
397}
398
400 if (getCurFPFeatures().isFPConstrained()) {
402 assert(FSI);
403 FSI->setUsesFPIntrin();
404 }
405}
406
409}
410
412 return getCurFunction()->CompoundScopes.back();
413}
414
416 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
417 const unsigned NumElts = Elts.size();
418
419 // If we're in C mode, check that we don't have any decls after stmts. If
420 // so, emit an extension diagnostic in C89 and potentially a warning in later
421 // versions.
422 const unsigned MixedDeclsCodeID = getLangOpts().C99
423 ? diag::warn_mixed_decls_code
424 : diag::ext_mixed_decls_code;
425 if (!getLangOpts().CPlusPlus && !Diags.isIgnored(MixedDeclsCodeID, L)) {
426 // Note that __extension__ can be around a decl.
427 unsigned i = 0;
428 // Skip over all declarations.
429 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
430 /*empty*/;
431
432 // We found the end of the list or a statement. Scan for another declstmt.
433 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
434 /*empty*/;
435
436 if (i != NumElts) {
437 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
438 Diag(D->getLocation(), MixedDeclsCodeID);
439 }
440 }
441
442 // Check for suspicious empty body (null statement) in `for' and `while'
443 // statements. Don't do anything for template instantiations, this just adds
444 // noise.
445 if (NumElts != 0 && !CurrentInstantiationScope &&
446 getCurCompoundScope().HasEmptyLoopBodies) {
447 for (unsigned i = 0; i != NumElts - 1; ++i)
448 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
449 }
450
451 // Calculate difference between FP options in this compound statement and in
452 // the enclosing one. If this is a function body, take the difference against
453 // default options. In this case the difference will indicate options that are
454 // changed upon entry to the statement.
455 FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1)
459
460 return CompoundStmt::Create(Context, Elts, FPDiff, L, R);
461}
462
465 if (!Val.get())
466 return Val;
467
469 return ExprError();
470
471 // If we're not inside a switch, let the 'case' statement handling diagnose
472 // this. Just clean up after the expression as best we can.
473 if (getCurFunction()->SwitchStack.empty())
474 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
476
477 Expr *CondExpr =
478 getCurFunction()->SwitchStack.back().getPointer()->getCond();
479 if (!CondExpr)
480 return ExprError();
481 QualType CondType = CondExpr->getType();
482
483 auto CheckAndFinish = [&](Expr *E) {
484 if (CondType->isDependentType() || E->isTypeDependent())
485 return ExprResult(E);
486
487 if (getLangOpts().CPlusPlus11) {
488 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
489 // constant expression of the promoted type of the switch condition.
490 llvm::APSInt TempVal;
491 return CheckConvertedConstantExpression(E, CondType, TempVal,
493 }
494
495 ExprResult ER = E;
496 if (!E->isValueDependent())
498 if (!ER.isInvalid())
499 ER = DefaultLvalueConversion(ER.get());
500 if (!ER.isInvalid())
501 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
502 if (!ER.isInvalid())
503 ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
504 return ER;
505 };
506
508 Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
509 CheckAndFinish);
510 if (Converted.get() == Val.get())
511 Converted = CheckAndFinish(Val.get());
512 return Converted;
513}
514
517 SourceLocation DotDotDotLoc, ExprResult RHSVal,
518 SourceLocation ColonLoc) {
519 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
520 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
521 : RHSVal.isInvalid() || RHSVal.get()) &&
522 "missing RHS value");
523
524 if (getCurFunction()->SwitchStack.empty()) {
525 Diag(CaseLoc, diag::err_case_not_in_switch);
526 return StmtError();
527 }
528
529 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
530 getCurFunction()->SwitchStack.back().setInt(true);
531 return StmtError();
532 }
533
534 if (LangOpts.OpenACC &&
535 getCurScope()->isInOpenACCComputeConstructScope(Scope::SwitchScope)) {
536 Diag(CaseLoc, diag::err_acc_branch_in_out_compute_construct)
537 << /*branch*/ 0 << /*into*/ 1;
538 return StmtError();
539 }
540
541 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
542 CaseLoc, DotDotDotLoc, ColonLoc);
543 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
544 return CS;
545}
546
547/// ActOnCaseStmtBody - This installs a statement as the body of a case.
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
2223/// In an Objective C collection iteration statement:
2224/// for (x in y)
2225/// x can be an arbitrary l-value expression. Bind it up as a
2226/// full-expression.
2228 // Reduce placeholder expressions here. Note that this rejects the
2229 // use of pseudo-object l-values in this position.
2230 ExprResult result = CheckPlaceholderExpr(E);
2231 if (result.isInvalid()) return StmtError();
2232 E = result.get();
2233
2234 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2235 if (FullExpr.isInvalid())
2236 return StmtError();
2237 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
2238}
2239
2240/// Finish building a variable declaration for a for-range statement.
2241/// \return true if an error occurs.
2243 SourceLocation Loc, int DiagID) {
2244 if (Decl->getType()->isUndeducedType()) {
2246 if (!Res.isUsable()) {
2248 return true;
2249 }
2250 Init = Res.get();
2251 }
2252
2253 // Deduce the type for the iterator variable now rather than leaving it to
2254 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2255 QualType InitType;
2256 if (!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) {
2257 SemaRef.Diag(Loc, DiagID) << Init->getType();
2258 } else {
2259 TemplateDeductionInfo Info(Init->getExprLoc());
2261 Decl->getTypeSourceInfo()->getTypeLoc(), Init, InitType, Info);
2264 SemaRef.Diag(Loc, DiagID) << Init->getType();
2265 }
2266
2267 if (InitType.isNull()) {
2269 return true;
2270 }
2271 Decl->setType(InitType);
2272
2273 // In ARC, infer lifetime.
2274 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2275 // we're doing the equivalent of fast iteration.
2276 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2277 SemaRef.ObjC().inferObjCARCLifetime(Decl))
2279
2280 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
2281 SemaRef.FinalizeDeclaration(Decl);
2282 SemaRef.CurContext->addHiddenDecl(Decl);
2283 return false;
2284}
2285
2286namespace {
2287// An enum to represent whether something is dealing with a call to begin()
2288// or a call to end() in a range-based for loop.
2289enum BeginEndFunction {
2290 BEF_begin,
2291 BEF_end
2292};
2293
2294/// Produce a note indicating which begin/end function was implicitly called
2295/// by a C++11 for-range statement. This is often not obvious from the code,
2296/// nor from the diagnostics produced when analysing the implicit expressions
2297/// required in a for-range statement.
2298void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2299 BeginEndFunction BEF) {
2300 CallExpr *CE = dyn_cast<CallExpr>(E);
2301 if (!CE)
2302 return;
2303 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2304 if (!D)
2305 return;
2307
2308 std::string Description;
2309 bool IsTemplate = false;
2310 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2311 Description = SemaRef.getTemplateArgumentBindingsText(
2312 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2313 IsTemplate = true;
2314 }
2315
2316 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2317 << BEF << IsTemplate << Description << E->getType();
2318}
2319
2320/// Build a variable declaration for a for-range statement.
2321VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2322 QualType Type, StringRef Name) {
2323 DeclContext *DC = SemaRef.CurContext;
2324 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2326 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2327 TInfo, SC_None);
2328 Decl->setImplicit();
2329 return Decl;
2330}
2331
2332}
2333
2334static bool ObjCEnumerationCollection(Expr *Collection) {
2335 return !Collection->isTypeDependent()
2336 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2337}
2338
2339/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2340///
2341/// C++11 [stmt.ranged]:
2342/// A range-based for statement is equivalent to
2343///
2344/// {
2345/// auto && __range = range-init;
2346/// for ( auto __begin = begin-expr,
2347/// __end = end-expr;
2348/// __begin != __end;
2349/// ++__begin ) {
2350/// for-range-declaration = *__begin;
2351/// statement
2352/// }
2353/// }
2354///
2355/// The body of the loop is not available yet, since it cannot be analysed until
2356/// we have determined the type of the for-range-declaration.
2358 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2359 Stmt *First, SourceLocation ColonLoc, Expr *Range, SourceLocation RParenLoc,
2360 BuildForRangeKind Kind,
2361 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2362 // FIXME: recover in order to allow the body to be parsed.
2363 if (!First)
2364 return StmtError();
2365
2367 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2368 if (InitStmt)
2369 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2370 << InitStmt->getSourceRange();
2371 return ObjC().ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2372 }
2373
2374 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2375 assert(DS && "first part of for range not a decl stmt");
2376
2377 if (!DS->isSingleDecl()) {
2378 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2379 return StmtError();
2380 }
2381
2382 // This function is responsible for attaching an initializer to LoopVar. We
2383 // must call ActOnInitializerError if we fail to do so.
2384 Decl *LoopVar = DS->getSingleDecl();
2385 if (LoopVar->isInvalidDecl() || !Range ||
2387 ActOnInitializerError(LoopVar);
2388 return StmtError();
2389 }
2390
2391 // Build the coroutine state immediately and not later during template
2392 // instantiation
2393 if (!CoawaitLoc.isInvalid()) {
2394 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) {
2395 ActOnInitializerError(LoopVar);
2396 return StmtError();
2397 }
2398 }
2399
2400 // Build auto && __range = range-init
2401 // Divide by 2, since the variables are in the inner scope (loop body).
2402 const auto DepthStr = std::to_string(S->getDepth() / 2);
2403 SourceLocation RangeLoc = Range->getBeginLoc();
2404 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2406 std::string("__range") + DepthStr);
2407 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2408 diag::err_for_range_deduction_failure)) {
2409 ActOnInitializerError(LoopVar);
2410 return StmtError();
2411 }
2412
2413 // Claim the type doesn't contain auto: we've already done the checking.
2414 DeclGroupPtrTy RangeGroup =
2416 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2417 if (RangeDecl.isInvalid()) {
2418 ActOnInitializerError(LoopVar);
2419 return StmtError();
2420 }
2421
2423 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2424 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2425 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind,
2426 LifetimeExtendTemps);
2427 if (R.isInvalid()) {
2428 ActOnInitializerError(LoopVar);
2429 return StmtError();
2430 }
2431
2432 return R;
2433}
2434
2435/// Create the initialization, compare, and increment steps for
2436/// the range-based for loop expression.
2437/// This function does not handle array-based for loops,
2438/// which are created in Sema::BuildCXXForRangeStmt.
2439///
2440/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2441/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2442/// CandidateSet and BEF are set and some non-success value is returned on
2443/// failure.
2445BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2446 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2447 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2448 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2449 ExprResult *EndExpr, BeginEndFunction *BEF) {
2450 DeclarationNameInfo BeginNameInfo(
2451 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2452 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2453 ColonLoc);
2454
2455 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2457 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2458
2459 auto BuildBegin = [&] {
2460 *BEF = BEF_begin;
2461 Sema::ForRangeStatus RangeStatus =
2462 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2463 BeginMemberLookup, CandidateSet,
2464 BeginRange, BeginExpr);
2465
2466 if (RangeStatus != Sema::FRS_Success) {
2467 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2468 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2469 << ColonLoc << BEF_begin << BeginRange->getType();
2470 return RangeStatus;
2471 }
2472 if (!CoawaitLoc.isInvalid()) {
2473 // FIXME: getCurScope() should not be used during template instantiation.
2474 // We should pick up the set of unqualified lookup results for operator
2475 // co_await during the initial parse.
2476 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2477 BeginExpr->get());
2478 if (BeginExpr->isInvalid())
2480 }
2481 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2482 diag::err_for_range_iter_deduction_failure)) {
2483 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2485 }
2486 return Sema::FRS_Success;
2487 };
2488
2489 auto BuildEnd = [&] {
2490 *BEF = BEF_end;
2491 Sema::ForRangeStatus RangeStatus =
2492 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2493 EndMemberLookup, CandidateSet,
2494 EndRange, EndExpr);
2495 if (RangeStatus != Sema::FRS_Success) {
2496 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2497 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2498 << ColonLoc << BEF_end << EndRange->getType();
2499 return RangeStatus;
2500 }
2501 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2502 diag::err_for_range_iter_deduction_failure)) {
2503 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2505 }
2506 return Sema::FRS_Success;
2507 };
2508
2509 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2510 // - if _RangeT is a class type, the unqualified-ids begin and end are
2511 // looked up in the scope of class _RangeT as if by class member access
2512 // lookup (3.4.5), and if either (or both) finds at least one
2513 // declaration, begin-expr and end-expr are __range.begin() and
2514 // __range.end(), respectively;
2515 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2516 if (BeginMemberLookup.isAmbiguous())
2518
2519 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2520 if (EndMemberLookup.isAmbiguous())
2522
2523 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2524 // Look up the non-member form of the member we didn't find, first.
2525 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2526 // a 'begin' but ignored it because there was no member 'end'"
2527 // diagnostic.
2528 auto BuildNonmember = [&](
2529 BeginEndFunction BEFFound, LookupResult &Found,
2530 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2531 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2532 LookupResult OldFound = std::move(Found);
2533 Found.clear();
2534
2535 if (Sema::ForRangeStatus Result = BuildNotFound())
2536 return Result;
2537
2538 switch (BuildFound()) {
2539 case Sema::FRS_Success:
2540 return Sema::FRS_Success;
2541
2543 CandidateSet->NoteCandidates(
2544 PartialDiagnosticAt(BeginRange->getBeginLoc(),
2545 SemaRef.PDiag(diag::err_for_range_invalid)
2546 << BeginRange->getType() << BEFFound),
2547 SemaRef, OCD_AllCandidates, BeginRange);
2548 [[fallthrough]];
2549
2551 for (NamedDecl *D : OldFound) {
2552 SemaRef.Diag(D->getLocation(),
2553 diag::note_for_range_member_begin_end_ignored)
2554 << BeginRange->getType() << BEFFound;
2555 }
2557 }
2558 llvm_unreachable("unexpected ForRangeStatus");
2559 };
2560 if (BeginMemberLookup.empty())
2561 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2562 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2563 }
2564 } else {
2565 // - otherwise, begin-expr and end-expr are begin(__range) and
2566 // end(__range), respectively, where begin and end are looked up with
2567 // argument-dependent lookup (3.4.2). For the purposes of this name
2568 // lookup, namespace std is an associated namespace.
2569 }
2570
2571 if (Sema::ForRangeStatus Result = BuildBegin())
2572 return Result;
2573 return BuildEnd();
2574}
2575
2576/// Speculatively attempt to dereference an invalid range expression.
2577/// If the attempt fails, this function will return a valid, null StmtResult
2578/// and emit no diagnostics.
2580 SourceLocation ForLoc,
2581 SourceLocation CoawaitLoc,
2582 Stmt *InitStmt,
2583 Stmt *LoopVarDecl,
2584 SourceLocation ColonLoc,
2585 Expr *Range,
2586 SourceLocation RangeLoc,
2587 SourceLocation RParenLoc) {
2588 // Determine whether we can rebuild the for-range statement with a
2589 // dereferenced range expression.
2590 ExprResult AdjustedRange;
2591 {
2592 Sema::SFINAETrap Trap(SemaRef);
2593
2594 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2595 if (AdjustedRange.isInvalid())
2596 return StmtResult();
2597
2598 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2599 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2600 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2601 if (SR.isInvalid())
2602 return StmtResult();
2603 }
2604
2605 // The attempt to dereference worked well enough that it could produce a valid
2606 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2607 // case there are any other (non-fatal) problems with it.
2608 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2609 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2610 return SemaRef.ActOnCXXForRangeStmt(
2611 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2612 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2613}
2614
2615/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2617 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2618 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
2619 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
2620 BuildForRangeKind Kind,
2621 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2622 // FIXME: This should not be used during template instantiation. We should
2623 // pick up the set of unqualified lookup results for the != and + operators
2624 // in the initial parse.
2625 //
2626 // Testcase (accepts-invalid):
2627 // template<typename T> void f() { for (auto x : T()) {} }
2628 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2629 // bool operator!=(N::X, N::X); void operator++(N::X);
2630 // void g() { f<N::X>(); }
2631 Scope *S = getCurScope();
2632
2633 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2634 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2635 QualType RangeVarType = RangeVar->getType();
2636
2637 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2638 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2639
2640 StmtResult BeginDeclStmt = Begin;
2641 StmtResult EndDeclStmt = End;
2642 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2643
2644 if (RangeVarType->isDependentType()) {
2645 // The range is implicitly used as a placeholder when it is dependent.
2646 RangeVar->markUsed(Context);
2647
2648 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2649 // them in properly when we instantiate the loop.
2650 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2651 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2652 for (auto *Binding : DD->bindings())
2653 Binding->setType(Context.DependentTy);
2654 LoopVar->setType(SubstAutoTypeDependent(LoopVar->getType()));
2655 }
2656 } else if (!BeginDeclStmt.get()) {
2657 SourceLocation RangeLoc = RangeVar->getLocation();
2658
2659 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2660
2661 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2662 VK_LValue, ColonLoc);
2663 if (BeginRangeRef.isInvalid())
2664 return StmtError();
2665
2666 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2667 VK_LValue, ColonLoc);
2668 if (EndRangeRef.isInvalid())
2669 return StmtError();
2670
2672 Expr *Range = RangeVar->getInit();
2673 if (!Range)
2674 return StmtError();
2675 QualType RangeType = Range->getType();
2676
2677 if (RequireCompleteType(RangeLoc, RangeType,
2678 diag::err_for_range_incomplete_type))
2679 return StmtError();
2680
2681 // P2718R0 - Lifetime extension in range-based for loops.
2682 if (getLangOpts().CPlusPlus23 && !LifetimeExtendTemps.empty()) {
2683 InitializedEntity Entity =
2685 for (auto *MTE : LifetimeExtendTemps)
2686 MTE->setExtendingDecl(RangeVar, Entity.allocateManglingNumber());
2687 }
2688
2689 // Build auto __begin = begin-expr, __end = end-expr.
2690 // Divide by 2, since the variables are in the inner scope (loop body).
2691 const auto DepthStr = std::to_string(S->getDepth() / 2);
2692 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2693 std::string("__begin") + DepthStr);
2694 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2695 std::string("__end") + DepthStr);
2696
2697 // Build begin-expr and end-expr and attach to __begin and __end variables.
2698 ExprResult BeginExpr, EndExpr;
2699 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2700 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2701 // __range + __bound, respectively, where __bound is the array bound. If
2702 // _RangeT is an array of unknown size or an array of incomplete type,
2703 // the program is ill-formed;
2704
2705 // begin-expr is __range.
2706 BeginExpr = BeginRangeRef;
2707 if (!CoawaitLoc.isInvalid()) {
2708 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2709 if (BeginExpr.isInvalid())
2710 return StmtError();
2711 }
2712 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2713 diag::err_for_range_iter_deduction_failure)) {
2714 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2715 return StmtError();
2716 }
2717
2718 // Find the array bound.
2719 ExprResult BoundExpr;
2720 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2721 BoundExpr = IntegerLiteral::Create(
2722 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2723 else if (const VariableArrayType *VAT =
2724 dyn_cast<VariableArrayType>(UnqAT)) {
2725 // For a variably modified type we can't just use the expression within
2726 // the array bounds, since we don't want that to be re-evaluated here.
2727 // Rather, we need to determine what it was when the array was first
2728 // created - so we resort to using sizeof(vla)/sizeof(element).
2729 // For e.g.
2730 // void f(int b) {
2731 // int vla[b];
2732 // b = -1; <-- This should not affect the num of iterations below
2733 // for (int &c : vla) { .. }
2734 // }
2735
2736 // FIXME: This results in codegen generating IR that recalculates the
2737 // run-time number of elements (as opposed to just using the IR Value
2738 // that corresponds to the run-time value of each bound that was
2739 // generated when the array was created.) If this proves too embarrassing
2740 // even for unoptimized IR, consider passing a magic-value/cookie to
2741 // codegen that then knows to simply use that initial llvm::Value (that
2742 // corresponds to the bound at time of array creation) within
2743 // getelementptr. But be prepared to pay the price of increasing a
2744 // customized form of coupling between the two components - which could
2745 // be hard to maintain as the codebase evolves.
2746
2748 EndVar->getLocation(), UETT_SizeOf,
2749 /*IsType=*/true,
2751 VAT->desugar(), RangeLoc))
2752 .getAsOpaquePtr(),
2753 EndVar->getSourceRange());
2754 if (SizeOfVLAExprR.isInvalid())
2755 return StmtError();
2756
2757 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2758 EndVar->getLocation(), UETT_SizeOf,
2759 /*IsType=*/true,
2760 CreateParsedType(VAT->desugar(),
2762 VAT->getElementType(), RangeLoc))
2763 .getAsOpaquePtr(),
2764 EndVar->getSourceRange());
2765 if (SizeOfEachElementExprR.isInvalid())
2766 return StmtError();
2767
2768 BoundExpr =
2769 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2770 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2771 if (BoundExpr.isInvalid())
2772 return StmtError();
2773
2774 } else {
2775 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2776 // UnqAT is not incomplete and Range is not type-dependent.
2777 llvm_unreachable("Unexpected array type in for-range");
2778 }
2779
2780 // end-expr is __range + __bound.
2781 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2782 BoundExpr.get());
2783 if (EndExpr.isInvalid())
2784 return StmtError();
2785 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2786 diag::err_for_range_iter_deduction_failure)) {
2787 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2788 return StmtError();
2789 }
2790 } else {
2791 OverloadCandidateSet CandidateSet(RangeLoc,
2793 BeginEndFunction BEFFailure;
2795 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2796 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2797 &BEFFailure);
2798
2799 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2800 BEFFailure == BEF_begin) {
2801 // If the range is being built from an array parameter, emit a
2802 // a diagnostic that it is being treated as a pointer.
2803 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2804 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2805 QualType ArrayTy = PVD->getOriginalType();
2806 QualType PointerTy = PVD->getType();
2807 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2808 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2809 << RangeLoc << PVD << ArrayTy << PointerTy;
2810 Diag(PVD->getLocation(), diag::note_declared_at);
2811 return StmtError();
2812 }
2813 }
2814 }
2815
2816 // If building the range failed, try dereferencing the range expression
2817 // unless a diagnostic was issued or the end function is problematic.
2818 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2819 CoawaitLoc, InitStmt,
2820 LoopVarDecl, ColonLoc,
2821 Range, RangeLoc,
2822 RParenLoc);
2823 if (SR.isInvalid() || SR.isUsable())
2824 return SR;
2825 }
2826
2827 // Otherwise, emit diagnostics if we haven't already.
2828 if (RangeStatus == FRS_NoViableFunction) {
2829 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2830 CandidateSet.NoteCandidates(
2831 PartialDiagnosticAt(Range->getBeginLoc(),
2832 PDiag(diag::err_for_range_invalid)
2833 << RangeLoc << Range->getType()
2834 << BEFFailure),
2835 *this, OCD_AllCandidates, Range);
2836 }
2837 // Return an error if no fix was discovered.
2838 if (RangeStatus != FRS_Success)
2839 return StmtError();
2840 }
2841
2842 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2843 "invalid range expression in for loop");
2844
2845 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2846 // C++1z removes this restriction.
2847 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2848 if (!Context.hasSameType(BeginType, EndType)) {
2849 Diag(RangeLoc, getLangOpts().CPlusPlus17
2850 ? diag::warn_for_range_begin_end_types_differ
2851 : diag::ext_for_range_begin_end_types_differ)
2852 << BeginType << EndType;
2853 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2854 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2855 }
2856
2857 BeginDeclStmt =
2858 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2859 EndDeclStmt =
2860 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2861
2862 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2863 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2864 VK_LValue, ColonLoc);
2865 if (BeginRef.isInvalid())
2866 return StmtError();
2867
2868 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2869 VK_LValue, ColonLoc);
2870 if (EndRef.isInvalid())
2871 return StmtError();
2872
2873 // Build and check __begin != __end expression.
2874 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2875 BeginRef.get(), EndRef.get());
2876 if (!NotEqExpr.isInvalid())
2877 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2878 if (!NotEqExpr.isInvalid())
2879 NotEqExpr =
2880 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2881 if (NotEqExpr.isInvalid()) {
2882 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2883 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2884 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2885 if (!Context.hasSameType(BeginType, EndType))
2886 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2887 return StmtError();
2888 }
2889
2890 // Build and check ++__begin expression.
2891 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2892 VK_LValue, ColonLoc);
2893 if (BeginRef.isInvalid())
2894 return StmtError();
2895
2896 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2897 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2898 // FIXME: getCurScope() should not be used during template instantiation.
2899 // We should pick up the set of unqualified lookup results for operator
2900 // co_await during the initial parse.
2901 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2902 if (!IncrExpr.isInvalid())
2903 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2904 if (IncrExpr.isInvalid()) {
2905 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2906 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2907 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2908 return StmtError();
2909 }
2910
2911 // Build and check *__begin expression.
2912 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2913 VK_LValue, ColonLoc);
2914 if (BeginRef.isInvalid())
2915 return StmtError();
2916
2917 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2918 if (DerefExpr.isInvalid()) {
2919 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2920 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2921 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2922 return StmtError();
2923 }
2924
2925 // Attach *__begin as initializer for VD. Don't touch it if we're just
2926 // trying to determine whether this would be a valid range.
2927 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2928 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2929 if (LoopVar->isInvalidDecl() ||
2930 (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
2931 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2932 }
2933 }
2934
2935 // Don't bother to actually allocate the result if we're just trying to
2936 // determine whether it would be valid.
2937 if (Kind == BFRK_Check)
2938 return StmtResult();
2939
2940 // In OpenMP loop region loop control variable must be private. Perform
2941 // analysis of first part (if any).
2942 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
2943 OpenMP().ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
2944
2945 return new (Context) CXXForRangeStmt(
2946 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2947 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2948 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2949 ColonLoc, RParenLoc);
2950}
2951
2952// Warn when the loop variable is a const reference that creates a copy.
2953// Suggest using the non-reference type for copies. If a copy can be prevented
2954// suggest the const reference type that would do so.
2955// For instance, given "for (const &Foo : Range)", suggest
2956// "for (const Foo : Range)" to denote a copy is made for the loop. If
2957// possible, also suggest "for (const &Bar : Range)" if this type prevents
2958// the copy altogether.
2960 const VarDecl *VD,
2961 QualType RangeInitType) {
2962 const Expr *InitExpr = VD->getInit();
2963 if (!InitExpr)
2964 return;
2965
2966 QualType VariableType = VD->getType();
2967
2968 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2969 if (!Cleanups->cleanupsHaveSideEffects())
2970 InitExpr = Cleanups->getSubExpr();
2971
2972 const MaterializeTemporaryExpr *MTE =
2973 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2974
2975 // No copy made.
2976 if (!MTE)
2977 return;
2978
2979 const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
2980
2981 // Searching for either UnaryOperator for dereference of a pointer or
2982 // CXXOperatorCallExpr for handling iterators.
2983 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2984 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2985 E = CCE->getArg(0);
2986 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2987 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2988 E = ME->getBase();
2989 } else {
2990 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2991 E = MTE->getSubExpr();
2992 }
2993 E = E->IgnoreImpCasts();
2994 }
2995
2996 QualType ReferenceReturnType;
2997 if (isa<UnaryOperator>(E)) {
2998 ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
2999 } else {
3000 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
3001 const FunctionDecl *FD = Call->getDirectCallee();
3002 QualType ReturnType = FD->getReturnType();
3003 if (ReturnType->isReferenceType())
3004 ReferenceReturnType = ReturnType;
3005 }
3006
3007 if (!ReferenceReturnType.isNull()) {
3008 // Loop variable creates a temporary. Suggest either to go with
3009 // non-reference loop variable to indicate a copy is made, or
3010 // the correct type to bind a const reference.
3011 SemaRef.Diag(VD->getLocation(),
3012 diag::warn_for_range_const_ref_binds_temp_built_from_ref)
3013 << VD << VariableType << ReferenceReturnType;
3014 QualType NonReferenceType = VariableType.getNonReferenceType();
3015 NonReferenceType.removeLocalConst();
3016 QualType NewReferenceType =
3018 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
3019 << NonReferenceType << NewReferenceType << VD->getSourceRange()
3021 } else if (!VariableType->isRValueReferenceType()) {
3022 // The range always returns a copy, so a temporary is always created.
3023 // Suggest removing the reference from the loop variable.
3024 // If the type is a rvalue reference do not warn since that changes the
3025 // semantic of the code.
3026 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
3027 << VD << RangeInitType;
3028 QualType NonReferenceType = VariableType.getNonReferenceType();
3029 NonReferenceType.removeLocalConst();
3030 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
3031 << NonReferenceType << VD->getSourceRange()
3033 }
3034}
3035
3036/// Determines whether the @p VariableType's declaration is a record with the
3037/// clang::trivial_abi attribute.
3038static bool hasTrivialABIAttr(QualType VariableType) {
3039 if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
3040 return RD->hasAttr<TrivialABIAttr>();
3041
3042 return false;
3043}
3044
3045// Warns when the loop variable can be changed to a reference type to
3046// prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
3047// "for (const Foo &x : Range)" if this form does not make a copy.
3049 const VarDecl *VD) {
3050 const Expr *InitExpr = VD->getInit();
3051 if (!InitExpr)
3052 return;
3053
3054 QualType VariableType = VD->getType();
3055
3056 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
3057 if (!CE->getConstructor()->isCopyConstructor())
3058 return;
3059 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
3060 if (CE->getCastKind() != CK_LValueToRValue)
3061 return;
3062 } else {
3063 return;
3064 }
3065
3066 // Small trivially copyable types are cheap to copy. Do not emit the
3067 // diagnostic for these instances. 64 bytes is a common size of a cache line.
3068 // (The function `getTypeSize` returns the size in bits.)
3069 ASTContext &Ctx = SemaRef.Context;
3070 if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
3071 (VariableType.isTriviallyCopyConstructibleType(Ctx) ||
3072 hasTrivialABIAttr(VariableType)))
3073 return;
3074
3075 // Suggest changing from a const variable to a const reference variable
3076 // if doing so will prevent a copy.
3077 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
3078 << VD << VariableType;
3079 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
3080 << SemaRef.Context.getLValueReferenceType(VariableType)
3081 << VD->getSourceRange()
3083}
3084
3085/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3086/// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
3087/// using "const foo x" to show that a copy is made
3088/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3089/// Suggest either "const bar x" to keep the copying or "const foo& x" to
3090/// prevent the copy.
3091/// 3) for (const foo x : foos) where x is constructed from a reference foo.
3092/// Suggest "const foo &x" to prevent the copy.
3094 const CXXForRangeStmt *ForStmt) {
3095 if (SemaRef.inTemplateInstantiation())
3096 return;
3097
3098 if (SemaRef.Diags.isIgnored(
3099 diag::warn_for_range_const_ref_binds_temp_built_from_ref,
3100 ForStmt->getBeginLoc()) &&
3101 SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
3102 ForStmt->getBeginLoc()) &&
3103 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
3104 ForStmt->getBeginLoc())) {
3105 return;
3106 }
3107
3108 const VarDecl *VD = ForStmt->getLoopVariable();
3109 if (!VD)
3110 return;
3111
3112 QualType VariableType = VD->getType();
3113
3114 if (VariableType->isIncompleteType())
3115 return;
3116
3117 const Expr *InitExpr = VD->getInit();
3118 if (!InitExpr)
3119 return;
3120
3121 if (InitExpr->getExprLoc().isMacroID())
3122 return;
3123
3124 if (VariableType->isReferenceType()) {
3126 ForStmt->getRangeInit()->getType());
3127 } else if (VariableType.isConstQualified()) {
3129 }
3130}
3131
3132/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
3133/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
3134/// body cannot be performed until after the type of the range variable is
3135/// determined.
3137 if (!S || !B)
3138 return StmtError();
3139
3140 if (isa<ObjCForCollectionStmt>(S))
3141 return ObjC().FinishObjCForCollectionStmt(S, B);
3142
3143 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
3144 ForStmt->setBody(B);
3145
3147 diag::warn_empty_range_based_for_body);
3148
3150
3151 return S;
3152}
3153
3155 SourceLocation LabelLoc,
3156 LabelDecl *TheDecl) {
3158
3159 // If this goto is in a compute construct scope, we need to make sure we check
3160 // gotos in/out.
3161 if (getCurScope()->isInOpenACCComputeConstructScope())
3163
3164 TheDecl->markUsed(Context);
3165 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
3166}
3167
3170 Expr *E) {
3171 // Convert operand to void*
3172 if (!E->isTypeDependent()) {
3173 QualType ETy = E->getType();
3175 ExprResult ExprRes = E;
3176 AssignConvertType ConvTy =
3177 CheckSingleAssignmentConstraints(DestTy, ExprRes);
3178 if (ExprRes.isInvalid())
3179 return StmtError();
3180 E = ExprRes.get();
3181 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
3182 return StmtError();
3183 }
3184
3185 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
3186 if (ExprRes.isInvalid())
3187 return StmtError();
3188 E = ExprRes.get();
3189
3191
3192 // If this goto is in a compute construct scope, we need to make sure we
3193 // check gotos in/out.
3194 if (getCurScope()->isInOpenACCComputeConstructScope())
3196
3197 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
3198}
3199
3201 const Scope &DestScope) {
3202 if (!S.CurrentSEHFinally.empty() &&
3203 DestScope.Contains(*S.CurrentSEHFinally.back())) {
3204 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
3205 }
3206}
3207
3210 Scope *S = CurScope->getContinueParent();
3211 if (!S) {
3212 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3213 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
3214 }
3215 if (S->isConditionVarScope()) {
3216 // We cannot 'continue;' from within a statement expression in the
3217 // initializer of a condition variable because we would jump past the
3218 // initialization of that variable.
3219 return StmtError(Diag(ContinueLoc, diag::err_continue_from_cond_var_init));
3220 }
3221
3222 // A 'continue' that would normally have execution continue on a block outside
3223 // of a compute construct counts as 'branching out of' the compute construct,
3224 // so diagnose here.
3225 if (S->isOpenACCComputeConstructScope())
3226 return StmtError(
3227 Diag(ContinueLoc, diag::err_acc_branch_in_out_compute_construct)
3228 << /*branch*/ 0 << /*out of */ 0);
3229
3230 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
3231
3232 return new (Context) ContinueStmt(ContinueLoc);
3233}
3234
3237 Scope *S = CurScope->getBreakParent();
3238 if (!S) {
3239 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3240 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
3241 }
3242 if (S->isOpenMPLoopScope())
3243 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
3244 << "break");
3245
3246 // OpenACC doesn't allow 'break'ing from a compute construct, so diagnose if
3247 // we are trying to do so. This can come in 2 flavors: 1-the break'able thing
3248 // (besides the compute construct) 'contains' the compute construct, at which
3249 // point the 'break' scope will be the compute construct. Else it could be a
3250 // loop of some sort that has a direct parent of the compute construct.
3251 // However, a 'break' in a 'switch' marked as a compute construct doesn't
3252 // count as 'branch out of' the compute construct.
3253 if (S->isOpenACCComputeConstructScope() ||
3254 (S->isLoopScope() && S->getParent() &&
3255 S->getParent()->isOpenACCComputeConstructScope()))
3256 return StmtError(
3257 Diag(BreakLoc, diag::err_acc_branch_in_out_compute_construct)
3258 << /*branch*/ 0 << /*out of */ 0);
3259
3260 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
3261
3262 return new (Context) BreakStmt(BreakLoc);
3263}
3264
3265/// Determine whether the given expression might be move-eligible or
3266/// copy-elidable in either a (co_)return statement or throw expression,
3267/// without considering function return type, if applicable.
3268///
3269/// \param E The expression being returned from the function or block,
3270/// being thrown, or being co_returned from a coroutine. This expression
3271/// might be modified by the implementation.
3272///
3273/// \param Mode Overrides detection of current language mode
3274/// and uses the rules for C++23.
3275///
3276/// \returns An aggregate which contains the Candidate and isMoveEligible
3277/// and isCopyElidable methods. If Candidate is non-null, it means
3278/// isMoveEligible() would be true under the most permissive language standard.
3281 if (!E)
3282 return NamedReturnInfo();
3283 // - in a return statement in a function [where] ...
3284 // ... the expression is the name of a non-volatile automatic object ...
3285 const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
3286 if (!DR || DR->refersToEnclosingVariableOrCapture())
3287 return NamedReturnInfo();
3288 const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
3289 if (!VD)
3290 return NamedReturnInfo();
3291 if (VD->getInit() && VD->getInit()->containsErrors())
3292 return NamedReturnInfo();
3294 if (Res.Candidate && !E->isXValue() &&
3299 CK_NoOp, E, nullptr, VK_XValue,
3301 }
3302 return Res;
3303}
3304
3305/// Determine whether the given NRVO candidate variable is move-eligible or
3306/// copy-elidable, without considering function return type.
3307///
3308/// \param VD The NRVO candidate variable.
3309///
3310/// \returns An aggregate which contains the Candidate and isMoveEligible
3311/// and isCopyElidable methods. If Candidate is non-null, it means
3312/// isMoveEligible() would be true under the most permissive language standard.
3315
3316 // C++20 [class.copy.elision]p3:
3317 // - in a return statement in a function with ...
3318 // (other than a function ... parameter)
3319 if (VD->getKind() == Decl::ParmVar)
3321 else if (VD->getKind() != Decl::Var)
3322 return NamedReturnInfo();
3323
3324 // (other than ... a catch-clause parameter)
3325 if (VD->isExceptionVariable())
3327
3328 // ...automatic...
3329 if (!VD->hasLocalStorage())
3330 return NamedReturnInfo();
3331
3332 // We don't want to implicitly move out of a __block variable during a return
3333 // because we cannot assume the variable will no longer be used.
3334 if (VD->hasAttr<BlocksAttr>())
3335 return NamedReturnInfo();
3336
3337 QualType VDType = VD->getType();
3338 if (VDType->isObjectType()) {
3339 // C++17 [class.copy.elision]p3:
3340 // ...non-volatile automatic object...
3341 if (VDType.isVolatileQualified())
3342 return NamedReturnInfo();
3343 } else if (VDType->isRValueReferenceType()) {
3344 // C++20 [class.copy.elision]p3:
3345 // ...either a non-volatile object or an rvalue reference to a non-volatile
3346 // object type...
3347 QualType VDReferencedType = VDType.getNonReferenceType();
3348 if (VDReferencedType.isVolatileQualified() ||
3349 !VDReferencedType->isObjectType())
3350 return NamedReturnInfo();
3352 } else {
3353 return NamedReturnInfo();
3354 }
3355
3356 // Variables with higher required alignment than their type's ABI
3357 // alignment cannot use NRVO.
3358 if (!VD->hasDependentAlignment() &&
3361
3362 return Info;
3363}
3364
3365/// Updates given NamedReturnInfo's move-eligible and
3366/// copy-elidable statuses, considering the function
3367/// return type criteria as applicable to return statements.
3368///
3369/// \param Info The NamedReturnInfo object to update.
3370///
3371/// \param ReturnType This is the return type of the function.
3372/// \returns The copy elision candidate, in case the initial return expression
3373/// was copy elidable, or nullptr otherwise.
3375 QualType ReturnType) {
3376 if (!Info.Candidate)
3377 return nullptr;
3378
3379 auto invalidNRVO = [&] {
3380 Info = NamedReturnInfo();
3381 return nullptr;
3382 };
3383
3384 // If we got a non-deduced auto ReturnType, we are in a dependent context and
3385 // there is no point in allowing copy elision since we won't have it deduced
3386 // by the point the VardDecl is instantiated, which is the last chance we have
3387 // of deciding if the candidate is really copy elidable.
3388 if ((ReturnType->getTypeClass() == Type::TypeClass::Auto &&
3389 ReturnType->isCanonicalUnqualified()) ||
3390 ReturnType->isSpecificBuiltinType(BuiltinType::Dependent))
3391 return invalidNRVO();
3392
3393 if (!ReturnType->isDependentType()) {
3394 // - in a return statement in a function with ...
3395 // ... a class return type ...
3396 if (!ReturnType->isRecordType())
3397 return invalidNRVO();
3398
3399 QualType VDType = Info.Candidate->getType();
3400 // ... the same cv-unqualified type as the function return type ...
3401 // When considering moving this expression out, allow dissimilar types.
3402 if (!VDType->isDependentType() &&
3403 !Context.hasSameUnqualifiedType(ReturnType, VDType))
3405 }
3406 return Info.isCopyElidable() ? Info.Candidate : nullptr;
3407}
3408
3409/// Verify that the initialization sequence that was picked for the
3410/// first overload resolution is permissible under C++98.
3411///
3412/// Reject (possibly converting) constructors not taking an rvalue reference,
3413/// or user conversion operators which are not ref-qualified.
3414static bool
3416 const InitializationSequence &Seq) {
3417 const auto *Step = llvm::find_if(Seq.steps(), [](const auto &Step) {
3418 return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3419 Step.Kind == InitializationSequence::SK_UserConversion;
3420 });
3421 if (Step != Seq.step_end()) {
3422 const auto *FD = Step->Function.Function;
3423 if (isa<CXXConstructorDecl>(FD)
3425 : cast<CXXMethodDecl>(FD)->getRefQualifier() == RQ_None)
3426 return false;
3427 }
3428 return true;
3429}
3430
3431/// Perform the initialization of a potentially-movable value, which
3432/// is the result of return value.
3433///
3434/// This routine implements C++20 [class.copy.elision]p3, which attempts to
3435/// treat returned lvalues as rvalues in certain cases (to prefer move
3436/// construction), then falls back to treating them as lvalues if that failed.
3438 const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value,
3439 bool SupressSimplerImplicitMoves) {
3440 if (getLangOpts().CPlusPlus &&
3441 (!getLangOpts().CPlusPlus23 || SupressSimplerImplicitMoves) &&
3442 NRInfo.isMoveEligible()) {
3444 CK_NoOp, Value, VK_XValue, FPOptionsOverride());
3445 Expr *InitExpr = &AsRvalue;
3446 auto Kind = InitializationKind::CreateCopy(Value->getBeginLoc(),
3447 Value->getBeginLoc());
3448 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3449 auto Res = Seq.getFailedOverloadResult();
3450 if ((Res == OR_Success || Res == OR_Deleted) &&
3453 // Promote "AsRvalue" to the heap, since we now need this
3454 // expression node to persist.
3455 Value =
3457 nullptr, VK_XValue, FPOptionsOverride());
3458 // Complete type-checking the initialization of the return type
3459 // using the constructor we found.
3460 return Seq.Perform(*this, Entity, Kind, Value);
3461 }
3462 }
3463 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3464 // above, or overload resolution failed. Either way, we need to try
3465 // (again) now with the return value expression as written.
3467}
3468
3469/// Determine whether the declared return type of the specified function
3470/// contains 'auto'.
3472 const FunctionProtoType *FPT =
3474 return FPT->getReturnType()->isUndeducedType();
3475}
3476
3477/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3478/// for capturing scopes.
3479///
3481 Expr *RetValExp,
3482 NamedReturnInfo &NRInfo,
3483 bool SupressSimplerImplicitMoves) {
3484 // If this is the first return we've seen, infer the return type.
3485 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3486 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3487 QualType FnRetType = CurCap->ReturnType;
3488 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3489 if (CurLambda && CurLambda->CallOperator->getType().isNull())
3490 return StmtError();
3491 bool HasDeducedReturnType =
3492 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3493
3494 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3495 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3496 if (RetValExp) {
3497 ExprResult ER =
3498 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3499 if (ER.isInvalid())
3500 return StmtError();
3501 RetValExp = ER.get();
3502 }
3503 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3504 /* NRVOCandidate=*/nullptr);
3505 }
3506
3507 if (HasDeducedReturnType) {
3508 FunctionDecl *FD = CurLambda->CallOperator;
3509 // If we've already decided this lambda is invalid, e.g. because
3510 // we saw a `return` whose expression had an error, don't keep
3511 // trying to deduce its return type.
3512 if (FD->isInvalidDecl())
3513 return StmtError();
3514 // In C++1y, the return type may involve 'auto'.
3515 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3516 if (CurCap->ReturnType.isNull())
3517 CurCap->ReturnType = FD->getReturnType();
3518
3519 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3520 assert(AT && "lost auto type from lambda return type");
3521 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3522 FD->setInvalidDecl();
3523 // FIXME: preserve the ill-formed return expression.
3524 return StmtError();
3525 }
3526 CurCap->ReturnType = FnRetType = FD->getReturnType();
3527 } else if (CurCap->HasImplicitReturnType) {
3528 // For blocks/lambdas with implicit return types, we check each return
3529 // statement individually, and deduce the common return type when the block
3530 // or lambda is completed.
3531 // FIXME: Fold this into the 'auto' codepath above.
3532 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3534 if (Result.isInvalid())
3535 return StmtError();
3536 RetValExp = Result.get();
3537
3538 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3539 // when deducing a return type for a lambda-expression (or by extension
3540 // for a block). These rules differ from the stated C++11 rules only in
3541 // that they remove top-level cv-qualifiers.
3543 FnRetType = RetValExp->getType().getUnqualifiedType();
3544 else
3545 FnRetType = CurCap->ReturnType = Context.DependentTy;
3546 } else {
3547 if (RetValExp) {
3548 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3549 // initializer list, because it is not an expression (even
3550 // though we represent it as one). We still deduce 'void'.
3551 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3552 << RetValExp->getSourceRange();
3553 }
3554
3555 FnRetType = Context.VoidTy;
3556 }
3557
3558 // Although we'll properly infer the type of the block once it's completed,
3559 // make sure we provide a return type now for better error recovery.
3560 if (CurCap->ReturnType.isNull())
3561 CurCap->ReturnType = FnRetType;
3562 }
3563 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
3564
3565 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3566 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
3567 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3568 return StmtError();
3569 }
3570 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3571 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3572 return StmtError();
3573 } else {
3574 assert(CurLambda && "unknown kind of captured scope");
3575 if (CurLambda->CallOperator->getType()
3576 ->castAs<FunctionType>()
3577 ->getNoReturnAttr()) {
3578 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3579 return StmtError();
3580 }
3581 }
3582
3583 // Otherwise, verify that this result type matches the previous one. We are
3584 // pickier with blocks than for normal functions because we don't have GCC
3585 // compatibility to worry about here.
3586 if (FnRetType->isDependentType()) {
3587 // Delay processing for now. TODO: there are lots of dependent
3588 // types we can conclusively prove aren't void.
3589 } else if (FnRetType->isVoidType()) {
3590 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3591 !(getLangOpts().CPlusPlus &&
3592 (RetValExp->isTypeDependent() ||
3593 RetValExp->getType()->isVoidType()))) {
3594 if (!getLangOpts().CPlusPlus &&
3595 RetValExp->getType()->isVoidType())
3596 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3597 else {
3598 Diag(ReturnLoc, diag::err_return_block_has_expr);
3599 RetValExp = nullptr;
3600 }
3601 }
3602 } else if (!RetValExp) {
3603 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3604 } else if (!RetValExp->isTypeDependent()) {
3605 // we have a non-void block with an expression, continue checking
3606
3607 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3608 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3609 // function return.
3610
3611 // In C++ the return statement is handled via a copy initialization.
3612 // the C version of which boils down to CheckSingleAssignmentConstraints.
3613 InitializedEntity Entity =
3614 InitializedEntity::InitializeResult(ReturnLoc, FnRetType);
3616 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
3617 if (Res.isInvalid()) {
3618 // FIXME: Cleanup temporaries here, anyway?
3619 return StmtError();
3620 }
3621 RetValExp = Res.get();
3622 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3623 }
3624
3625 if (RetValExp) {
3626 ExprResult ER =
3627 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3628 if (ER.isInvalid())
3629 return StmtError();
3630 RetValExp = ER.get();
3631 }
3632 auto *Result =
3633 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3634
3635 // If we need to check for the named return value optimization,
3636 // or if we need to infer the return type,
3637 // save the return statement in our scope for later processing.
3638 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3639 FunctionScopes.back()->Returns.push_back(Result);
3640
3641 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3642 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3643
3644 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap);
3645 CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
3646 RetValExp->containsErrors())
3647 CurBlock->TheDecl->setInvalidDecl();
3648
3649 return Result;
3650}
3651
3652namespace {
3653/// Marks all typedefs in all local classes in a type referenced.
3654///
3655/// In a function like
3656/// auto f() {
3657/// struct S { typedef int a; };
3658/// return S();
3659/// }
3660///
3661/// the local type escapes and could be referenced in some TUs but not in
3662/// others. Pretend that all local typedefs are always referenced, to not warn
3663/// on this. This isn't necessary if f has internal linkage, or the typedef
3664/// is private.
3665class LocalTypedefNameReferencer
3666 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3667public:
3668 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3669 bool VisitRecordType(const RecordType *RT);
3670private:
3671 Sema &S;
3672};
3673bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3674 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3675 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3676 R->isDependentType())
3677 return true;
3678 for (auto *TmpD : R->decls())
3679 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3680 if (T->getAccess() != AS_private || R->hasFriends())
3681 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3682 return true;
3683}
3684}
3685
3687 return FD->getTypeSourceInfo()
3688 ->getTypeLoc()
3690 .getReturnLoc();
3691}
3692
3693/// Deduce the return type for a function from a returned expression, per
3694/// C++1y [dcl.spec.auto]p6.
3696 SourceLocation ReturnLoc,
3697 Expr *RetExpr, const AutoType *AT) {
3698 // If this is the conversion function for a lambda, we choose to deduce its
3699 // type from the corresponding call operator, not from the synthesized return
3700 // statement within it. See Sema::DeduceReturnType.
3702 return false;
3703
3704 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3705 // If the deduction is for a return statement and the initializer is
3706 // a braced-init-list, the program is ill-formed.
3707 Diag(RetExpr->getExprLoc(),
3708 getCurLambda() ? diag::err_lambda_return_init_list
3709 : diag::err_auto_fn_return_init_list)
3710 << RetExpr->getSourceRange();
3711 return true;
3712 }
3713
3714 if (FD->isDependentContext()) {
3715 // C++1y [dcl.spec.auto]p12:
3716 // Return type deduction [...] occurs when the definition is
3717 // instantiated even if the function body contains a return
3718 // statement with a non-type-dependent operand.
3719 assert(AT->isDeduced() && "should have deduced to dependent type");
3720 return false;
3721 }
3722
3723 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3724 // In the case of a return with no operand, the initializer is considered
3725 // to be void().
3727 if (!RetExpr) {
3728 // For a function with a deduced result type to return with omitted
3729 // expression, the result type as written must be 'auto' or
3730 // 'decltype(auto)', possibly cv-qualified or constrained, but not
3731 // ref-qualified.
3732 if (!OrigResultType.getType()->getAs<AutoType>()) {
3733 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3734 << OrigResultType.getType();
3735 return true;
3736 }
3737 RetExpr = &VoidVal;
3738 }
3739
3740 QualType Deduced = AT->getDeducedType();
3741 {
3742 // Otherwise, [...] deduce a value for U using the rules of template
3743 // argument deduction.
3744 auto RetExprLoc = RetExpr->getExprLoc();
3745 TemplateDeductionInfo Info(RetExprLoc);
3746 SourceLocation TemplateSpecLoc;
3747 if (RetExpr->getType() == Context.OverloadTy) {
3748 auto FindResult = OverloadExpr::find(RetExpr);
3749 if (FindResult.Expression)
3750 TemplateSpecLoc = FindResult.Expression->getNameLoc();
3751 }
3752 TemplateSpecCandidateSet FailedTSC(TemplateSpecLoc);
3754 OrigResultType, RetExpr, Deduced, Info, /*DependentDeduction=*/false,
3755 /*IgnoreConstraints=*/false, &FailedTSC);
3757 return true;
3758 switch (Res) {
3760 break;
3762 return true;
3764 // If a function with a declared return type that contains a placeholder
3765 // type has multiple return statements, the return type is deduced for
3766 // each return statement. [...] if the type deduced is not the same in
3767 // each deduction, the program is ill-formed.
3768 const LambdaScopeInfo *LambdaSI = getCurLambda();
3769 if (LambdaSI && LambdaSI->HasImplicitReturnType)
3770 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3771 << Info.SecondArg << Info.FirstArg << true /*IsLambda*/;
3772 else
3773 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3774 << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg
3775 << Info.FirstArg;
3776 return true;
3777 }
3778 default:
3779 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3780 << OrigResultType.getType() << RetExpr->getType();
3781 FailedTSC.NoteCandidates(*this, RetExprLoc);
3782 return true;
3783 }
3784 }
3785
3786 // If a local type is part of the returned type, mark its fields as
3787 // referenced.
3788 LocalTypedefNameReferencer(*this).TraverseType(RetExpr->getType());
3789
3790 // CUDA: Kernel function must have 'void' return type.
3791 if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() &&
3792 !Deduced->isVoidType()) {
3793 Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3794 << FD->getType() << FD->getSourceRange();
3795 return true;
3796 }
3797
3798 if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced)
3799 // Update all declarations of the function to have the deduced return type.
3801
3802 return false;
3803}
3804
3807 Scope *CurScope) {
3808 // Correct typos, in case the containing function returns 'auto' and
3809 // RetValExp should determine the deduced type.
3811 RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true);
3812 if (RetVal.isInvalid())
3813 return StmtError();
3814
3815 if (getCurScope()->isInOpenACCComputeConstructScope())
3816 return StmtError(
3817 Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct)
3818 << /*return*/ 1 << /*out of */ 0);
3819
3820 StmtResult R =
3821 BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true);
3822 if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
3823 return R;
3824
3825 VarDecl *VD =
3826 const_cast<VarDecl *>(cast<ReturnStmt>(R.get())->getNRVOCandidate());
3827
3828 CurScope->updateNRVOCandidate(VD);
3829
3830 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3831
3832 return R;
3833}
3834
3836 const Expr *E) {
3837 if (!E || !S.getLangOpts().CPlusPlus23 || !S.getLangOpts().MSVCCompat)
3838 return false;
3839 const Decl *D = E->getReferencedDeclOfCallee();
3840 if (!D || !S.SourceMgr.isInSystemHeader(D->getLocation()))
3841 return false;
3842 for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
3843 if (DC->isStdNamespace())
3844 return true;
3845 }
3846 return false;
3847}
3848
3850 bool AllowRecovery) {
3851 // Check for unexpanded parameter packs.
3852 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3853 return StmtError();
3854
3855 // HACK: We suppress simpler implicit move here in msvc compatibility mode
3856 // just as a temporary work around, as the MSVC STL has issues with
3857 // this change.
3858 bool SupressSimplerImplicitMoves =
3861 RetValExp, SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
3863
3864 if (isa<CapturingScopeInfo>(getCurFunction()))
3865 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
3866 SupressSimplerImplicitMoves);
3867
3868 QualType FnRetType;
3869 QualType RelatedRetType;
3870 const AttrVec *Attrs = nullptr;
3871 bool isObjCMethod = false;
3872
3873 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3874 FnRetType = FD->getReturnType();
3875 if (FD->hasAttrs())
3876 Attrs = &FD->getAttrs();
3877 if (FD->isNoReturn())
3878 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD;
3879 if (FD->isMain() && RetValExp)
3880 if (isa<CXXBoolLiteralExpr>(RetValExp))
3881 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3882 << RetValExp->getSourceRange();
3883 if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
3884 if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) {
3885 if (RT->getDecl()->isOrContainsUnion())
3886 Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
3887 }
3888 }
3889 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3890 FnRetType = MD->getReturnType();
3891 isObjCMethod = true;
3892 if (MD->hasAttrs())
3893 Attrs = &MD->getAttrs();
3894 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3895 // In the implementation of a method with a related return type, the
3896 // type used to type-check the validity of return statements within the
3897 // method body is a pointer to the type of the class being implemented.
3898 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3899 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3900 }
3901 } else // If we don't have a function/method context, bail.
3902 return StmtError();
3903
3904 if (RetValExp) {
3905 const auto *ATy = dyn_cast<ArrayType>(RetValExp->getType());
3906 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
3907 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
3908 return StmtError();
3909 }
3910 }
3911
3912 // C++1z: discarded return statements are not considered when deducing a
3913 // return type.
3914 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3915 FnRetType->getContainedAutoType()) {
3916 if (RetValExp) {
3917 ExprResult ER =
3918 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3919 if (ER.isInvalid())
3920 return StmtError();
3921 RetValExp = ER.get();
3922 }
3923 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3924 /* NRVOCandidate=*/nullptr);
3925 }
3926
3927 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3928 // deduction.
3929 if (getLangOpts().CPlusPlus14) {
3930 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3931 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3932 // If we've already decided this function is invalid, e.g. because
3933 // we saw a `return` whose expression had an error, don't keep
3934 // trying to deduce its return type.
3935 // (Some return values may be needlessly wrapped in RecoveryExpr).
3936 if (FD->isInvalidDecl() ||
3937 DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3938 FD->setInvalidDecl();
3939 if (!AllowRecovery)
3940 return StmtError();
3941 // The deduction failure is diagnosed and marked, try to recover.
3942 if (RetValExp) {
3943 // Wrap return value with a recovery expression of the previous type.
3944 // If no deduction yet, use DependentTy.
3945 auto Recovery = CreateRecoveryExpr(
3946 RetValExp->getBeginLoc(), RetValExp->getEndLoc(), RetValExp,
3947 AT->isDeduced() ? FnRetType : QualType());
3948 if (Recovery.isInvalid())
3949 return StmtError();
3950 RetValExp = Recovery.get();
3951 } else {
3952 // Nothing to do: a ReturnStmt with no value is fine recovery.
3953 }
3954 } else {
3955 FnRetType = FD->getReturnType();
3956 }
3957 }
3958 }
3959 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
3960
3961 bool HasDependentReturnType = FnRetType->isDependentType();
3962
3963 ReturnStmt *Result = nullptr;
3964 if (FnRetType->isVoidType()) {
3965 if (RetValExp) {
3966 if (auto *ILE = dyn_cast<InitListExpr>(RetValExp)) {
3967 // We simply never allow init lists as the return value of void
3968 // functions. This is compatible because this was never allowed before,
3969 // so there's no legacy code to deal with.
3971 int FunctionKind = 0;
3972 if (isa<ObjCMethodDecl>(CurDecl))
3973 FunctionKind = 1;
3974 else if (isa<CXXConstructorDecl>(CurDecl))
3975 FunctionKind = 2;
3976 else if (isa<CXXDestructorDecl>(CurDecl))
3977 FunctionKind = 3;
3978
3979 Diag(ReturnLoc, diag::err_return_init_list)
3980 << CurDecl << FunctionKind << RetValExp->getSourceRange();
3981
3982 // Preserve the initializers in the AST.
3983 RetValExp = AllowRecovery
3984 ? CreateRecoveryExpr(ILE->getLBraceLoc(),
3985 ILE->getRBraceLoc(), ILE->inits())
3986 .get()
3987 : nullptr;
3988 } else if (!RetValExp->isTypeDependent()) {
3989 // C99 6.8.6.4p1 (ext_ since GCC warns)
3990 unsigned D = diag::ext_return_has_expr;
3991 if (RetValExp->getType()->isVoidType()) {
3993 if (isa<CXXConstructorDecl>(CurDecl) ||
3994 isa<CXXDestructorDecl>(CurDecl))
3995 D = diag::err_ctor_dtor_returns_void;
3996 else
3997 D = diag::ext_return_has_void_expr;
3998 }
3999 else {
4000 ExprResult Result = RetValExp;
4002 if (Result.isInvalid())
4003 return StmtError();
4004 RetValExp = Result.get();
4005 RetValExp = ImpCastExprToType(RetValExp,
4006 Context.VoidTy, CK_ToVoid).get();
4007 }
4008 // return of void in constructor/destructor is illegal in C++.
4009 if (D == diag::err_ctor_dtor_returns_void) {
4011 Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl)
4012 << RetValExp->getSourceRange();
4013 }
4014 // return (some void expression); is legal in C++.
4015 else if (D != diag::ext_return_has_void_expr ||
4018
4019 int FunctionKind = 0;
4020 if (isa<ObjCMethodDecl>(CurDecl))
4021 FunctionKind = 1;
4022 else if (isa<CXXConstructorDecl>(CurDecl))
4023 FunctionKind = 2;
4024 else if (isa<CXXDestructorDecl>(CurDecl))
4025 FunctionKind = 3;
4026
4027 Diag(ReturnLoc, D)
4028 << CurDecl << FunctionKind << RetValExp->getSourceRange();
4029 }
4030 }
4031
4032 if (RetValExp) {
4033 ExprResult ER =
4034 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
4035 if (ER.isInvalid())
4036 return StmtError();
4037 RetValExp = ER.get();
4038 }
4039 }
4040
4041 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
4042 /* NRVOCandidate=*/nullptr);
4043 } else if (!RetValExp && !HasDependentReturnType) {
4045
4046 if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) {
4047 // The intended return type might have been "void", so don't warn.
4048 } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
4049 // C++11 [stmt.return]p2
4050 Diag(ReturnLoc, diag::err_constexpr_return_missing_expr)
4051 << FD << FD->isConsteval();
4052 FD->setInvalidDecl();
4053 } else {
4054 // C99 6.8.6.4p1 (ext_ since GCC warns)
4055 // C90 6.6.6.4p4
4056 unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
4057 : diag::warn_return_missing_expr;
4058 // Note that at this point one of getCurFunctionDecl() or
4059 // getCurMethodDecl() must be non-null (see above).
4060 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4061 "Not in a FunctionDecl or ObjCMethodDecl?");
4062 bool IsMethod = FD == nullptr;
4063 const NamedDecl *ND =
4064 IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD);
4065 Diag(ReturnLoc, DiagID) << ND << IsMethod;
4066 }
4067
4068 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
4069 /* NRVOCandidate=*/nullptr);
4070 } else {
4071 assert(RetValExp || HasDependentReturnType);
4072 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
4073
4074 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4075 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4076 // function return.
4077
4078 // In C++ the return statement is handled via a copy initialization,
4079 // the C version of which boils down to CheckSingleAssignmentConstraints.
4080 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
4081 // we have a non-void function with an expression, continue checking
4082 InitializedEntity Entity =
4083 InitializedEntity::InitializeResult(ReturnLoc, RetType);
4085 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
4086 if (Res.isInvalid() && AllowRecovery)
4087 Res = CreateRecoveryExpr(RetValExp->getBeginLoc(),
4088 RetValExp->getEndLoc(), RetValExp, RetType);
4089 if (Res.isInvalid()) {
4090 // FIXME: Clean up temporaries here anyway?
4091 return StmtError();
4092 }
4093 RetValExp = Res.getAs<Expr>();
4094
4095 // If we have a related result type, we need to implicitly
4096 // convert back to the formal result type. We can't pretend to
4097 // initialize the result again --- we might end double-retaining
4098 // --- so instead we initialize a notional temporary.
4099 if (!RelatedRetType.isNull()) {
4101 FnRetType);
4102 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
4103 if (Res.isInvalid()) {
4104 // FIXME: Clean up temporaries here anyway?
4105 return StmtError();
4106 }
4107 RetValExp = Res.getAs<Expr>();
4108 }
4109
4110 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
4112 }
4113
4114 if (RetValExp) {
4115 ExprResult ER =
4116 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
4117 if (ER.isInvalid())
4118 return StmtError();
4119 RetValExp = ER.get();
4120 }
4121 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
4122 }
4123
4124 // If we need to check for the named return value optimization, save the
4125 // return statement in our scope for later processing.
4126 if (Result->getNRVOCandidate())
4127 FunctionScopes.back()->Returns.push_back(Result);
4128
4129 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
4130 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
4131
4132 return Result;
4133}
4134
4135/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
4136/// and creates a proper catch handler from them.
4139 Stmt *HandlerBlock) {
4140 // There's nothing to test that ActOnExceptionDecl didn't already test.
4141 return new (Context)
4142 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
4143}
4144
4145namespace {
4146class CatchHandlerType {
4147 QualType QT;
4148 LLVM_PREFERRED_TYPE(bool)
4149 unsigned IsPointer : 1;
4150
4151 // This is a special constructor to be used only with DenseMapInfo's
4152 // getEmptyKey() and getTombstoneKey() functions.
4153 friend struct llvm::DenseMapInfo<CatchHandlerType>;
4154 enum Unique { ForDenseMap };
4155 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
4156
4157public:
4158 /// Used when creating a CatchHandlerType from a handler type; will determine
4159 /// whether the type is a pointer or reference and will strip off the top
4160 /// level pointer and cv-qualifiers.
4161 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
4162 if (QT->isPointerType())
4163 IsPointer = true;
4164
4165 QT = QT.getUnqualifiedType();
4166 if (IsPointer || QT->isReferenceType())
4167 QT = QT->getPointeeType();
4168 }
4169
4170 /// Used when creating a CatchHandlerType from a base class type; pretends the
4171 /// type passed in had the pointer qualifier, does not need to get an
4172 /// unqualified type.
4173 CatchHandlerType(QualType QT, bool IsPointer)
4174 : QT(QT), IsPointer(IsPointer) {}
4175
4176 QualType underlying() const { return QT; }
4177 bool isPointer() const { return IsPointer; }
4178
4179 friend bool operator==(const CatchHandlerType &LHS,
4180 const CatchHandlerType &RHS) {
4181 // If the pointer qualification does not match, we can return early.
4182 if (LHS.IsPointer != RHS.IsPointer)
4183 return false;
4184 // Otherwise, check the underlying type without cv-qualifiers.
4185 return LHS.QT == RHS.QT;
4186 }
4187};
4188} // namespace
4189
4190namespace llvm {
4191template <> struct DenseMapInfo<CatchHandlerType> {
4192 static CatchHandlerType getEmptyKey() {
4193 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4194 CatchHandlerType::ForDenseMap);
4195 }
4196
4197 static CatchHandlerType getTombstoneKey() {
4198 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4199 CatchHandlerType::ForDenseMap);
4200 }
4201
4202 static unsigned getHashValue(const CatchHandlerType &Base) {
4203 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
4204 }
4205
4206 static bool isEqual(const CatchHandlerType &LHS,
4207 const CatchHandlerType &RHS) {
4208 return LHS == RHS;
4209 }
4210};
4211}
4212
4213namespace {
4214class CatchTypePublicBases {
4215 const llvm::DenseMap<QualType, CXXCatchStmt *> &TypesToCheck;
4216
4217 CXXCatchStmt *FoundHandler;
4218 QualType FoundHandlerType;
4219 QualType TestAgainstType;
4220
4221public:
4222 CatchTypePublicBases(const llvm::DenseMap<QualType, CXXCatchStmt *> &T,
4223 QualType QT)
4224 : TypesToCheck(T), FoundHandler(nullptr), TestAgainstType(QT) {}
4225
4226 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
4227 QualType getFoundHandlerType() const { return FoundHandlerType; }
4228
4229 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
4230 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
4231 QualType Check = S->getType().getCanonicalType();
4232 const auto &M = TypesToCheck;
4233 auto I = M.find(Check);
4234 if (I != M.end()) {
4235 // We're pretty sure we found what we need to find. However, we still
4236 // need to make sure that we properly compare for pointers and
4237 // references, to handle cases like:
4238 //
4239 // } catch (Base *b) {
4240 // } catch (Derived &d) {
4241 // }
4242 //
4243 // where there is a qualification mismatch that disqualifies this
4244 // handler as a potential problem.
4245 if (I->second->getCaughtType()->isPointerType() ==
4246 TestAgainstType->isPointerType()) {
4247 FoundHandler = I->second;
4248 FoundHandlerType = Check;
4249 return true;
4250 }
4251 }
4252 }
4253 return false;
4254 }
4255};
4256}
4257
4258/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4259/// handlers and creates a try statement from them.
4261 ArrayRef<Stmt *> Handlers) {
4262 const llvm::Triple &T = Context.getTargetInfo().getTriple();
4263 const bool IsOpenMPGPUTarget =
4264 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
4265 // Don't report an error if 'try' is used in system headers or in an OpenMP
4266 // target region compiled for a GPU architecture.
4267 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
4268 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
4269 // Delay error emission for the OpenMP device code.
4270 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4271 }
4272
4273 // In OpenMP target regions, we assume that catch is never reached on GPU
4274 // targets.
4275 if (IsOpenMPGPUTarget)
4276 targetDiag(TryLoc, diag::warn_try_not_valid_on_target) << T.str();
4277
4278 // Exceptions aren't allowed in CUDA device code.
4279 if (getLangOpts().CUDA)
4280 CUDA().DiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4281 << "try" << llvm::to_underlying(CUDA().CurrentTarget());
4282
4283 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4284 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4285
4287
4288 // C++ try is incompatible with SEH __try.
4289 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4290 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
4291 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4292 }
4293
4294 const unsigned NumHandlers = Handlers.size();
4295 assert(!Handlers.empty() &&
4296 "The parser shouldn't call this if there are no handlers.");
4297
4298 llvm::DenseMap<QualType, CXXCatchStmt *> HandledBaseTypes;
4299 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4300 for (unsigned i = 0; i < NumHandlers; ++i) {
4301 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4302
4303 // Diagnose when the handler is a catch-all handler, but it isn't the last
4304 // handler for the try block. [except.handle]p5. Also, skip exception
4305 // declarations that are invalid, since we can't usefully report on them.
4306 if (!H->getExceptionDecl()) {
4307 if (i < NumHandlers - 1)
4308 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4309 continue;
4310 } else if (H->getExceptionDecl()->isInvalidDecl())
4311 continue;
4312
4313 // Walk the type hierarchy to diagnose when this type has already been
4314 // handled (duplication), or cannot be handled (derivation inversion). We
4315 // ignore top-level cv-qualifiers, per [except.handle]p3
4316 CatchHandlerType HandlerCHT = H->getCaughtType().getCanonicalType();
4317
4318 // We can ignore whether the type is a reference or a pointer; we need the
4319 // underlying declaration type in order to get at the underlying record
4320 // decl, if there is one.
4321 QualType Underlying = HandlerCHT.underlying();
4322 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4323 if (!RD->hasDefinition())
4324 continue;
4325 // Check that none of the public, unambiguous base classes are in the
4326 // map ([except.handle]p1). Give the base classes the same pointer
4327 // qualification as the original type we are basing off of. This allows
4328 // comparison against the handler type using the same top-level pointer
4329 // as the original type.
4330 CXXBasePaths Paths;
4331 Paths.setOrigin(RD);
4332 CatchTypePublicBases CTPB(HandledBaseTypes,
4334 if (RD->lookupInBases(CTPB, Paths)) {
4335 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4336 if (!Paths.isAmbiguous(
4337 CanQualType::CreateUnsafe(CTPB.getFoundHandlerType()))) {
4339 diag::warn_exception_caught_by_earlier_handler)
4340 << H->getCaughtType();
4342 diag::note_previous_exception_handler)
4343 << Problem->getCaughtType();
4344 }
4345 }
4346 // Strip the qualifiers here because we're going to be comparing this
4347 // type to the base type specifiers of a class, which are ignored in a
4348 // base specifier per [class.derived.general]p2.
4349 HandledBaseTypes[Underlying.getUnqualifiedType()] = H;
4350 }
4351
4352 // Add the type the list of ones we have handled; diagnose if we've already
4353 // handled it.
4354 auto R = HandledTypes.insert(
4355 std::make_pair(H->getCaughtType().getCanonicalType(), H));
4356 if (!R.second) {
4357 const CXXCatchStmt *Problem = R.first->second;
4359 diag::warn_exception_caught_by_earlier_handler)
4360 << H->getCaughtType();
4362 diag::note_previous_exception_handler)
4363 << Problem->getCaughtType();
4364 }
4365 }
4366
4367 FSI->setHasCXXTry(TryLoc);
4368
4369 return CXXTryStmt::Create(Context, TryLoc, cast<CompoundStmt>(TryBlock),
4370 Handlers);
4371}
4372
4374 Stmt *TryBlock, Stmt *Handler) {
4375 assert(TryBlock && Handler);
4376
4378
4379 // SEH __try is incompatible with C++ try. Borland appears to support this,
4380 // however.
4381 if (!getLangOpts().Borland) {
4382 if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
4383 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
4384 Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here)
4386 ? "'try'"
4387 : "'@try'");
4388 }
4389 }
4390
4391 FSI->setHasSEHTry(TryLoc);
4392
4393 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4394 // track if they use SEH.
4395 DeclContext *DC = CurContext;
4396 while (DC && !DC->isFunctionOrMethod())
4397 DC = DC->getParent();
4398 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4399 if (FD)
4400 FD->setUsesSEHTry(true);
4401 else
4402 Diag(TryLoc, diag::err_seh_try_outside_functions);
4403
4404 // Reject __try on unsupported targets.
4406 Diag(TryLoc, diag::err_seh_try_unsupported);
4407
4408 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4409}
4410
4412 Stmt *Block) {
4413 assert(FilterExpr && Block);
4414 QualType FTy = FilterExpr->getType();
4415 if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4416 return StmtError(
4417 Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4418 << FTy);
4419 }
4420 return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
4421}
4422
4424 CurrentSEHFinally.push_back(CurScope);
4425}
4426
4428 CurrentSEHFinally.pop_back();
4429}
4430
4432 assert(Block);
4433 CurrentSEHFinally.pop_back();
4435}
4436
4439 Scope *SEHTryParent = CurScope;
4440 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4441 SEHTryParent = SEHTryParent->getParent();
4442 if (!SEHTryParent)
4443 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4444 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4445
4446 return new (Context) SEHLeaveStmt(Loc);
4447}
4448
4450 bool IsIfExists,
4451 NestedNameSpecifierLoc QualifierLoc,
4452 DeclarationNameInfo NameInfo,
4453 Stmt *Nested)
4454{
4455 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4456 QualifierLoc, NameInfo,
4457 cast<CompoundStmt>(Nested));
4458}
4459
4460
4462 bool IsIfExists,
4463 CXXScopeSpec &SS,
4464 UnqualifiedId &Name,
4465 Stmt *Nested) {
4466 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4469 Nested);
4470}
4471
4474 unsigned NumParams) {
4475 DeclContext *DC = CurContext;
4476 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4477 DC = DC->getParent();
4478
4479 RecordDecl *RD = nullptr;
4480 if (getLangOpts().CPlusPlus)
4482 /*Id=*/nullptr);
4483 else
4485 /*Id=*/nullptr);
4486
4487 RD->setCapturedRecord();
4488 DC->addDecl(RD);
4489 RD->setImplicit();
4490 RD->startDefinition();
4491
4492 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4493 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4494 DC->addDecl(CD);
4495 return RD;
4496}
4497
4498static bool
4501 SmallVectorImpl<Expr *> &CaptureInits) {
4502 for (const sema::Capture &Cap : RSI->Captures) {
4503 if (Cap.isInvalid())
4504 continue;
4505
4506 // Form the initializer for the capture.
4508 RSI->CapRegionKind == CR_OpenMP);
4509
4510 // FIXME: Bail out now if the capture is not used and the initializer has
4511 // no side-effects.
4512
4513 // Create a field for this capture.
4514 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4515
4516 // Add the capture to our list of captures.
4517 if (Cap.isThisCapture()) {
4518 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4520 } else if (Cap.isVLATypeCapture()) {
4521 Captures.push_back(
4523 } else {
4524 assert(Cap.isVariableCapture() && "unknown kind of capture");
4525
4526 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4527 S.OpenMP().setOpenMPCaptureKind(Field, Cap.getVariable(),
4528 RSI->OpenMPLevel);
4529
4530 Captures.push_back(CapturedStmt::Capture(
4531 Cap.getLocation(),
4534 cast<VarDecl>(Cap.getVariable())));
4535 }
4536 CaptureInits.push_back(Init.get());
4537 }
4538 return false;
4539}
4540
4542 CapturedRegionKind Kind,
4543 unsigned NumParams) {
4544 CapturedDecl *CD = nullptr;
4545 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4546
4547 // Build the context parameter
4549 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4551 auto *Param =
4552 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4554 DC->addDecl(Param);
4555
4556 CD->setContextParam(0, Param);
4557
4558 // Enter the capturing scope for this captured region.
4559 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4560
4561 if (CurScope)
4562 PushDeclContext(CurScope, CD);
4563 else
4564 CurContext = CD;
4565
4568 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = false;
4569}
4570
4572 CapturedRegionKind Kind,
4574 unsigned OpenMPCaptureLevel) {
4575 CapturedDecl *CD = nullptr;
4576 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4577
4578 // Build the context parameter
4580 bool ContextIsFound = false;
4581 unsigned ParamNum = 0;
4582 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4583 E = Params.end();
4584 I != E; ++I, ++ParamNum) {
4585 if (I->second.isNull()) {
4586 assert(!ContextIsFound &&
4587 "null type has been found already for '__context' parameter");
4588 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4590 .withConst()
4591 .withRestrict();
4592 auto *Param =
4593 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4595 DC->addDecl(Param);
4596 CD->setContextParam(ParamNum, Param);
4597 ContextIsFound = true;
4598 } else {
4599 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4600 auto *Param =
4601 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4603 DC->addDecl(Param);
4604 CD->setParam(ParamNum, Param);
4605 }
4606 }
4607 assert(ContextIsFound && "no null type for '__context' parameter");
4608 if (!ContextIsFound) {
4609 // Add __context implicitly if it is not specified.
4610 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4612 auto *Param =
4613 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4615 DC->addDecl(Param);
4616 CD->setContextParam(ParamNum, Param);
4617 }
4618 // Enter the capturing scope for this captured region.
4619 PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
4620
4621 if (CurScope)
4622 PushDeclContext(CurScope, CD);
4623 else
4624 CurContext = CD;
4625
4628}
4629
4635 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4636
4639
4640 SmallVector<Decl*, 4> Fields(Record->fields());
4641 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4643}
4644
4646 // Leave the captured scope before we start creating captures in the
4647 // enclosing scope.
4652 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4653
4655 SmallVector<Expr *, 4> CaptureInits;
4656 if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4657 return StmtError();
4658
4659 CapturedDecl *CD = RSI->TheCapturedDecl;
4660 RecordDecl *RD = RSI->TheRecordDecl;
4661
4663 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4664 Captures, CaptureInits, CD, RD);
4665
4666 CD->setBody(Res->getCapturedStmt());
4667 RD->completeDefinition();
4668
4669 return Res;
4670}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
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:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
@ 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:2242
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:3471
static bool ObjCEnumerationCollection(Expr *Collection)
Definition: SemaStmt.cpp:2334
static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef, const VarDecl *VD)
Definition: SemaStmt.cpp:3048
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:2579
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:2959
static void DiagnoseForRangeVariableCopies(Sema &SemaRef, const CXXForRangeStmt *ForStmt)
DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
Definition: SemaStmt.cpp:3093
static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S, const Expr *E)
Definition: SemaStmt.cpp:3835
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:3415
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:2445
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:3038
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:4499
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:3200
Defines the Objective-C statement AST node classes.
enum clang::format::@1262::AnnotatingParser::Context::@343 ContextType
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
SourceLocation 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:182
SourceManager & getSourceManager()
Definition: ASTContext.h:705
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:2591
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
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:1119
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:1591
IdentifierTable & Idents
Definition: ASTContext.h:644
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:1119
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:2618
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2341
CanQualType VoidTy
Definition: ASTContext.h:1091
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
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:3518
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:5981
bool isDecltypeAuto() const
Definition: Type.h:6004
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4295
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition: Expr.h:4279
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
Expr * getLHS() const
Definition: Expr.h:3889
SourceLocation getExprLoc() const
Definition: Expr.h:3880
Expr * getRHS() const
Definition: Expr.h:3891
Opcode getOpcode() const
Definition: Expr.h:3884
BreakStmt - This represents a break.
Definition: Stmt.h:2980
SourceLocation getBreakLoc() const
Definition: Stmt.h:2989
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition: Expr.h:3771
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1487
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: StmtCXX.h:43
VarDecl * getExceptionDecl() const
Definition: StmtCXX.h:49
QualType getCaughtType() const
Definition: StmtCXX.cpp:19
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition: ExprCXX.h:1813
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2177
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, CompoundStmt *tryBlock, ArrayRef< Stmt * > handlers)
Definition: StmtCXX.cpp:25
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Decl * getCalleeDecl()
Definition: Expr.h:2984
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:4686
void setBody(Stmt *B)
Definition: Decl.cpp:5441
static DeclContext * castToDeclContext(const CapturedDecl *D)
Definition: Decl.h:4770
void setContextParam(unsigned i, ImplicitParamDecl *P)
Definition: Decl.h:4752
void setParam(unsigned i, ImplicitParamDecl *P)
Definition: Decl.h:4734
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition: Decl.cpp:5428
Describes the capture of either a variable, or 'this', or variable-length array type.
Definition: Stmt.h:3770
This captures a statement into a function.
Definition: Stmt.h:3757
Stmt * getCapturedStmt()
Retrieve the statement being captured.
Definition: Stmt.h:3861
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:1801
Expr * getLHS()
Definition: Stmt.h:1888
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:1900
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3483
CastKind getCastKind() const
Definition: Expr.h:3527
Expr * getSubExpr()
Definition: Expr.h:3533
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
bool body_empty() const
Definition: Stmt.h:1650
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:1669
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4211
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4202
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4206
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3556
ContinueStmt - This represents a continue.
Definition: Stmt.h:2950
SourceLocation getContinueLoc() const
Definition: Stmt.h:2959
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isFileContext() const
Definition: DeclBase.h:2137
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
bool isRecord() const
Definition: DeclBase.h:2146
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
bool isStdNamespace() const
Definition: DeclBase.cpp:1266
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1690
Decl * getSingleDecl()
Definition: DeclGroup.h:83
bool isSingleDecl() const
Definition: DeclGroup.h:80
bool isNull() const
Definition: DeclGroup.h:79
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getLocation() const
Definition: Expr.h:1336
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition: Stmt.h:1510
const Decl * getSingleDecl() const
Definition: Stmt.h:1512
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.h:1523
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:579
bool hasAttrs() const
Definition: DeclBase.h:524
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1019
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setLocation(SourceLocation L)
Definition: DeclBase.h:446
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AttrVec & getAttrs()
Definition: DeclBase.h:530
bool hasAttr() const
Definition: DeclBase.h:583
Kind getKind() const
Definition: DeclBase.h:448
SourceLocation getTypeSpecEndLoc() const
Definition: Decl.cpp:1991
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1985
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5968
bool isDeduced() const
Definition: Type.h:5969
SourceLocation getDefaultLoc() const
Definition: Stmt.h:1970
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:2725
Represents an enum.
Definition: Decl.h:3867
enumerator_range enumerators() const
Definition: Decl.h:4000
bool isClosed() const
Returns true if this enum is either annotated with enum_extensibility(closed) or isn't annotated with...
Definition: Decl.cpp:4891
bool isClosedNonFlag() const
Returns true if this enum is annotated with neither flag_enum nor enum_extensibility(open).
Definition: Decl.cpp:4901
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
EnumDecl * getDecl() const
Definition: Type.h:5582
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:3064
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:2589
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:3059
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:3055
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:3039
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:915
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1022
Represents a member of a struct/union/class.
Definition: Decl.h:3057
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:2781
void setBody(Stmt *S)
Definition: Stmt.h:2835
SourceLocation getRParenLoc() const
Definition: Stmt.h:2841
SourceLocation getBeginLoc() const
Definition: Stmt.h:2844
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1039
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
void setUsesSEHTry(bool UST)
Definition: Decl.h:2481
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition: Decl.cpp:3525
QualType getReturnType() const
Definition: Decl.h:2754
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2432
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3306
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4395
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2842
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
bool isConsteval() const
Definition: Decl.h:2444
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3485
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4581
QualType getReturnType() const
Definition: Type.h:4573
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4633
GotoStmt - This represents a direct goto.
Definition: Stmt.h:2862
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static IfStmt * Create(const ASTContext &Ctx, SourceLocation IL, IfStatementKind Kind, Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL, SourceLocation RPL, Stmt *Then, SourceLocation EL=SourceLocation(), Stmt *Else=nullptr)
Create an IfStmt.
Definition: Stmt.cpp:958
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
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:5379
IndirectGotoStmt - This represents an indirect goto.
Definition: Stmt.h:2901
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Describes the sequence of initializations required to initialize a given object or reference with a s...
Describes an entity that is being initialized.
static InitializedEntity InitializeResult(SourceLocation ReturnLoc, QualType Type)
Create the initialization entity for the result of a function.
static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD, QualType Type)
Create the initialization entity for a related result.
unsigned allocateManglingNumber() const
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp: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:2031
Represents the results of name lookup.
Definition: Lookup.h:46
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
bool isAmbiguous() const
Definition: Lookup.h:324
Representation of a Microsoft __if_exists or __if_not_exists statement with a dependent name.
Definition: StmtCXX.h:253
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4710
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition: ExprCXX.h:4727
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
Expr * getBase() const
Definition: Expr.h:3249
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
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:1119
A C++ nested-name-specifier augmented with source location information.
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1569
Represents Objective-C's collection statement.
Definition: StmtObjC.h:23
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: Type.h:7008
Wrapper for void* pointer.
Definition: Ownership.h:50
void * getAsOpaquePtr() const
Definition: Ownership.h:90
PtrTy get() const
Definition: Ownership.h:80
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1218
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3038
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
const Expr * getSubExpr() const
Definition: Expr.h:2145
Represents a parameter to a function.
Definition: Decl.h:1761
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:6305
ArrayRef< Expr * > semantics()
Definition: Expr.h:6384
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
QualType withRestrict() const
Definition: Type.h:1170
QualType withConst() const
Definition: Type.h:1154
bool isTriviallyCopyConstructibleType(const ASTContext &Context) const
Return true if this is a trivially copyable type.
Definition: Type.cpp:2734
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7560
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
void removeLocalConst()
Definition: Type.h:7467
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
Represents a struct/union/class.
Definition: Decl.h:4168
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5015
bool isOrContainsUnion() const
Returns whether this record is a union, or contains (at any nesting level) a union member.
Definition: Decl.cpp:5054
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5081
void setCapturedRecord()
Mark the record as a record for captured variables in CapturedStmt construct.
Definition: Decl.cpp:5050
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
void setRetValue(Expr *E)
Definition: Stmt.h:3052
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Definition: Stmt.cpp:1204
Expr * getRetValue()
Definition: Stmt.h:3050
static SEHExceptStmt * Create(const ASTContext &C, SourceLocation ExceptLoc, Expr *FilterExpr, Stmt *Block)
Definition: Stmt.cpp:1267
static SEHFinallyStmt * Create(const ASTContext &C, SourceLocation FinallyLoc, Stmt *Block)
Definition: Stmt.cpp:1275
Represents a __leave statement.
Definition: Stmt.h:3718
static SEHTryStmt * Create(const ASTContext &C, bool isCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
Definition: Stmt.cpp:1247
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
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:56
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:32
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body)
FinishObjCForCollectionStmt - Attach the body to a objective-C foreach statement.
Definition: SemaObjC.cpp:194
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:5811
bool isInvalid() const
Definition: Sema.h:5810
ExprResult release()
Definition: Sema.h:5757
Expr * get() const
Definition: Sema.h:5759
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9410
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6350
SmallVector< Scope *, 2 > CurrentSEHFinally
Stack of active SEH __finally scopes. Can be empty.
Definition: Sema.h:8401
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9703
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:688
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)
Definition: SemaExpr.cpp:15755
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested)
Definition: SemaStmt.cpp:4449
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:7297
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:1013
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope)
Definition: SemaStmt.cpp:4438
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:2227
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl)
Definition: SemaStmt.cpp:89
SemaCUDA & CUDA()
Definition: Sema.h:993
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17296
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:20261
@ 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:797
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:2251
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:3154
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope)
Definition: SemaStmt.cpp:3806
void setFunctionHasBranchIntoScope()
Definition: Sema.cpp:2302
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition: SemaStmt.cpp:464
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:17081
SimplerImplicitMoveMode
Definition: Sema.h:8525
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:1499
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:798
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13865
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1058
ASTContext & Context
Definition: Sema.h:848
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:20057
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14737
void ActOnCapturedRegionError()
Definition: SemaStmt.cpp:4630
SemaObjC & ObjC()
Definition: Sema.h:1003
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:67
@ AllowFold
Definition: Sema.h:5724
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition: Sema.h:517
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15710
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17722
StmtResult ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler)
Definition: SemaStmt.cpp:4373
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:645
ForRangeStatus
Definition: Sema.h:8278
@ FRS_Success
Definition: Sema.h:8279
@ FRS_DiagnosticIssued
Definition: Sema.h:8281
@ FRS_NoViableFunction
Definition: Sema.h:8280
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2208
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void setFunctionHasIndirectGoto()
Definition: Sema.cpp:2312
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:3279
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:638
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:512
void PopCompoundScope()
Definition: Sema.cpp:2289
@ UPPC_Expression
An arbitrary expression.
Definition: Sema.h:10709
const LangOptions & getLangOpts() const
Definition: Sema.h:510
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body)
Definition: SemaStmt.cpp:1720
Preprocessor & PP
Definition: Sema.h:847
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:846
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2366
void ActOnStartOfCompoundStmt(bool IsStmtExpr)
Definition: SemaStmt.cpp:395
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:3695
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19933
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const
Definition: SemaStmt.cpp:3686
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:3374
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1511
StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro=false)
Definition: SemaStmt.cpp:74
RecordDecl * CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams)
Definition: SemaStmt.cpp:4473
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams)
Definition: SemaStmt.cpp:4541
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:882
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2284
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14969
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:9725
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:2085
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:652
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5870
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6213
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo, bool SupressSimplerImplicitMoves)
ActOnCapScopeReturnStmt - Utility routine to type-check return statements for capturing scopes.
Definition: SemaStmt.cpp:3480
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6020
StmtResult ActOnCapturedRegionEnd(Stmt *S)
Definition: SemaStmt.cpp:4645
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:3169
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20849
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10402
SourceManager & getSourceManager() const
Definition: Sema.h:515
@ AA_Passing
Definition: Sema.h:5159
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:3437
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13959
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:2357
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery=false)
Definition: SemaStmt.cpp:3849
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15212
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition: Sema.cpp:2692
void setFunctionHasMustTail()
Definition: Sema.cpp:2317
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2307
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block)
Definition: SemaStmt.cpp:4431
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope)
Definition: SemaStmt.cpp:3209
@ CCEK_CaseValue
Expression in a case label.
Definition: Sema.h:7949
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:2616
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:4461
@ 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:4411
void ActOnAfterCompoundStatementLeadingPragmas()
Definition: SemaStmt.cpp:399
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:8831
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19080
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17800
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6364
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1330
StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList, Stmt *SubStmt)
Definition: SemaStmt.cpp:624
SourceManager & SourceMgr
Definition: Sema.h:851
DiagnosticsEngine & Diags
Definition: Sema.h:850
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope)
Definition: SemaStmt.cpp:3236
void ActOnStartSEHFinallyBlock()
Definition: SemaStmt.cpp:4423
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10684
void ActOnAbortSEHFinallyBlock()
Definition: SemaStmt.cpp:4427
void PopDeclContext()
Definition: SemaDecl.cpp:1337
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
BuildForRangeKind
Definition: Sema.h:8485
@ BFRK_Check
Determining whether a for-range statement could be built.
Definition: Sema.h:8493
@ BFRK_Build
Initial building of a for-range statement.
Definition: Sema.h:8487
@ BFRK_Rebuild
Instantiation or recovery rebuild of a for-range statement.
Definition: Sema.h:8490
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:4138
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:13438
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:16748
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1899
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:21042
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:4771
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:411
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:407
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef< Stmt * > Elts, bool isStmtExpr)
Definition: SemaStmt.cpp:415
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:20059
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:4260
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:516
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body)
FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
Definition: SemaStmt.cpp:3136
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:6652
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:1774
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2388
void setBody(Stmt *Body)
Definition: Stmt.h:2468
static SwitchStmt * Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a switch statement.
Definition: Stmt.cpp:1081
Expr * getCond()
Definition: Stmt.h:2451
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2525
void setAllEnumCasesCovered()
Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a switch over an enum value then ...
Definition: Stmt.h:2550
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3687
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3812
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4737
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:1575
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:7330
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:7341
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isVoidType() const
Definition: Type.h:7905
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2156
bool isRValueReferenceType() const
Definition: Type.h:7632
bool isArrayType() const
Definition: Type.h:7678
bool isPointerType() const
Definition: Type.h:7612
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2758
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7874
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2647
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8179
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8039
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2405
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2326
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isRecordType() const
Definition: Type.h:7706
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:918
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
void setARCPseudoStrong(bool PS)
Definition: Decl.h:1528
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1213
bool isExceptionVariable() const
Determine whether this variable is the exception variable in a C++ catch statememt or an Objective-C ...
Definition: Decl.h:1474
const Expr * getInit() const
Definition: Decl.h:1355
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
void setInit(Expr *I)
Definition: Decl.cpp:2454
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1240
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2683
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3747
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2584
static WhileStmt * Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body, SourceLocation WL, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a while statement.
Definition: Stmt.cpp:1143
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
enum clang::sema::FunctionScopeInfo::@243 FirstTryType
SourceLocation FirstSEHTryLoc
First SEH '__try' statement in the current function.
Definition: ScopeInfo.h:193
void setHasCXXTry(SourceLocation TryLoc)
Definition: ScopeInfo.h:465
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:1899
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
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:1762
@ 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:247
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:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
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:367
@ 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:123
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
bool isMoveEligible() const
Definition: Sema.h:8522
bool isCopyElidable() const
Definition: Sema.h:8523
const VarDecl * Candidate
Definition: Sema.h:8517
static CatchHandlerType getEmptyKey()
Definition: SemaStmt.cpp:4192
static CatchHandlerType getTombstoneKey()
Definition: SemaStmt.cpp:4197
static unsigned getHashValue(const CatchHandlerType &Base)
Definition: SemaStmt.cpp:4202
static bool isEqual(const CatchHandlerType &LHS, const CatchHandlerType &RHS)
Definition: SemaStmt.cpp:4206