Coverage Report

Created: 2024-01-17 10:31

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