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