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