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