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