Coverage Report

Created: 2022-07-16 07:03

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