Coverage Report

Created: 2022-01-22 13:19

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