Coverage Report

Created: 2020-02-25 14:32

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