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