Coverage Report

Created: 2023-11-11 10:31

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