Coverage Report

Created: 2021-08-24 07:12

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