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