xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Sema/SemaLambda.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg //  This file implements semantic analysis for C++ lambda expressions.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg #include "clang/Sema/DeclSpec.h"
137330f729Sjoerg #include "TypeLocBuilder.h"
147330f729Sjoerg #include "clang/AST/ASTLambda.h"
157330f729Sjoerg #include "clang/AST/ExprCXX.h"
167330f729Sjoerg #include "clang/Basic/TargetInfo.h"
177330f729Sjoerg #include "clang/Sema/Initialization.h"
187330f729Sjoerg #include "clang/Sema/Lookup.h"
197330f729Sjoerg #include "clang/Sema/Scope.h"
207330f729Sjoerg #include "clang/Sema/ScopeInfo.h"
217330f729Sjoerg #include "clang/Sema/SemaInternal.h"
227330f729Sjoerg #include "clang/Sema/SemaLambda.h"
237330f729Sjoerg #include "llvm/ADT/STLExtras.h"
247330f729Sjoerg using namespace clang;
257330f729Sjoerg using namespace sema;
267330f729Sjoerg 
277330f729Sjoerg /// Examines the FunctionScopeInfo stack to determine the nearest
287330f729Sjoerg /// enclosing lambda (to the current lambda) that is 'capture-ready' for
297330f729Sjoerg /// the variable referenced in the current lambda (i.e. \p VarToCapture).
307330f729Sjoerg /// If successful, returns the index into Sema's FunctionScopeInfo stack
317330f729Sjoerg /// of the capture-ready lambda's LambdaScopeInfo.
327330f729Sjoerg ///
337330f729Sjoerg /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
347330f729Sjoerg /// lambda - is on top) to determine the index of the nearest enclosing/outer
357330f729Sjoerg /// lambda that is ready to capture the \p VarToCapture being referenced in
367330f729Sjoerg /// the current lambda.
377330f729Sjoerg /// As we climb down the stack, we want the index of the first such lambda -
387330f729Sjoerg /// that is the lambda with the highest index that is 'capture-ready'.
397330f729Sjoerg ///
407330f729Sjoerg /// A lambda 'L' is capture-ready for 'V' (var or this) if:
417330f729Sjoerg ///  - its enclosing context is non-dependent
427330f729Sjoerg ///  - and if the chain of lambdas between L and the lambda in which
437330f729Sjoerg ///    V is potentially used (i.e. the lambda at the top of the scope info
447330f729Sjoerg ///    stack), can all capture or have already captured V.
457330f729Sjoerg /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
467330f729Sjoerg ///
477330f729Sjoerg /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
487330f729Sjoerg /// for whether it is 'capture-capable' (see
497330f729Sjoerg /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
507330f729Sjoerg /// capture.
517330f729Sjoerg ///
527330f729Sjoerg /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
537330f729Sjoerg ///  LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
547330f729Sjoerg ///  is at the top of the stack and has the highest index.
557330f729Sjoerg /// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
567330f729Sjoerg ///
577330f729Sjoerg /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
587330f729Sjoerg /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
597330f729Sjoerg /// which is capture-ready.  If the return value evaluates to 'false' then
607330f729Sjoerg /// no lambda is capture-ready for \p VarToCapture.
617330f729Sjoerg 
627330f729Sjoerg static inline Optional<unsigned>
getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef<const clang::sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture)637330f729Sjoerg getStackIndexOfNearestEnclosingCaptureReadyLambda(
647330f729Sjoerg     ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
657330f729Sjoerg     VarDecl *VarToCapture) {
667330f729Sjoerg   // Label failure to capture.
677330f729Sjoerg   const Optional<unsigned> NoLambdaIsCaptureReady;
687330f729Sjoerg 
697330f729Sjoerg   // Ignore all inner captured regions.
707330f729Sjoerg   unsigned CurScopeIndex = FunctionScopes.size() - 1;
717330f729Sjoerg   while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
727330f729Sjoerg                                   FunctionScopes[CurScopeIndex]))
737330f729Sjoerg     --CurScopeIndex;
747330f729Sjoerg   assert(
757330f729Sjoerg       isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
767330f729Sjoerg       "The function on the top of sema's function-info stack must be a lambda");
777330f729Sjoerg 
787330f729Sjoerg   // If VarToCapture is null, we are attempting to capture 'this'.
797330f729Sjoerg   const bool IsCapturingThis = !VarToCapture;
807330f729Sjoerg   const bool IsCapturingVariable = !IsCapturingThis;
817330f729Sjoerg 
827330f729Sjoerg   // Start with the current lambda at the top of the stack (highest index).
837330f729Sjoerg   DeclContext *EnclosingDC =
847330f729Sjoerg       cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
857330f729Sjoerg 
867330f729Sjoerg   do {
877330f729Sjoerg     const clang::sema::LambdaScopeInfo *LSI =
887330f729Sjoerg         cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
897330f729Sjoerg     // IF we have climbed down to an intervening enclosing lambda that contains
907330f729Sjoerg     // the variable declaration - it obviously can/must not capture the
917330f729Sjoerg     // variable.
927330f729Sjoerg     // Since its enclosing DC is dependent, all the lambdas between it and the
937330f729Sjoerg     // innermost nested lambda are dependent (otherwise we wouldn't have
947330f729Sjoerg     // arrived here) - so we don't yet have a lambda that can capture the
957330f729Sjoerg     // variable.
967330f729Sjoerg     if (IsCapturingVariable &&
977330f729Sjoerg         VarToCapture->getDeclContext()->Equals(EnclosingDC))
987330f729Sjoerg       return NoLambdaIsCaptureReady;
997330f729Sjoerg 
1007330f729Sjoerg     // For an enclosing lambda to be capture ready for an entity, all
1017330f729Sjoerg     // intervening lambda's have to be able to capture that entity. If even
1027330f729Sjoerg     // one of the intervening lambda's is not capable of capturing the entity
1037330f729Sjoerg     // then no enclosing lambda can ever capture that entity.
1047330f729Sjoerg     // For e.g.
1057330f729Sjoerg     // const int x = 10;
1067330f729Sjoerg     // [=](auto a) {    #1
1077330f729Sjoerg     //   [](auto b) {   #2 <-- an intervening lambda that can never capture 'x'
1087330f729Sjoerg     //    [=](auto c) { #3
1097330f729Sjoerg     //       f(x, c);  <-- can not lead to x's speculative capture by #1 or #2
1107330f729Sjoerg     //    }; }; };
1117330f729Sjoerg     // If they do not have a default implicit capture, check to see
1127330f729Sjoerg     // if the entity has already been explicitly captured.
1137330f729Sjoerg     // If even a single dependent enclosing lambda lacks the capability
1147330f729Sjoerg     // to ever capture this variable, there is no further enclosing
1157330f729Sjoerg     // non-dependent lambda that can capture this variable.
1167330f729Sjoerg     if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
1177330f729Sjoerg       if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
1187330f729Sjoerg         return NoLambdaIsCaptureReady;
1197330f729Sjoerg       if (IsCapturingThis && !LSI->isCXXThisCaptured())
1207330f729Sjoerg         return NoLambdaIsCaptureReady;
1217330f729Sjoerg     }
1227330f729Sjoerg     EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
1237330f729Sjoerg 
1247330f729Sjoerg     assert(CurScopeIndex);
1257330f729Sjoerg     --CurScopeIndex;
1267330f729Sjoerg   } while (!EnclosingDC->isTranslationUnit() &&
1277330f729Sjoerg            EnclosingDC->isDependentContext() &&
1287330f729Sjoerg            isLambdaCallOperator(EnclosingDC));
1297330f729Sjoerg 
1307330f729Sjoerg   assert(CurScopeIndex < (FunctionScopes.size() - 1));
1317330f729Sjoerg   // If the enclosingDC is not dependent, then the immediately nested lambda
1327330f729Sjoerg   // (one index above) is capture-ready.
1337330f729Sjoerg   if (!EnclosingDC->isDependentContext())
1347330f729Sjoerg     return CurScopeIndex + 1;
1357330f729Sjoerg   return NoLambdaIsCaptureReady;
1367330f729Sjoerg }
1377330f729Sjoerg 
1387330f729Sjoerg /// Examines the FunctionScopeInfo stack to determine the nearest
1397330f729Sjoerg /// enclosing lambda (to the current lambda) that is 'capture-capable' for
1407330f729Sjoerg /// the variable referenced in the current lambda (i.e. \p VarToCapture).
1417330f729Sjoerg /// If successful, returns the index into Sema's FunctionScopeInfo stack
1427330f729Sjoerg /// of the capture-capable lambda's LambdaScopeInfo.
1437330f729Sjoerg ///
1447330f729Sjoerg /// Given the current stack of lambdas being processed by Sema and
1457330f729Sjoerg /// the variable of interest, to identify the nearest enclosing lambda (to the
1467330f729Sjoerg /// current lambda at the top of the stack) that can truly capture
1477330f729Sjoerg /// a variable, it has to have the following two properties:
1487330f729Sjoerg ///  a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
1497330f729Sjoerg ///     - climb down the stack (i.e. starting from the innermost and examining
1507330f729Sjoerg ///       each outer lambda step by step) checking if each enclosing
1517330f729Sjoerg ///       lambda can either implicitly or explicitly capture the variable.
1527330f729Sjoerg ///       Record the first such lambda that is enclosed in a non-dependent
1537330f729Sjoerg ///       context. If no such lambda currently exists return failure.
1547330f729Sjoerg ///  b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
1557330f729Sjoerg ///  capture the variable by checking all its enclosing lambdas:
1567330f729Sjoerg ///     - check if all outer lambdas enclosing the 'capture-ready' lambda
1577330f729Sjoerg ///       identified above in 'a' can also capture the variable (this is done
1587330f729Sjoerg ///       via tryCaptureVariable for variables and CheckCXXThisCapture for
1597330f729Sjoerg ///       'this' by passing in the index of the Lambda identified in step 'a')
1607330f729Sjoerg ///
1617330f729Sjoerg /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
1627330f729Sjoerg /// LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
1637330f729Sjoerg /// is at the top of the stack.
1647330f729Sjoerg ///
1657330f729Sjoerg /// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
1667330f729Sjoerg ///
1677330f729Sjoerg ///
1687330f729Sjoerg /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
1697330f729Sjoerg /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
1707330f729Sjoerg /// which is capture-capable.  If the return value evaluates to 'false' then
1717330f729Sjoerg /// no lambda is capture-capable for \p VarToCapture.
1727330f729Sjoerg 
getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef<const sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture,Sema & S)1737330f729Sjoerg Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
1747330f729Sjoerg     ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
1757330f729Sjoerg     VarDecl *VarToCapture, Sema &S) {
1767330f729Sjoerg 
1777330f729Sjoerg   const Optional<unsigned> NoLambdaIsCaptureCapable;
1787330f729Sjoerg 
1797330f729Sjoerg   const Optional<unsigned> OptionalStackIndex =
1807330f729Sjoerg       getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
1817330f729Sjoerg                                                         VarToCapture);
1827330f729Sjoerg   if (!OptionalStackIndex)
1837330f729Sjoerg     return NoLambdaIsCaptureCapable;
1847330f729Sjoerg 
1857330f729Sjoerg   const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
1867330f729Sjoerg   assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
1877330f729Sjoerg           S.getCurGenericLambda()) &&
1887330f729Sjoerg          "The capture ready lambda for a potential capture can only be the "
1897330f729Sjoerg          "current lambda if it is a generic lambda");
1907330f729Sjoerg 
1917330f729Sjoerg   const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
1927330f729Sjoerg       cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
1937330f729Sjoerg 
1947330f729Sjoerg   // If VarToCapture is null, we are attempting to capture 'this'
1957330f729Sjoerg   const bool IsCapturingThis = !VarToCapture;
1967330f729Sjoerg   const bool IsCapturingVariable = !IsCapturingThis;
1977330f729Sjoerg 
1987330f729Sjoerg   if (IsCapturingVariable) {
1997330f729Sjoerg     // Check if the capture-ready lambda can truly capture the variable, by
2007330f729Sjoerg     // checking whether all enclosing lambdas of the capture-ready lambda allow
2017330f729Sjoerg     // the capture - i.e. make sure it is capture-capable.
2027330f729Sjoerg     QualType CaptureType, DeclRefType;
2037330f729Sjoerg     const bool CanCaptureVariable =
2047330f729Sjoerg         !S.tryCaptureVariable(VarToCapture,
2057330f729Sjoerg                               /*ExprVarIsUsedInLoc*/ SourceLocation(),
2067330f729Sjoerg                               clang::Sema::TryCapture_Implicit,
2077330f729Sjoerg                               /*EllipsisLoc*/ SourceLocation(),
2087330f729Sjoerg                               /*BuildAndDiagnose*/ false, CaptureType,
2097330f729Sjoerg                               DeclRefType, &IndexOfCaptureReadyLambda);
2107330f729Sjoerg     if (!CanCaptureVariable)
2117330f729Sjoerg       return NoLambdaIsCaptureCapable;
2127330f729Sjoerg   } else {
2137330f729Sjoerg     // Check if the capture-ready lambda can truly capture 'this' by checking
2147330f729Sjoerg     // whether all enclosing lambdas of the capture-ready lambda can capture
2157330f729Sjoerg     // 'this'.
2167330f729Sjoerg     const bool CanCaptureThis =
2177330f729Sjoerg         !S.CheckCXXThisCapture(
2187330f729Sjoerg              CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
2197330f729Sjoerg              /*Explicit*/ false, /*BuildAndDiagnose*/ false,
2207330f729Sjoerg              &IndexOfCaptureReadyLambda);
2217330f729Sjoerg     if (!CanCaptureThis)
2227330f729Sjoerg       return NoLambdaIsCaptureCapable;
2237330f729Sjoerg   }
2247330f729Sjoerg   return IndexOfCaptureReadyLambda;
2257330f729Sjoerg }
2267330f729Sjoerg 
2277330f729Sjoerg static inline TemplateParameterList *
getGenericLambdaTemplateParameterList(LambdaScopeInfo * LSI,Sema & SemaRef)2287330f729Sjoerg getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
2297330f729Sjoerg   if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
2307330f729Sjoerg     LSI->GLTemplateParameterList = TemplateParameterList::Create(
2317330f729Sjoerg         SemaRef.Context,
2327330f729Sjoerg         /*Template kw loc*/ SourceLocation(),
2337330f729Sjoerg         /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
2347330f729Sjoerg         LSI->TemplateParams,
2357330f729Sjoerg         /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
236*e038c9c4Sjoerg         LSI->RequiresClause.get());
2377330f729Sjoerg   }
2387330f729Sjoerg   return LSI->GLTemplateParameterList;
2397330f729Sjoerg }
2407330f729Sjoerg 
createLambdaClosureType(SourceRange IntroducerRange,TypeSourceInfo * Info,bool KnownDependent,LambdaCaptureDefault CaptureDefault)2417330f729Sjoerg CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
2427330f729Sjoerg                                              TypeSourceInfo *Info,
2437330f729Sjoerg                                              bool KnownDependent,
2447330f729Sjoerg                                              LambdaCaptureDefault CaptureDefault) {
2457330f729Sjoerg   DeclContext *DC = CurContext;
2467330f729Sjoerg   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
2477330f729Sjoerg     DC = DC->getParent();
2487330f729Sjoerg   bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
2497330f729Sjoerg                                                                *this);
2507330f729Sjoerg   // Start constructing the lambda class.
2517330f729Sjoerg   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
2527330f729Sjoerg                                                      IntroducerRange.getBegin(),
2537330f729Sjoerg                                                      KnownDependent,
2547330f729Sjoerg                                                      IsGenericLambda,
2557330f729Sjoerg                                                      CaptureDefault);
2567330f729Sjoerg   DC->addDecl(Class);
2577330f729Sjoerg 
2587330f729Sjoerg   return Class;
2597330f729Sjoerg }
2607330f729Sjoerg 
2617330f729Sjoerg /// Determine whether the given context is or is enclosed in an inline
2627330f729Sjoerg /// function.
isInInlineFunction(const DeclContext * DC)2637330f729Sjoerg static bool isInInlineFunction(const DeclContext *DC) {
2647330f729Sjoerg   while (!DC->isFileContext()) {
2657330f729Sjoerg     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
2667330f729Sjoerg       if (FD->isInlined())
2677330f729Sjoerg         return true;
2687330f729Sjoerg 
2697330f729Sjoerg     DC = DC->getLexicalParent();
2707330f729Sjoerg   }
2717330f729Sjoerg 
2727330f729Sjoerg   return false;
2737330f729Sjoerg }
2747330f729Sjoerg 
2757330f729Sjoerg std::tuple<MangleNumberingContext *, Decl *>
getCurrentMangleNumberContext(const DeclContext * DC)2767330f729Sjoerg Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
2777330f729Sjoerg   // Compute the context for allocating mangling numbers in the current
2787330f729Sjoerg   // expression, if the ABI requires them.
2797330f729Sjoerg   Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
2807330f729Sjoerg 
2817330f729Sjoerg   enum ContextKind {
2827330f729Sjoerg     Normal,
2837330f729Sjoerg     DefaultArgument,
2847330f729Sjoerg     DataMember,
2857330f729Sjoerg     StaticDataMember,
2867330f729Sjoerg     InlineVariable,
2877330f729Sjoerg     VariableTemplate
2887330f729Sjoerg   } Kind = Normal;
2897330f729Sjoerg 
2907330f729Sjoerg   // Default arguments of member function parameters that appear in a class
2917330f729Sjoerg   // definition, as well as the initializers of data members, receive special
2927330f729Sjoerg   // treatment. Identify them.
2937330f729Sjoerg   if (ManglingContextDecl) {
2947330f729Sjoerg     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
2957330f729Sjoerg       if (const DeclContext *LexicalDC
2967330f729Sjoerg           = Param->getDeclContext()->getLexicalParent())
2977330f729Sjoerg         if (LexicalDC->isRecord())
2987330f729Sjoerg           Kind = DefaultArgument;
2997330f729Sjoerg     } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
3007330f729Sjoerg       if (Var->getDeclContext()->isRecord())
3017330f729Sjoerg         Kind = StaticDataMember;
3027330f729Sjoerg       else if (Var->getMostRecentDecl()->isInline())
3037330f729Sjoerg         Kind = InlineVariable;
3047330f729Sjoerg       else if (Var->getDescribedVarTemplate())
3057330f729Sjoerg         Kind = VariableTemplate;
3067330f729Sjoerg       else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
3077330f729Sjoerg         if (!VTS->isExplicitSpecialization())
3087330f729Sjoerg           Kind = VariableTemplate;
3097330f729Sjoerg       }
3107330f729Sjoerg     } else if (isa<FieldDecl>(ManglingContextDecl)) {
3117330f729Sjoerg       Kind = DataMember;
3127330f729Sjoerg     }
3137330f729Sjoerg   }
3147330f729Sjoerg 
3157330f729Sjoerg   // Itanium ABI [5.1.7]:
3167330f729Sjoerg   //   In the following contexts [...] the one-definition rule requires closure
3177330f729Sjoerg   //   types in different translation units to "correspond":
3187330f729Sjoerg   bool IsInNonspecializedTemplate =
3197330f729Sjoerg       inTemplateInstantiation() || CurContext->isDependentContext();
3207330f729Sjoerg   switch (Kind) {
3217330f729Sjoerg   case Normal: {
3227330f729Sjoerg     //  -- the bodies of non-exported nonspecialized template functions
3237330f729Sjoerg     //  -- the bodies of inline functions
3247330f729Sjoerg     if ((IsInNonspecializedTemplate &&
3257330f729Sjoerg          !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
3267330f729Sjoerg         isInInlineFunction(CurContext)) {
3277330f729Sjoerg       while (auto *CD = dyn_cast<CapturedDecl>(DC))
3287330f729Sjoerg         DC = CD->getParent();
3297330f729Sjoerg       return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
3307330f729Sjoerg     }
3317330f729Sjoerg 
3327330f729Sjoerg     return std::make_tuple(nullptr, nullptr);
3337330f729Sjoerg   }
3347330f729Sjoerg 
3357330f729Sjoerg   case StaticDataMember:
3367330f729Sjoerg     //  -- the initializers of nonspecialized static members of template classes
3377330f729Sjoerg     if (!IsInNonspecializedTemplate)
3387330f729Sjoerg       return std::make_tuple(nullptr, ManglingContextDecl);
3397330f729Sjoerg     // Fall through to get the current context.
3407330f729Sjoerg     LLVM_FALLTHROUGH;
3417330f729Sjoerg 
3427330f729Sjoerg   case DataMember:
3437330f729Sjoerg     //  -- the in-class initializers of class members
3447330f729Sjoerg   case DefaultArgument:
3457330f729Sjoerg     //  -- default arguments appearing in class definitions
3467330f729Sjoerg   case InlineVariable:
3477330f729Sjoerg     //  -- the initializers of inline variables
3487330f729Sjoerg   case VariableTemplate:
3497330f729Sjoerg     //  -- the initializers of templated variables
3507330f729Sjoerg     return std::make_tuple(
3517330f729Sjoerg         &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
3527330f729Sjoerg                                           ManglingContextDecl),
3537330f729Sjoerg         ManglingContextDecl);
3547330f729Sjoerg   }
3557330f729Sjoerg 
3567330f729Sjoerg   llvm_unreachable("unexpected context");
3577330f729Sjoerg }
3587330f729Sjoerg 
startLambdaDefinition(CXXRecordDecl * Class,SourceRange IntroducerRange,TypeSourceInfo * MethodTypeInfo,SourceLocation EndLoc,ArrayRef<ParmVarDecl * > Params,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)3597330f729Sjoerg CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
3607330f729Sjoerg                                            SourceRange IntroducerRange,
3617330f729Sjoerg                                            TypeSourceInfo *MethodTypeInfo,
3627330f729Sjoerg                                            SourceLocation EndLoc,
3637330f729Sjoerg                                            ArrayRef<ParmVarDecl *> Params,
364*e038c9c4Sjoerg                                            ConstexprSpecKind ConstexprKind,
365*e038c9c4Sjoerg                                            Expr *TrailingRequiresClause) {
3667330f729Sjoerg   QualType MethodType = MethodTypeInfo->getType();
3677330f729Sjoerg   TemplateParameterList *TemplateParams =
3687330f729Sjoerg       getGenericLambdaTemplateParameterList(getCurLambda(), *this);
3697330f729Sjoerg   // If a lambda appears in a dependent context or is a generic lambda (has
3707330f729Sjoerg   // template parameters) and has an 'auto' return type, deduce it to a
3717330f729Sjoerg   // dependent type.
3727330f729Sjoerg   if (Class->isDependentContext() || TemplateParams) {
3737330f729Sjoerg     const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
3747330f729Sjoerg     QualType Result = FPT->getReturnType();
3757330f729Sjoerg     if (Result->isUndeducedType()) {
3767330f729Sjoerg       Result = SubstAutoType(Result, Context.DependentTy);
3777330f729Sjoerg       MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
3787330f729Sjoerg                                            FPT->getExtProtoInfo());
3797330f729Sjoerg     }
3807330f729Sjoerg   }
3817330f729Sjoerg 
3827330f729Sjoerg   // C++11 [expr.prim.lambda]p5:
3837330f729Sjoerg   //   The closure type for a lambda-expression has a public inline function
3847330f729Sjoerg   //   call operator (13.5.4) whose parameters and return type are described by
3857330f729Sjoerg   //   the lambda-expression's parameter-declaration-clause and
3867330f729Sjoerg   //   trailing-return-type respectively.
3877330f729Sjoerg   DeclarationName MethodName
3887330f729Sjoerg     = Context.DeclarationNames.getCXXOperatorName(OO_Call);
389*e038c9c4Sjoerg   DeclarationNameLoc MethodNameLoc =
390*e038c9c4Sjoerg       DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange);
3917330f729Sjoerg   CXXMethodDecl *Method = CXXMethodDecl::Create(
3927330f729Sjoerg       Context, Class, EndLoc,
3937330f729Sjoerg       DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
3947330f729Sjoerg                           MethodNameLoc),
3957330f729Sjoerg       MethodType, MethodTypeInfo, SC_None,
396*e038c9c4Sjoerg       /*isInline=*/true, ConstexprKind, EndLoc, TrailingRequiresClause);
3977330f729Sjoerg   Method->setAccess(AS_public);
3987330f729Sjoerg   if (!TemplateParams)
3997330f729Sjoerg     Class->addDecl(Method);
4007330f729Sjoerg 
4017330f729Sjoerg   // Temporarily set the lexical declaration context to the current
4027330f729Sjoerg   // context, so that the Scope stack matches the lexical nesting.
4037330f729Sjoerg   Method->setLexicalDeclContext(CurContext);
4047330f729Sjoerg   // Create a function template if we have a template parameter list
4057330f729Sjoerg   FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
4067330f729Sjoerg             FunctionTemplateDecl::Create(Context, Class,
4077330f729Sjoerg                                          Method->getLocation(), MethodName,
4087330f729Sjoerg                                          TemplateParams,
4097330f729Sjoerg                                          Method) : nullptr;
4107330f729Sjoerg   if (TemplateMethod) {
4117330f729Sjoerg     TemplateMethod->setAccess(AS_public);
4127330f729Sjoerg     Method->setDescribedFunctionTemplate(TemplateMethod);
4137330f729Sjoerg     Class->addDecl(TemplateMethod);
4147330f729Sjoerg     TemplateMethod->setLexicalDeclContext(CurContext);
4157330f729Sjoerg   }
4167330f729Sjoerg 
4177330f729Sjoerg   // Add parameters.
4187330f729Sjoerg   if (!Params.empty()) {
4197330f729Sjoerg     Method->setParams(Params);
4207330f729Sjoerg     CheckParmsForFunctionDef(Params,
4217330f729Sjoerg                              /*CheckParameterNames=*/false);
4227330f729Sjoerg 
4237330f729Sjoerg     for (auto P : Method->parameters())
4247330f729Sjoerg       P->setOwningFunction(Method);
4257330f729Sjoerg   }
4267330f729Sjoerg 
4277330f729Sjoerg   return Method;
4287330f729Sjoerg }
4297330f729Sjoerg 
handleLambdaNumbering(CXXRecordDecl * Class,CXXMethodDecl * Method,Optional<std::tuple<bool,unsigned,unsigned,Decl * >> Mangling)4307330f729Sjoerg void Sema::handleLambdaNumbering(
4317330f729Sjoerg     CXXRecordDecl *Class, CXXMethodDecl *Method,
432*e038c9c4Sjoerg     Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
4337330f729Sjoerg   if (Mangling) {
4347330f729Sjoerg     bool HasKnownInternalLinkage;
435*e038c9c4Sjoerg     unsigned ManglingNumber, DeviceManglingNumber;
4367330f729Sjoerg     Decl *ManglingContextDecl;
437*e038c9c4Sjoerg     std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
438*e038c9c4Sjoerg              ManglingContextDecl) = Mangling.getValue();
4397330f729Sjoerg     Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
4407330f729Sjoerg                              HasKnownInternalLinkage);
441*e038c9c4Sjoerg     Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
4427330f729Sjoerg     return;
4437330f729Sjoerg   }
4447330f729Sjoerg 
4457330f729Sjoerg   auto getMangleNumberingContext =
4467330f729Sjoerg       [this](CXXRecordDecl *Class,
4477330f729Sjoerg              Decl *ManglingContextDecl) -> MangleNumberingContext * {
4487330f729Sjoerg     // Get mangle numbering context if there's any extra decl context.
4497330f729Sjoerg     if (ManglingContextDecl)
4507330f729Sjoerg       return &Context.getManglingNumberContext(
4517330f729Sjoerg           ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
4527330f729Sjoerg     // Otherwise, from that lambda's decl context.
4537330f729Sjoerg     auto DC = Class->getDeclContext();
4547330f729Sjoerg     while (auto *CD = dyn_cast<CapturedDecl>(DC))
4557330f729Sjoerg       DC = CD->getParent();
4567330f729Sjoerg     return &Context.getManglingNumberContext(DC);
4577330f729Sjoerg   };
4587330f729Sjoerg 
4597330f729Sjoerg   MangleNumberingContext *MCtx;
4607330f729Sjoerg   Decl *ManglingContextDecl;
4617330f729Sjoerg   std::tie(MCtx, ManglingContextDecl) =
4627330f729Sjoerg       getCurrentMangleNumberContext(Class->getDeclContext());
4637330f729Sjoerg   bool HasKnownInternalLinkage = false;
4647330f729Sjoerg   if (!MCtx && getLangOpts().CUDA) {
4657330f729Sjoerg     // Force lambda numbering in CUDA/HIP as we need to name lambdas following
4667330f729Sjoerg     // ODR. Both device- and host-compilation need to have a consistent naming
4677330f729Sjoerg     // on kernel functions. As lambdas are potential part of these `__global__`
4687330f729Sjoerg     // function names, they needs numbering following ODR.
4697330f729Sjoerg     MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
4707330f729Sjoerg     assert(MCtx && "Retrieving mangle numbering context failed!");
4717330f729Sjoerg     HasKnownInternalLinkage = true;
4727330f729Sjoerg   }
4737330f729Sjoerg   if (MCtx) {
4747330f729Sjoerg     unsigned ManglingNumber = MCtx->getManglingNumber(Method);
4757330f729Sjoerg     Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
4767330f729Sjoerg                              HasKnownInternalLinkage);
477*e038c9c4Sjoerg     Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
4787330f729Sjoerg   }
4797330f729Sjoerg }
4807330f729Sjoerg 
buildLambdaScope(LambdaScopeInfo * LSI,CXXMethodDecl * CallOperator,SourceRange IntroducerRange,LambdaCaptureDefault CaptureDefault,SourceLocation CaptureDefaultLoc,bool ExplicitParams,bool ExplicitResultType,bool Mutable)4817330f729Sjoerg void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
4827330f729Sjoerg                                         CXXMethodDecl *CallOperator,
4837330f729Sjoerg                                         SourceRange IntroducerRange,
4847330f729Sjoerg                                         LambdaCaptureDefault CaptureDefault,
4857330f729Sjoerg                                         SourceLocation CaptureDefaultLoc,
4867330f729Sjoerg                                         bool ExplicitParams,
4877330f729Sjoerg                                         bool ExplicitResultType,
4887330f729Sjoerg                                         bool Mutable) {
4897330f729Sjoerg   LSI->CallOperator = CallOperator;
4907330f729Sjoerg   CXXRecordDecl *LambdaClass = CallOperator->getParent();
4917330f729Sjoerg   LSI->Lambda = LambdaClass;
4927330f729Sjoerg   if (CaptureDefault == LCD_ByCopy)
4937330f729Sjoerg     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
4947330f729Sjoerg   else if (CaptureDefault == LCD_ByRef)
4957330f729Sjoerg     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
4967330f729Sjoerg   LSI->CaptureDefaultLoc = CaptureDefaultLoc;
4977330f729Sjoerg   LSI->IntroducerRange = IntroducerRange;
4987330f729Sjoerg   LSI->ExplicitParams = ExplicitParams;
4997330f729Sjoerg   LSI->Mutable = Mutable;
5007330f729Sjoerg 
5017330f729Sjoerg   if (ExplicitResultType) {
5027330f729Sjoerg     LSI->ReturnType = CallOperator->getReturnType();
5037330f729Sjoerg 
5047330f729Sjoerg     if (!LSI->ReturnType->isDependentType() &&
5057330f729Sjoerg         !LSI->ReturnType->isVoidType()) {
5067330f729Sjoerg       if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
5077330f729Sjoerg                               diag::err_lambda_incomplete_result)) {
5087330f729Sjoerg         // Do nothing.
5097330f729Sjoerg       }
5107330f729Sjoerg     }
5117330f729Sjoerg   } else {
5127330f729Sjoerg     LSI->HasImplicitReturnType = true;
5137330f729Sjoerg   }
5147330f729Sjoerg }
5157330f729Sjoerg 
finishLambdaExplicitCaptures(LambdaScopeInfo * LSI)5167330f729Sjoerg void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
5177330f729Sjoerg   LSI->finishedExplicitCaptures();
5187330f729Sjoerg }
5197330f729Sjoerg 
ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,ArrayRef<NamedDecl * > TParams,SourceLocation RAngleLoc,ExprResult RequiresClause)5207330f729Sjoerg void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
5217330f729Sjoerg                                                     ArrayRef<NamedDecl *> TParams,
522*e038c9c4Sjoerg                                                     SourceLocation RAngleLoc,
523*e038c9c4Sjoerg                                                     ExprResult RequiresClause) {
5247330f729Sjoerg   LambdaScopeInfo *LSI = getCurLambda();
5257330f729Sjoerg   assert(LSI && "Expected a lambda scope");
5267330f729Sjoerg   assert(LSI->NumExplicitTemplateParams == 0 &&
5277330f729Sjoerg          "Already acted on explicit template parameters");
5287330f729Sjoerg   assert(LSI->TemplateParams.empty() &&
5297330f729Sjoerg          "Explicit template parameters should come "
5307330f729Sjoerg          "before invented (auto) ones");
5317330f729Sjoerg   assert(!TParams.empty() &&
5327330f729Sjoerg          "No template parameters to act on");
5337330f729Sjoerg   LSI->TemplateParams.append(TParams.begin(), TParams.end());
5347330f729Sjoerg   LSI->NumExplicitTemplateParams = TParams.size();
5357330f729Sjoerg   LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
536*e038c9c4Sjoerg   LSI->RequiresClause = RequiresClause;
5377330f729Sjoerg }
5387330f729Sjoerg 
addLambdaParameters(ArrayRef<LambdaIntroducer::LambdaCapture> Captures,CXXMethodDecl * CallOperator,Scope * CurScope)5397330f729Sjoerg void Sema::addLambdaParameters(
5407330f729Sjoerg     ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
5417330f729Sjoerg     CXXMethodDecl *CallOperator, Scope *CurScope) {
5427330f729Sjoerg   // Introduce our parameters into the function scope
5437330f729Sjoerg   for (unsigned p = 0, NumParams = CallOperator->getNumParams();
5447330f729Sjoerg        p < NumParams; ++p) {
5457330f729Sjoerg     ParmVarDecl *Param = CallOperator->getParamDecl(p);
5467330f729Sjoerg 
5477330f729Sjoerg     // If this has an identifier, add it to the scope stack.
5487330f729Sjoerg     if (CurScope && Param->getIdentifier()) {
5497330f729Sjoerg       bool Error = false;
5507330f729Sjoerg       // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
5517330f729Sjoerg       // retroactively apply it.
5527330f729Sjoerg       for (const auto &Capture : Captures) {
5537330f729Sjoerg         if (Capture.Id == Param->getIdentifier()) {
5547330f729Sjoerg           Error = true;
5557330f729Sjoerg           Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
5567330f729Sjoerg           Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
5577330f729Sjoerg               << Capture.Id << true;
5587330f729Sjoerg         }
5597330f729Sjoerg       }
5607330f729Sjoerg       if (!Error)
5617330f729Sjoerg         CheckShadow(CurScope, Param);
5627330f729Sjoerg 
5637330f729Sjoerg       PushOnScopeChains(Param, CurScope);
5647330f729Sjoerg     }
5657330f729Sjoerg   }
5667330f729Sjoerg }
5677330f729Sjoerg 
5687330f729Sjoerg /// If this expression is an enumerator-like expression of some type
5697330f729Sjoerg /// T, return the type T; otherwise, return null.
5707330f729Sjoerg ///
5717330f729Sjoerg /// Pointer comparisons on the result here should always work because
5727330f729Sjoerg /// it's derived from either the parent of an EnumConstantDecl
5737330f729Sjoerg /// (i.e. the definition) or the declaration returned by
5747330f729Sjoerg /// EnumType::getDecl() (i.e. the definition).
findEnumForBlockReturn(Expr * E)5757330f729Sjoerg static EnumDecl *findEnumForBlockReturn(Expr *E) {
5767330f729Sjoerg   // An expression is an enumerator-like expression of type T if,
5777330f729Sjoerg   // ignoring parens and parens-like expressions:
5787330f729Sjoerg   E = E->IgnoreParens();
5797330f729Sjoerg 
5807330f729Sjoerg   //  - it is an enumerator whose enum type is T or
5817330f729Sjoerg   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5827330f729Sjoerg     if (EnumConstantDecl *D
5837330f729Sjoerg           = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5847330f729Sjoerg       return cast<EnumDecl>(D->getDeclContext());
5857330f729Sjoerg     }
5867330f729Sjoerg     return nullptr;
5877330f729Sjoerg   }
5887330f729Sjoerg 
5897330f729Sjoerg   //  - it is a comma expression whose RHS is an enumerator-like
5907330f729Sjoerg   //    expression of type T or
5917330f729Sjoerg   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5927330f729Sjoerg     if (BO->getOpcode() == BO_Comma)
5937330f729Sjoerg       return findEnumForBlockReturn(BO->getRHS());
5947330f729Sjoerg     return nullptr;
5957330f729Sjoerg   }
5967330f729Sjoerg 
5977330f729Sjoerg   //  - it is a statement-expression whose value expression is an
5987330f729Sjoerg   //    enumerator-like expression of type T or
5997330f729Sjoerg   if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
6007330f729Sjoerg     if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
6017330f729Sjoerg       return findEnumForBlockReturn(last);
6027330f729Sjoerg     return nullptr;
6037330f729Sjoerg   }
6047330f729Sjoerg 
6057330f729Sjoerg   //   - it is a ternary conditional operator (not the GNU ?:
6067330f729Sjoerg   //     extension) whose second and third operands are
6077330f729Sjoerg   //     enumerator-like expressions of type T or
6087330f729Sjoerg   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6097330f729Sjoerg     if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
6107330f729Sjoerg       if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
6117330f729Sjoerg         return ED;
6127330f729Sjoerg     return nullptr;
6137330f729Sjoerg   }
6147330f729Sjoerg 
6157330f729Sjoerg   // (implicitly:)
6167330f729Sjoerg   //   - it is an implicit integral conversion applied to an
6177330f729Sjoerg   //     enumerator-like expression of type T or
6187330f729Sjoerg   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6197330f729Sjoerg     // We can sometimes see integral conversions in valid
6207330f729Sjoerg     // enumerator-like expressions.
6217330f729Sjoerg     if (ICE->getCastKind() == CK_IntegralCast)
6227330f729Sjoerg       return findEnumForBlockReturn(ICE->getSubExpr());
6237330f729Sjoerg 
6247330f729Sjoerg     // Otherwise, just rely on the type.
6257330f729Sjoerg   }
6267330f729Sjoerg 
6277330f729Sjoerg   //   - it is an expression of that formal enum type.
6287330f729Sjoerg   if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
6297330f729Sjoerg     return ET->getDecl();
6307330f729Sjoerg   }
6317330f729Sjoerg 
6327330f729Sjoerg   // Otherwise, nope.
6337330f729Sjoerg   return nullptr;
6347330f729Sjoerg }
6357330f729Sjoerg 
6367330f729Sjoerg /// Attempt to find a type T for which the returned expression of the
6377330f729Sjoerg /// given statement is an enumerator-like expression of that type.
findEnumForBlockReturn(ReturnStmt * ret)6387330f729Sjoerg static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
6397330f729Sjoerg   if (Expr *retValue = ret->getRetValue())
6407330f729Sjoerg     return findEnumForBlockReturn(retValue);
6417330f729Sjoerg   return nullptr;
6427330f729Sjoerg }
6437330f729Sjoerg 
6447330f729Sjoerg /// Attempt to find a common type T for which all of the returned
6457330f729Sjoerg /// expressions in a block are enumerator-like expressions of that
6467330f729Sjoerg /// type.
findCommonEnumForBlockReturns(ArrayRef<ReturnStmt * > returns)6477330f729Sjoerg static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
6487330f729Sjoerg   ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
6497330f729Sjoerg 
6507330f729Sjoerg   // Try to find one for the first return.
6517330f729Sjoerg   EnumDecl *ED = findEnumForBlockReturn(*i);
6527330f729Sjoerg   if (!ED) return nullptr;
6537330f729Sjoerg 
6547330f729Sjoerg   // Check that the rest of the returns have the same enum.
6557330f729Sjoerg   for (++i; i != e; ++i) {
6567330f729Sjoerg     if (findEnumForBlockReturn(*i) != ED)
6577330f729Sjoerg       return nullptr;
6587330f729Sjoerg   }
6597330f729Sjoerg 
6607330f729Sjoerg   // Never infer an anonymous enum type.
6617330f729Sjoerg   if (!ED->hasNameForLinkage()) return nullptr;
6627330f729Sjoerg 
6637330f729Sjoerg   return ED;
6647330f729Sjoerg }
6657330f729Sjoerg 
6667330f729Sjoerg /// Adjust the given return statements so that they formally return
6677330f729Sjoerg /// the given type.  It should require, at most, an IntegralCast.
adjustBlockReturnsToEnum(Sema & S,ArrayRef<ReturnStmt * > returns,QualType returnType)6687330f729Sjoerg static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
6697330f729Sjoerg                                      QualType returnType) {
6707330f729Sjoerg   for (ArrayRef<ReturnStmt*>::iterator
6717330f729Sjoerg          i = returns.begin(), e = returns.end(); i != e; ++i) {
6727330f729Sjoerg     ReturnStmt *ret = *i;
6737330f729Sjoerg     Expr *retValue = ret->getRetValue();
6747330f729Sjoerg     if (S.Context.hasSameType(retValue->getType(), returnType))
6757330f729Sjoerg       continue;
6767330f729Sjoerg 
6777330f729Sjoerg     // Right now we only support integral fixup casts.
6787330f729Sjoerg     assert(returnType->isIntegralOrUnscopedEnumerationType());
6797330f729Sjoerg     assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
6807330f729Sjoerg 
6817330f729Sjoerg     ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
6827330f729Sjoerg 
6837330f729Sjoerg     Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
684*e038c9c4Sjoerg     E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
685*e038c9c4Sjoerg                                  /*base path*/ nullptr, VK_RValue,
686*e038c9c4Sjoerg                                  FPOptionsOverride());
6877330f729Sjoerg     if (cleanups) {
6887330f729Sjoerg       cleanups->setSubExpr(E);
6897330f729Sjoerg     } else {
6907330f729Sjoerg       ret->setRetValue(E);
6917330f729Sjoerg     }
6927330f729Sjoerg   }
6937330f729Sjoerg }
6947330f729Sjoerg 
deduceClosureReturnType(CapturingScopeInfo & CSI)6957330f729Sjoerg void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
6967330f729Sjoerg   assert(CSI.HasImplicitReturnType);
6977330f729Sjoerg   // If it was ever a placeholder, it had to been deduced to DependentTy.
6987330f729Sjoerg   assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
6997330f729Sjoerg   assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
7007330f729Sjoerg          "lambda expressions use auto deduction in C++14 onwards");
7017330f729Sjoerg 
7027330f729Sjoerg   // C++ core issue 975:
7037330f729Sjoerg   //   If a lambda-expression does not include a trailing-return-type,
7047330f729Sjoerg   //   it is as if the trailing-return-type denotes the following type:
7057330f729Sjoerg   //     - if there are no return statements in the compound-statement,
7067330f729Sjoerg   //       or all return statements return either an expression of type
7077330f729Sjoerg   //       void or no expression or braced-init-list, the type void;
7087330f729Sjoerg   //     - otherwise, if all return statements return an expression
7097330f729Sjoerg   //       and the types of the returned expressions after
7107330f729Sjoerg   //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
7117330f729Sjoerg   //       array-to-pointer conversion (4.2 [conv.array]), and
7127330f729Sjoerg   //       function-to-pointer conversion (4.3 [conv.func]) are the
7137330f729Sjoerg   //       same, that common type;
7147330f729Sjoerg   //     - otherwise, the program is ill-formed.
7157330f729Sjoerg   //
7167330f729Sjoerg   // C++ core issue 1048 additionally removes top-level cv-qualifiers
7177330f729Sjoerg   // from the types of returned expressions to match the C++14 auto
7187330f729Sjoerg   // deduction rules.
7197330f729Sjoerg   //
7207330f729Sjoerg   // In addition, in blocks in non-C++ modes, if all of the return
7217330f729Sjoerg   // statements are enumerator-like expressions of some type T, where
7227330f729Sjoerg   // T has a name for linkage, then we infer the return type of the
7237330f729Sjoerg   // block to be that type.
7247330f729Sjoerg 
7257330f729Sjoerg   // First case: no return statements, implicit void return type.
7267330f729Sjoerg   ASTContext &Ctx = getASTContext();
7277330f729Sjoerg   if (CSI.Returns.empty()) {
7287330f729Sjoerg     // It's possible there were simply no /valid/ return statements.
7297330f729Sjoerg     // In this case, the first one we found may have at least given us a type.
7307330f729Sjoerg     if (CSI.ReturnType.isNull())
7317330f729Sjoerg       CSI.ReturnType = Ctx.VoidTy;
7327330f729Sjoerg     return;
7337330f729Sjoerg   }
7347330f729Sjoerg 
7357330f729Sjoerg   // Second case: at least one return statement has dependent type.
7367330f729Sjoerg   // Delay type checking until instantiation.
7377330f729Sjoerg   assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
7387330f729Sjoerg   if (CSI.ReturnType->isDependentType())
7397330f729Sjoerg     return;
7407330f729Sjoerg 
7417330f729Sjoerg   // Try to apply the enum-fuzz rule.
7427330f729Sjoerg   if (!getLangOpts().CPlusPlus) {
7437330f729Sjoerg     assert(isa<BlockScopeInfo>(CSI));
7447330f729Sjoerg     const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
7457330f729Sjoerg     if (ED) {
7467330f729Sjoerg       CSI.ReturnType = Context.getTypeDeclType(ED);
7477330f729Sjoerg       adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
7487330f729Sjoerg       return;
7497330f729Sjoerg     }
7507330f729Sjoerg   }
7517330f729Sjoerg 
7527330f729Sjoerg   // Third case: only one return statement. Don't bother doing extra work!
7537330f729Sjoerg   if (CSI.Returns.size() == 1)
7547330f729Sjoerg     return;
7557330f729Sjoerg 
7567330f729Sjoerg   // General case: many return statements.
7577330f729Sjoerg   // Check that they all have compatible return types.
7587330f729Sjoerg 
7597330f729Sjoerg   // We require the return types to strictly match here.
7607330f729Sjoerg   // Note that we've already done the required promotions as part of
7617330f729Sjoerg   // processing the return statement.
7627330f729Sjoerg   for (const ReturnStmt *RS : CSI.Returns) {
7637330f729Sjoerg     const Expr *RetE = RS->getRetValue();
7647330f729Sjoerg 
7657330f729Sjoerg     QualType ReturnType =
7667330f729Sjoerg         (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
7677330f729Sjoerg     if (Context.getCanonicalFunctionResultType(ReturnType) ==
7687330f729Sjoerg           Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
7697330f729Sjoerg       // Use the return type with the strictest possible nullability annotation.
7707330f729Sjoerg       auto RetTyNullability = ReturnType->getNullability(Ctx);
7717330f729Sjoerg       auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
7727330f729Sjoerg       if (BlockNullability &&
7737330f729Sjoerg           (!RetTyNullability ||
7747330f729Sjoerg            hasWeakerNullability(*RetTyNullability, *BlockNullability)))
7757330f729Sjoerg         CSI.ReturnType = ReturnType;
7767330f729Sjoerg       continue;
7777330f729Sjoerg     }
7787330f729Sjoerg 
7797330f729Sjoerg     // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
7807330f729Sjoerg     // TODO: It's possible that the *first* return is the divergent one.
7817330f729Sjoerg     Diag(RS->getBeginLoc(),
7827330f729Sjoerg          diag::err_typecheck_missing_return_type_incompatible)
7837330f729Sjoerg         << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
7847330f729Sjoerg     // Continue iterating so that we keep emitting diagnostics.
7857330f729Sjoerg   }
7867330f729Sjoerg }
7877330f729Sjoerg 
buildLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,Optional<unsigned> NumExpansions,IdentifierInfo * Id,bool IsDirectInit,Expr * & Init)7887330f729Sjoerg QualType Sema::buildLambdaInitCaptureInitialization(
7897330f729Sjoerg     SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
7907330f729Sjoerg     Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
7917330f729Sjoerg     Expr *&Init) {
7927330f729Sjoerg   // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
7937330f729Sjoerg   // deduce against.
7947330f729Sjoerg   QualType DeductType = Context.getAutoDeductType();
7957330f729Sjoerg   TypeLocBuilder TLB;
796*e038c9c4Sjoerg   AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
797*e038c9c4Sjoerg   TL.setNameLoc(Loc);
7987330f729Sjoerg   if (ByRef) {
7997330f729Sjoerg     DeductType = BuildReferenceType(DeductType, true, Loc, Id);
8007330f729Sjoerg     assert(!DeductType.isNull() && "can't build reference to auto");
8017330f729Sjoerg     TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
8027330f729Sjoerg   }
8037330f729Sjoerg   if (EllipsisLoc.isValid()) {
8047330f729Sjoerg     if (Init->containsUnexpandedParameterPack()) {
805*e038c9c4Sjoerg       Diag(EllipsisLoc, getLangOpts().CPlusPlus20
8067330f729Sjoerg                             ? diag::warn_cxx17_compat_init_capture_pack
8077330f729Sjoerg                             : diag::ext_init_capture_pack);
808*e038c9c4Sjoerg       DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
809*e038c9c4Sjoerg                                                 /*ExpectPackInType=*/false);
8107330f729Sjoerg       TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
8117330f729Sjoerg     } else {
8127330f729Sjoerg       // Just ignore the ellipsis for now and form a non-pack variable. We'll
8137330f729Sjoerg       // diagnose this later when we try to capture it.
8147330f729Sjoerg     }
8157330f729Sjoerg   }
8167330f729Sjoerg   TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
8177330f729Sjoerg 
8187330f729Sjoerg   // Deduce the type of the init capture.
8197330f729Sjoerg   QualType DeducedType = deduceVarTypeFromInitializer(
8207330f729Sjoerg       /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
8217330f729Sjoerg       SourceRange(Loc, Loc), IsDirectInit, Init);
8227330f729Sjoerg   if (DeducedType.isNull())
8237330f729Sjoerg     return QualType();
8247330f729Sjoerg 
8257330f729Sjoerg   // Are we a non-list direct initialization?
8267330f729Sjoerg   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8277330f729Sjoerg 
8287330f729Sjoerg   // Perform initialization analysis and ensure any implicit conversions
8297330f729Sjoerg   // (such as lvalue-to-rvalue) are enforced.
8307330f729Sjoerg   InitializedEntity Entity =
8317330f729Sjoerg       InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
8327330f729Sjoerg   InitializationKind Kind =
8337330f729Sjoerg       IsDirectInit
8347330f729Sjoerg           ? (CXXDirectInit ? InitializationKind::CreateDirect(
8357330f729Sjoerg                                  Loc, Init->getBeginLoc(), Init->getEndLoc())
8367330f729Sjoerg                            : InitializationKind::CreateDirectList(Loc))
8377330f729Sjoerg           : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
8387330f729Sjoerg 
8397330f729Sjoerg   MultiExprArg Args = Init;
8407330f729Sjoerg   if (CXXDirectInit)
8417330f729Sjoerg     Args =
8427330f729Sjoerg         MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
8437330f729Sjoerg   QualType DclT;
8447330f729Sjoerg   InitializationSequence InitSeq(*this, Entity, Kind, Args);
8457330f729Sjoerg   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8467330f729Sjoerg 
8477330f729Sjoerg   if (Result.isInvalid())
8487330f729Sjoerg     return QualType();
8497330f729Sjoerg 
8507330f729Sjoerg   Init = Result.getAs<Expr>();
8517330f729Sjoerg   return DeducedType;
8527330f729Sjoerg }
8537330f729Sjoerg 
createLambdaInitCaptureVarDecl(SourceLocation Loc,QualType InitCaptureType,SourceLocation EllipsisLoc,IdentifierInfo * Id,unsigned InitStyle,Expr * Init)8547330f729Sjoerg VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
8557330f729Sjoerg                                               QualType InitCaptureType,
8567330f729Sjoerg                                               SourceLocation EllipsisLoc,
8577330f729Sjoerg                                               IdentifierInfo *Id,
8587330f729Sjoerg                                               unsigned InitStyle, Expr *Init) {
8597330f729Sjoerg   // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
8607330f729Sjoerg   // rather than reconstructing it here.
8617330f729Sjoerg   TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
8627330f729Sjoerg   if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
8637330f729Sjoerg     PETL.setEllipsisLoc(EllipsisLoc);
8647330f729Sjoerg 
8657330f729Sjoerg   // Create a dummy variable representing the init-capture. This is not actually
8667330f729Sjoerg   // used as a variable, and only exists as a way to name and refer to the
8677330f729Sjoerg   // init-capture.
8687330f729Sjoerg   // FIXME: Pass in separate source locations for '&' and identifier.
8697330f729Sjoerg   VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
8707330f729Sjoerg                                    Loc, Id, InitCaptureType, TSI, SC_Auto);
8717330f729Sjoerg   NewVD->setInitCapture(true);
8727330f729Sjoerg   NewVD->setReferenced(true);
8737330f729Sjoerg   // FIXME: Pass in a VarDecl::InitializationStyle.
8747330f729Sjoerg   NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
8757330f729Sjoerg   NewVD->markUsed(Context);
8767330f729Sjoerg   NewVD->setInit(Init);
8777330f729Sjoerg   if (NewVD->isParameterPack())
8787330f729Sjoerg     getCurLambda()->LocalPacks.push_back(NewVD);
8797330f729Sjoerg   return NewVD;
8807330f729Sjoerg }
8817330f729Sjoerg 
addInitCapture(LambdaScopeInfo * LSI,VarDecl * Var)8827330f729Sjoerg void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
8837330f729Sjoerg   assert(Var->isInitCapture() && "init capture flag should be set");
8847330f729Sjoerg   LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
8857330f729Sjoerg                   /*isNested*/false, Var->getLocation(), SourceLocation(),
8867330f729Sjoerg                   Var->getType(), /*Invalid*/false);
8877330f729Sjoerg }
8887330f729Sjoerg 
ActOnStartOfLambdaDefinition(LambdaIntroducer & Intro,Declarator & ParamInfo,Scope * CurScope)8897330f729Sjoerg void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
8907330f729Sjoerg                                         Declarator &ParamInfo,
8917330f729Sjoerg                                         Scope *CurScope) {
8927330f729Sjoerg   LambdaScopeInfo *const LSI = getCurLambda();
8937330f729Sjoerg   assert(LSI && "LambdaScopeInfo should be on stack!");
8947330f729Sjoerg 
8957330f729Sjoerg   // Determine if we're within a context where we know that the lambda will
8967330f729Sjoerg   // be dependent, because there are template parameters in scope.
8977330f729Sjoerg   bool KnownDependent;
8987330f729Sjoerg   if (LSI->NumExplicitTemplateParams > 0) {
8997330f729Sjoerg     auto *TemplateParamScope = CurScope->getTemplateParamParent();
9007330f729Sjoerg     assert(TemplateParamScope &&
9017330f729Sjoerg            "Lambda with explicit template param list should establish a "
9027330f729Sjoerg            "template param scope");
9037330f729Sjoerg     assert(TemplateParamScope->getParent());
9047330f729Sjoerg     KnownDependent = TemplateParamScope->getParent()
9057330f729Sjoerg                                        ->getTemplateParamParent() != nullptr;
9067330f729Sjoerg   } else {
9077330f729Sjoerg     KnownDependent = CurScope->getTemplateParamParent() != nullptr;
9087330f729Sjoerg   }
9097330f729Sjoerg 
9107330f729Sjoerg   // Determine the signature of the call operator.
9117330f729Sjoerg   TypeSourceInfo *MethodTyInfo;
9127330f729Sjoerg   bool ExplicitParams = true;
9137330f729Sjoerg   bool ExplicitResultType = true;
9147330f729Sjoerg   bool ContainsUnexpandedParameterPack = false;
9157330f729Sjoerg   SourceLocation EndLoc;
9167330f729Sjoerg   SmallVector<ParmVarDecl *, 8> Params;
9177330f729Sjoerg   if (ParamInfo.getNumTypeObjects() == 0) {
9187330f729Sjoerg     // C++11 [expr.prim.lambda]p4:
9197330f729Sjoerg     //   If a lambda-expression does not include a lambda-declarator, it is as
9207330f729Sjoerg     //   if the lambda-declarator were ().
9217330f729Sjoerg     FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
9227330f729Sjoerg         /*IsVariadic=*/false, /*IsCXXMethod=*/true));
9237330f729Sjoerg     EPI.HasTrailingReturn = true;
9247330f729Sjoerg     EPI.TypeQuals.addConst();
925*e038c9c4Sjoerg     LangAS AS = getDefaultCXXMethodAddrSpace();
926*e038c9c4Sjoerg     if (AS != LangAS::Default)
927*e038c9c4Sjoerg       EPI.TypeQuals.addAddressSpace(AS);
928*e038c9c4Sjoerg 
9297330f729Sjoerg     // C++1y [expr.prim.lambda]:
9307330f729Sjoerg     //   The lambda return type is 'auto', which is replaced by the
9317330f729Sjoerg     //   trailing-return type if provided and/or deduced from 'return'
9327330f729Sjoerg     //   statements
9337330f729Sjoerg     // We don't do this before C++1y, because we don't support deduced return
9347330f729Sjoerg     // types there.
9357330f729Sjoerg     QualType DefaultTypeForNoTrailingReturn =
9367330f729Sjoerg         getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
9377330f729Sjoerg                                   : Context.DependentTy;
9387330f729Sjoerg     QualType MethodTy =
9397330f729Sjoerg         Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
9407330f729Sjoerg     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
9417330f729Sjoerg     ExplicitParams = false;
9427330f729Sjoerg     ExplicitResultType = false;
9437330f729Sjoerg     EndLoc = Intro.Range.getEnd();
9447330f729Sjoerg   } else {
9457330f729Sjoerg     assert(ParamInfo.isFunctionDeclarator() &&
9467330f729Sjoerg            "lambda-declarator is a function");
9477330f729Sjoerg     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
9487330f729Sjoerg 
9497330f729Sjoerg     // C++11 [expr.prim.lambda]p5:
9507330f729Sjoerg     //   This function call operator is declared const (9.3.1) if and only if
9517330f729Sjoerg     //   the lambda-expression's parameter-declaration-clause is not followed
9527330f729Sjoerg     //   by mutable. It is neither virtual nor declared volatile. [...]
9537330f729Sjoerg     if (!FTI.hasMutableQualifier()) {
9547330f729Sjoerg       FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
9557330f729Sjoerg                                                     SourceLocation());
9567330f729Sjoerg     }
9577330f729Sjoerg 
9587330f729Sjoerg     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
9597330f729Sjoerg     assert(MethodTyInfo && "no type from lambda-declarator");
9607330f729Sjoerg     EndLoc = ParamInfo.getSourceRange().getEnd();
9617330f729Sjoerg 
9627330f729Sjoerg     ExplicitResultType = FTI.hasTrailingReturnType();
9637330f729Sjoerg 
9647330f729Sjoerg     if (FTIHasNonVoidParameters(FTI)) {
9657330f729Sjoerg       Params.reserve(FTI.NumParams);
9667330f729Sjoerg       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
9677330f729Sjoerg         Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
9687330f729Sjoerg     }
9697330f729Sjoerg 
9707330f729Sjoerg     // Check for unexpanded parameter packs in the method type.
9717330f729Sjoerg     if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
9727330f729Sjoerg       DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
9737330f729Sjoerg                                       UPPC_DeclarationType);
9747330f729Sjoerg   }
9757330f729Sjoerg 
9767330f729Sjoerg   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
9777330f729Sjoerg                                                  KnownDependent, Intro.Default);
9787330f729Sjoerg   CXXMethodDecl *Method =
9797330f729Sjoerg       startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
980*e038c9c4Sjoerg                             ParamInfo.getDeclSpec().getConstexprSpecifier(),
981*e038c9c4Sjoerg                             ParamInfo.getTrailingRequiresClause());
9827330f729Sjoerg   if (ExplicitParams)
9837330f729Sjoerg     CheckCXXDefaultArguments(Method);
9847330f729Sjoerg 
9857330f729Sjoerg   // This represents the function body for the lambda function, check if we
9867330f729Sjoerg   // have to apply optnone due to a pragma.
9877330f729Sjoerg   AddRangeBasedOptnone(Method);
9887330f729Sjoerg 
9897330f729Sjoerg   // code_seg attribute on lambda apply to the method.
9907330f729Sjoerg   if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
9917330f729Sjoerg     Method->addAttr(A);
9927330f729Sjoerg 
9937330f729Sjoerg   // Attributes on the lambda apply to the method.
9947330f729Sjoerg   ProcessDeclAttributes(CurScope, Method, ParamInfo);
9957330f729Sjoerg 
996*e038c9c4Sjoerg   // CUDA lambdas get implicit host and device attributes.
9977330f729Sjoerg   if (getLangOpts().CUDA)
9987330f729Sjoerg     CUDASetLambdaAttrs(Method);
9997330f729Sjoerg 
1000*e038c9c4Sjoerg   // OpenMP lambdas might get assumumption attributes.
1001*e038c9c4Sjoerg   if (LangOpts.OpenMP)
1002*e038c9c4Sjoerg     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
1003*e038c9c4Sjoerg 
10047330f729Sjoerg   // Number the lambda for linkage purposes if necessary.
10057330f729Sjoerg   handleLambdaNumbering(Class, Method);
10067330f729Sjoerg 
10077330f729Sjoerg   // Introduce the function call operator as the current declaration context.
10087330f729Sjoerg   PushDeclContext(CurScope, Method);
10097330f729Sjoerg 
10107330f729Sjoerg   // Build the lambda scope.
10117330f729Sjoerg   buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
10127330f729Sjoerg                    ExplicitParams, ExplicitResultType, !Method->isConst());
10137330f729Sjoerg 
10147330f729Sjoerg   // C++11 [expr.prim.lambda]p9:
10157330f729Sjoerg   //   A lambda-expression whose smallest enclosing scope is a block scope is a
10167330f729Sjoerg   //   local lambda expression; any other lambda expression shall not have a
10177330f729Sjoerg   //   capture-default or simple-capture in its lambda-introducer.
10187330f729Sjoerg   //
10197330f729Sjoerg   // For simple-captures, this is covered by the check below that any named
10207330f729Sjoerg   // entity is a variable that can be captured.
10217330f729Sjoerg   //
10227330f729Sjoerg   // For DR1632, we also allow a capture-default in any context where we can
10237330f729Sjoerg   // odr-use 'this' (in particular, in a default initializer for a non-static
10247330f729Sjoerg   // data member).
10257330f729Sjoerg   if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
10267330f729Sjoerg       (getCurrentThisType().isNull() ||
10277330f729Sjoerg        CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
10287330f729Sjoerg                            /*BuildAndDiagnose*/false)))
10297330f729Sjoerg     Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
10307330f729Sjoerg 
10317330f729Sjoerg   // Distinct capture names, for diagnostics.
10327330f729Sjoerg   llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
10337330f729Sjoerg 
10347330f729Sjoerg   // Handle explicit captures.
10357330f729Sjoerg   SourceLocation PrevCaptureLoc
10367330f729Sjoerg     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
10377330f729Sjoerg   for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
10387330f729Sjoerg        PrevCaptureLoc = C->Loc, ++C) {
10397330f729Sjoerg     if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
10407330f729Sjoerg       if (C->Kind == LCK_StarThis)
10417330f729Sjoerg         Diag(C->Loc, !getLangOpts().CPlusPlus17
10427330f729Sjoerg                              ? diag::ext_star_this_lambda_capture_cxx17
10437330f729Sjoerg                              : diag::warn_cxx14_compat_star_this_lambda_capture);
10447330f729Sjoerg 
10457330f729Sjoerg       // C++11 [expr.prim.lambda]p8:
10467330f729Sjoerg       //   An identifier or this shall not appear more than once in a
10477330f729Sjoerg       //   lambda-capture.
10487330f729Sjoerg       if (LSI->isCXXThisCaptured()) {
10497330f729Sjoerg         Diag(C->Loc, diag::err_capture_more_than_once)
10507330f729Sjoerg             << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
10517330f729Sjoerg             << FixItHint::CreateRemoval(
10527330f729Sjoerg                    SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
10537330f729Sjoerg         continue;
10547330f729Sjoerg       }
10557330f729Sjoerg 
10567330f729Sjoerg       // C++2a [expr.prim.lambda]p8:
10577330f729Sjoerg       //  If a lambda-capture includes a capture-default that is =,
10587330f729Sjoerg       //  each simple-capture of that lambda-capture shall be of the form
10597330f729Sjoerg       //  "&identifier", "this", or "* this". [ Note: The form [&,this] is
10607330f729Sjoerg       //  redundant but accepted for compatibility with ISO C++14. --end note ]
10617330f729Sjoerg       if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1062*e038c9c4Sjoerg         Diag(C->Loc, !getLangOpts().CPlusPlus20
1063*e038c9c4Sjoerg                          ? diag::ext_equals_this_lambda_capture_cxx20
10647330f729Sjoerg                          : diag::warn_cxx17_compat_equals_this_lambda_capture);
10657330f729Sjoerg 
10667330f729Sjoerg       // C++11 [expr.prim.lambda]p12:
10677330f729Sjoerg       //   If this is captured by a local lambda expression, its nearest
10687330f729Sjoerg       //   enclosing function shall be a non-static member function.
10697330f729Sjoerg       QualType ThisCaptureType = getCurrentThisType();
10707330f729Sjoerg       if (ThisCaptureType.isNull()) {
10717330f729Sjoerg         Diag(C->Loc, diag::err_this_capture) << true;
10727330f729Sjoerg         continue;
10737330f729Sjoerg       }
10747330f729Sjoerg 
10757330f729Sjoerg       CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
10767330f729Sjoerg                           /*FunctionScopeIndexToStopAtPtr*/ nullptr,
10777330f729Sjoerg                           C->Kind == LCK_StarThis);
10787330f729Sjoerg       if (!LSI->Captures.empty())
10797330f729Sjoerg         LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
10807330f729Sjoerg       continue;
10817330f729Sjoerg     }
10827330f729Sjoerg 
10837330f729Sjoerg     assert(C->Id && "missing identifier for capture");
10847330f729Sjoerg 
10857330f729Sjoerg     if (C->Init.isInvalid())
10867330f729Sjoerg       continue;
10877330f729Sjoerg 
10887330f729Sjoerg     VarDecl *Var = nullptr;
10897330f729Sjoerg     if (C->Init.isUsable()) {
10907330f729Sjoerg       Diag(C->Loc, getLangOpts().CPlusPlus14
10917330f729Sjoerg                        ? diag::warn_cxx11_compat_init_capture
10927330f729Sjoerg                        : diag::ext_init_capture);
10937330f729Sjoerg 
10947330f729Sjoerg       // If the initializer expression is usable, but the InitCaptureType
10957330f729Sjoerg       // is not, then an error has occurred - so ignore the capture for now.
10967330f729Sjoerg       // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
10977330f729Sjoerg       // FIXME: we should create the init capture variable and mark it invalid
10987330f729Sjoerg       // in this case.
10997330f729Sjoerg       if (C->InitCaptureType.get().isNull())
11007330f729Sjoerg         continue;
11017330f729Sjoerg 
11027330f729Sjoerg       if (C->Init.get()->containsUnexpandedParameterPack() &&
11037330f729Sjoerg           !C->InitCaptureType.get()->getAs<PackExpansionType>())
11047330f729Sjoerg         DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
11057330f729Sjoerg 
11067330f729Sjoerg       unsigned InitStyle;
11077330f729Sjoerg       switch (C->InitKind) {
11087330f729Sjoerg       case LambdaCaptureInitKind::NoInit:
11097330f729Sjoerg         llvm_unreachable("not an init-capture?");
11107330f729Sjoerg       case LambdaCaptureInitKind::CopyInit:
11117330f729Sjoerg         InitStyle = VarDecl::CInit;
11127330f729Sjoerg         break;
11137330f729Sjoerg       case LambdaCaptureInitKind::DirectInit:
11147330f729Sjoerg         InitStyle = VarDecl::CallInit;
11157330f729Sjoerg         break;
11167330f729Sjoerg       case LambdaCaptureInitKind::ListInit:
11177330f729Sjoerg         InitStyle = VarDecl::ListInit;
11187330f729Sjoerg         break;
11197330f729Sjoerg       }
11207330f729Sjoerg       Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
11217330f729Sjoerg                                            C->EllipsisLoc, C->Id, InitStyle,
11227330f729Sjoerg                                            C->Init.get());
11237330f729Sjoerg       // C++1y [expr.prim.lambda]p11:
11247330f729Sjoerg       //   An init-capture behaves as if it declares and explicitly
11257330f729Sjoerg       //   captures a variable [...] whose declarative region is the
11267330f729Sjoerg       //   lambda-expression's compound-statement
11277330f729Sjoerg       if (Var)
11287330f729Sjoerg         PushOnScopeChains(Var, CurScope, false);
11297330f729Sjoerg     } else {
11307330f729Sjoerg       assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
11317330f729Sjoerg              "init capture has valid but null init?");
11327330f729Sjoerg 
11337330f729Sjoerg       // C++11 [expr.prim.lambda]p8:
11347330f729Sjoerg       //   If a lambda-capture includes a capture-default that is &, the
11357330f729Sjoerg       //   identifiers in the lambda-capture shall not be preceded by &.
11367330f729Sjoerg       //   If a lambda-capture includes a capture-default that is =, [...]
11377330f729Sjoerg       //   each identifier it contains shall be preceded by &.
11387330f729Sjoerg       if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
11397330f729Sjoerg         Diag(C->Loc, diag::err_reference_capture_with_reference_default)
11407330f729Sjoerg             << FixItHint::CreateRemoval(
11417330f729Sjoerg                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
11427330f729Sjoerg         continue;
11437330f729Sjoerg       } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
11447330f729Sjoerg         Diag(C->Loc, diag::err_copy_capture_with_copy_default)
11457330f729Sjoerg             << FixItHint::CreateRemoval(
11467330f729Sjoerg                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
11477330f729Sjoerg         continue;
11487330f729Sjoerg       }
11497330f729Sjoerg 
11507330f729Sjoerg       // C++11 [expr.prim.lambda]p10:
11517330f729Sjoerg       //   The identifiers in a capture-list are looked up using the usual
11527330f729Sjoerg       //   rules for unqualified name lookup (3.4.1)
11537330f729Sjoerg       DeclarationNameInfo Name(C->Id, C->Loc);
11547330f729Sjoerg       LookupResult R(*this, Name, LookupOrdinaryName);
11557330f729Sjoerg       LookupName(R, CurScope);
11567330f729Sjoerg       if (R.isAmbiguous())
11577330f729Sjoerg         continue;
11587330f729Sjoerg       if (R.empty()) {
11597330f729Sjoerg         // FIXME: Disable corrections that would add qualification?
11607330f729Sjoerg         CXXScopeSpec ScopeSpec;
11617330f729Sjoerg         DeclFilterCCC<VarDecl> Validator{};
11627330f729Sjoerg         if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
11637330f729Sjoerg           continue;
11647330f729Sjoerg       }
11657330f729Sjoerg 
11667330f729Sjoerg       Var = R.getAsSingle<VarDecl>();
11677330f729Sjoerg       if (Var && DiagnoseUseOfDecl(Var, C->Loc))
11687330f729Sjoerg         continue;
11697330f729Sjoerg     }
11707330f729Sjoerg 
11717330f729Sjoerg     // C++11 [expr.prim.lambda]p8:
11727330f729Sjoerg     //   An identifier or this shall not appear more than once in a
11737330f729Sjoerg     //   lambda-capture.
11747330f729Sjoerg     if (!CaptureNames.insert(C->Id).second) {
11757330f729Sjoerg       if (Var && LSI->isCaptured(Var)) {
11767330f729Sjoerg         Diag(C->Loc, diag::err_capture_more_than_once)
11777330f729Sjoerg             << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
11787330f729Sjoerg             << FixItHint::CreateRemoval(
11797330f729Sjoerg                    SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
11807330f729Sjoerg       } else
11817330f729Sjoerg         // Previous capture captured something different (one or both was
11827330f729Sjoerg         // an init-cpature): no fixit.
11837330f729Sjoerg         Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
11847330f729Sjoerg       continue;
11857330f729Sjoerg     }
11867330f729Sjoerg 
11877330f729Sjoerg     // C++11 [expr.prim.lambda]p10:
11887330f729Sjoerg     //   [...] each such lookup shall find a variable with automatic storage
11897330f729Sjoerg     //   duration declared in the reaching scope of the local lambda expression.
11907330f729Sjoerg     // Note that the 'reaching scope' check happens in tryCaptureVariable().
11917330f729Sjoerg     if (!Var) {
11927330f729Sjoerg       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
11937330f729Sjoerg       continue;
11947330f729Sjoerg     }
11957330f729Sjoerg 
11967330f729Sjoerg     // Ignore invalid decls; they'll just confuse the code later.
11977330f729Sjoerg     if (Var->isInvalidDecl())
11987330f729Sjoerg       continue;
11997330f729Sjoerg 
12007330f729Sjoerg     if (!Var->hasLocalStorage()) {
12017330f729Sjoerg       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
12027330f729Sjoerg       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
12037330f729Sjoerg       continue;
12047330f729Sjoerg     }
12057330f729Sjoerg 
12067330f729Sjoerg     // C++11 [expr.prim.lambda]p23:
12077330f729Sjoerg     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
12087330f729Sjoerg     SourceLocation EllipsisLoc;
12097330f729Sjoerg     if (C->EllipsisLoc.isValid()) {
12107330f729Sjoerg       if (Var->isParameterPack()) {
12117330f729Sjoerg         EllipsisLoc = C->EllipsisLoc;
12127330f729Sjoerg       } else {
12137330f729Sjoerg         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12147330f729Sjoerg             << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
12157330f729Sjoerg                                    : SourceRange(C->Loc));
12167330f729Sjoerg 
12177330f729Sjoerg         // Just ignore the ellipsis.
12187330f729Sjoerg       }
12197330f729Sjoerg     } else if (Var->isParameterPack()) {
12207330f729Sjoerg       ContainsUnexpandedParameterPack = true;
12217330f729Sjoerg     }
12227330f729Sjoerg 
12237330f729Sjoerg     if (C->Init.isUsable()) {
12247330f729Sjoerg       addInitCapture(LSI, Var);
12257330f729Sjoerg     } else {
12267330f729Sjoerg       TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
12277330f729Sjoerg                                                    TryCapture_ExplicitByVal;
12287330f729Sjoerg       tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
12297330f729Sjoerg     }
12307330f729Sjoerg     if (!LSI->Captures.empty())
12317330f729Sjoerg       LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
12327330f729Sjoerg   }
12337330f729Sjoerg   finishLambdaExplicitCaptures(LSI);
12347330f729Sjoerg 
12357330f729Sjoerg   LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
12367330f729Sjoerg 
12377330f729Sjoerg   // Add lambda parameters into scope.
12387330f729Sjoerg   addLambdaParameters(Intro.Captures, Method, CurScope);
12397330f729Sjoerg 
12407330f729Sjoerg   // Enter a new evaluation context to insulate the lambda from any
12417330f729Sjoerg   // cleanups from the enclosing full-expression.
12427330f729Sjoerg   PushExpressionEvaluationContext(
1243*e038c9c4Sjoerg       LSI->CallOperator->isConsteval()
1244*e038c9c4Sjoerg           ? ExpressionEvaluationContext::ConstantEvaluated
1245*e038c9c4Sjoerg           : ExpressionEvaluationContext::PotentiallyEvaluated);
12467330f729Sjoerg }
12477330f729Sjoerg 
ActOnLambdaError(SourceLocation StartLoc,Scope * CurScope,bool IsInstantiation)12487330f729Sjoerg void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
12497330f729Sjoerg                             bool IsInstantiation) {
12507330f729Sjoerg   LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
12517330f729Sjoerg 
12527330f729Sjoerg   // Leave the expression-evaluation context.
12537330f729Sjoerg   DiscardCleanupsInEvaluationContext();
12547330f729Sjoerg   PopExpressionEvaluationContext();
12557330f729Sjoerg 
12567330f729Sjoerg   // Leave the context of the lambda.
12577330f729Sjoerg   if (!IsInstantiation)
12587330f729Sjoerg     PopDeclContext();
12597330f729Sjoerg 
12607330f729Sjoerg   // Finalize the lambda.
12617330f729Sjoerg   CXXRecordDecl *Class = LSI->Lambda;
12627330f729Sjoerg   Class->setInvalidDecl();
12637330f729Sjoerg   SmallVector<Decl*, 4> Fields(Class->fields());
12647330f729Sjoerg   ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
12657330f729Sjoerg               SourceLocation(), ParsedAttributesView());
1266*e038c9c4Sjoerg   CheckCompletedCXXClass(nullptr, Class);
12677330f729Sjoerg 
12687330f729Sjoerg   PopFunctionScopeInfo();
12697330f729Sjoerg }
12707330f729Sjoerg 
1271*e038c9c4Sjoerg template <typename Func>
repeatForLambdaConversionFunctionCallingConvs(Sema & S,const FunctionProtoType & CallOpProto,Func F)1272*e038c9c4Sjoerg static void repeatForLambdaConversionFunctionCallingConvs(
1273*e038c9c4Sjoerg     Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1274*e038c9c4Sjoerg   CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1275*e038c9c4Sjoerg       CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1276*e038c9c4Sjoerg   CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1277*e038c9c4Sjoerg       CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1278*e038c9c4Sjoerg   CallingConv CallOpCC = CallOpProto.getCallConv();
1279*e038c9c4Sjoerg 
1280*e038c9c4Sjoerg   /// Implement emitting a version of the operator for many of the calling
1281*e038c9c4Sjoerg   /// conventions for MSVC, as described here:
1282*e038c9c4Sjoerg   /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1283*e038c9c4Sjoerg   /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1284*e038c9c4Sjoerg   /// vectorcall are generated by MSVC when it is supported by the target.
1285*e038c9c4Sjoerg   /// Additionally, we are ensuring that the default-free/default-member and
1286*e038c9c4Sjoerg   /// call-operator calling convention are generated as well.
1287*e038c9c4Sjoerg   /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1288*e038c9c4Sjoerg   /// 'member default', despite MSVC not doing so. We do this in order to ensure
1289*e038c9c4Sjoerg   /// that someone who intentionally places 'thiscall' on the lambda call
1290*e038c9c4Sjoerg   /// operator will still get that overload, since we don't have the a way of
1291*e038c9c4Sjoerg   /// detecting the attribute by the time we get here.
1292*e038c9c4Sjoerg   if (S.getLangOpts().MSVCCompat) {
1293*e038c9c4Sjoerg     CallingConv Convs[] = {
1294*e038c9c4Sjoerg         CC_C,        CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1295*e038c9c4Sjoerg         DefaultFree, DefaultMember, CallOpCC};
1296*e038c9c4Sjoerg     llvm::sort(Convs);
1297*e038c9c4Sjoerg     llvm::iterator_range<CallingConv *> Range(
1298*e038c9c4Sjoerg         std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1299*e038c9c4Sjoerg     const TargetInfo &TI = S.getASTContext().getTargetInfo();
1300*e038c9c4Sjoerg 
1301*e038c9c4Sjoerg     for (CallingConv C : Range) {
1302*e038c9c4Sjoerg       if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
1303*e038c9c4Sjoerg         F(C);
1304*e038c9c4Sjoerg     }
1305*e038c9c4Sjoerg     return;
1306*e038c9c4Sjoerg   }
1307*e038c9c4Sjoerg 
1308*e038c9c4Sjoerg   if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1309*e038c9c4Sjoerg     F(DefaultFree);
1310*e038c9c4Sjoerg     F(DefaultMember);
1311*e038c9c4Sjoerg   } else {
1312*e038c9c4Sjoerg     F(CallOpCC);
1313*e038c9c4Sjoerg   }
1314*e038c9c4Sjoerg }
1315*e038c9c4Sjoerg 
1316*e038c9c4Sjoerg // Returns the 'standard' calling convention to be used for the lambda
1317*e038c9c4Sjoerg // conversion function, that is, the 'free' function calling convention unless
1318*e038c9c4Sjoerg // it is overridden by a non-default calling convention attribute.
1319*e038c9c4Sjoerg static CallingConv
getLambdaConversionFunctionCallConv(Sema & S,const FunctionProtoType * CallOpProto)1320*e038c9c4Sjoerg getLambdaConversionFunctionCallConv(Sema &S,
13217330f729Sjoerg                                     const FunctionProtoType *CallOpProto) {
1322*e038c9c4Sjoerg   CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1323*e038c9c4Sjoerg       CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1324*e038c9c4Sjoerg   CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1325*e038c9c4Sjoerg       CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1326*e038c9c4Sjoerg   CallingConv CallOpCC = CallOpProto->getCallConv();
1327*e038c9c4Sjoerg 
1328*e038c9c4Sjoerg   // If the call-operator hasn't been changed, return both the 'free' and
1329*e038c9c4Sjoerg   // 'member' function calling convention.
1330*e038c9c4Sjoerg   if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1331*e038c9c4Sjoerg     return DefaultFree;
1332*e038c9c4Sjoerg   return CallOpCC;
1333*e038c9c4Sjoerg }
1334*e038c9c4Sjoerg 
getLambdaConversionFunctionResultType(const FunctionProtoType * CallOpProto,CallingConv CC)1335*e038c9c4Sjoerg QualType Sema::getLambdaConversionFunctionResultType(
1336*e038c9c4Sjoerg     const FunctionProtoType *CallOpProto, CallingConv CC) {
13377330f729Sjoerg   const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
13387330f729Sjoerg       CallOpProto->getExtProtoInfo();
13397330f729Sjoerg   FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
13407330f729Sjoerg   InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
13417330f729Sjoerg   InvokerExtInfo.TypeQuals = Qualifiers();
13427330f729Sjoerg   assert(InvokerExtInfo.RefQualifier == RQ_None &&
13437330f729Sjoerg          "Lambda's call operator should not have a reference qualifier");
13447330f729Sjoerg   return Context.getFunctionType(CallOpProto->getReturnType(),
13457330f729Sjoerg                                  CallOpProto->getParamTypes(), InvokerExtInfo);
13467330f729Sjoerg }
13477330f729Sjoerg 
13487330f729Sjoerg /// Add a lambda's conversion to function pointer, as described in
13497330f729Sjoerg /// C++11 [expr.prim.lambda]p6.
addFunctionPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator,QualType InvokerFunctionTy)1350*e038c9c4Sjoerg static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
13517330f729Sjoerg                                          CXXRecordDecl *Class,
1352*e038c9c4Sjoerg                                          CXXMethodDecl *CallOperator,
1353*e038c9c4Sjoerg                                          QualType InvokerFunctionTy) {
13547330f729Sjoerg   // This conversion is explicitly disabled if the lambda's function has
13557330f729Sjoerg   // pass_object_size attributes on any of its parameters.
13567330f729Sjoerg   auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
13577330f729Sjoerg     return P->hasAttr<PassObjectSizeAttr>();
13587330f729Sjoerg   };
13597330f729Sjoerg   if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
13607330f729Sjoerg     return;
13617330f729Sjoerg 
13627330f729Sjoerg   // Add the conversion to function pointer.
13637330f729Sjoerg   QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
13647330f729Sjoerg 
13657330f729Sjoerg   // Create the type of the conversion function.
13667330f729Sjoerg   FunctionProtoType::ExtProtoInfo ConvExtInfo(
13677330f729Sjoerg       S.Context.getDefaultCallingConvention(
13687330f729Sjoerg       /*IsVariadic=*/false, /*IsCXXMethod=*/true));
13697330f729Sjoerg   // The conversion function is always const and noexcept.
13707330f729Sjoerg   ConvExtInfo.TypeQuals = Qualifiers();
13717330f729Sjoerg   ConvExtInfo.TypeQuals.addConst();
13727330f729Sjoerg   ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
13737330f729Sjoerg   QualType ConvTy =
13747330f729Sjoerg       S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
13757330f729Sjoerg 
13767330f729Sjoerg   SourceLocation Loc = IntroducerRange.getBegin();
13777330f729Sjoerg   DeclarationName ConversionName
13787330f729Sjoerg     = S.Context.DeclarationNames.getCXXConversionFunctionName(
13797330f729Sjoerg         S.Context.getCanonicalType(PtrToFunctionTy));
13807330f729Sjoerg   // Construct a TypeSourceInfo for the conversion function, and wire
13817330f729Sjoerg   // all the parameters appropriately for the FunctionProtoTypeLoc
13827330f729Sjoerg   // so that everything works during transformation/instantiation of
13837330f729Sjoerg   // generic lambdas.
13847330f729Sjoerg   // The main reason for wiring up the parameters of the conversion
13857330f729Sjoerg   // function with that of the call operator is so that constructs
13867330f729Sjoerg   // like the following work:
13877330f729Sjoerg   // auto L = [](auto b) {                <-- 1
13887330f729Sjoerg   //   return [](auto a) -> decltype(a) { <-- 2
13897330f729Sjoerg   //      return a;
13907330f729Sjoerg   //   };
13917330f729Sjoerg   // };
13927330f729Sjoerg   // int (*fp)(int) = L(5);
13937330f729Sjoerg   // Because the trailing return type can contain DeclRefExprs that refer
13947330f729Sjoerg   // to the original call operator's variables, we hijack the call
13957330f729Sjoerg   // operators ParmVarDecls below.
13967330f729Sjoerg   TypeSourceInfo *ConvNamePtrToFunctionTSI =
13977330f729Sjoerg       S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1398*e038c9c4Sjoerg   DeclarationNameLoc ConvNameLoc =
1399*e038c9c4Sjoerg       DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
14007330f729Sjoerg 
14017330f729Sjoerg   // The conversion function is a conversion to a pointer-to-function.
14027330f729Sjoerg   TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
14037330f729Sjoerg   FunctionProtoTypeLoc ConvTL =
14047330f729Sjoerg       ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
14057330f729Sjoerg   // Get the result of the conversion function which is a pointer-to-function.
14067330f729Sjoerg   PointerTypeLoc PtrToFunctionTL =
14077330f729Sjoerg       ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
14087330f729Sjoerg   // Do the same for the TypeSourceInfo that is used to name the conversion
14097330f729Sjoerg   // operator.
14107330f729Sjoerg   PointerTypeLoc ConvNamePtrToFunctionTL =
14117330f729Sjoerg       ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
14127330f729Sjoerg 
14137330f729Sjoerg   // Get the underlying function types that the conversion function will
14147330f729Sjoerg   // be converting to (should match the type of the call operator).
14157330f729Sjoerg   FunctionProtoTypeLoc CallOpConvTL =
14167330f729Sjoerg       PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
14177330f729Sjoerg   FunctionProtoTypeLoc CallOpConvNameTL =
14187330f729Sjoerg     ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
14197330f729Sjoerg 
14207330f729Sjoerg   // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
14217330f729Sjoerg   // These parameter's are essentially used to transform the name and
14227330f729Sjoerg   // the type of the conversion operator.  By using the same parameters
14237330f729Sjoerg   // as the call operator's we don't have to fix any back references that
14247330f729Sjoerg   // the trailing return type of the call operator's uses (such as
14257330f729Sjoerg   // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
14267330f729Sjoerg   // - we can simply use the return type of the call operator, and
14277330f729Sjoerg   // everything should work.
14287330f729Sjoerg   SmallVector<ParmVarDecl *, 4> InvokerParams;
14297330f729Sjoerg   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
14307330f729Sjoerg     ParmVarDecl *From = CallOperator->getParamDecl(I);
14317330f729Sjoerg 
14327330f729Sjoerg     InvokerParams.push_back(ParmVarDecl::Create(
14337330f729Sjoerg         S.Context,
14347330f729Sjoerg         // Temporarily add to the TU. This is set to the invoker below.
14357330f729Sjoerg         S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
14367330f729Sjoerg         From->getLocation(), From->getIdentifier(), From->getType(),
14377330f729Sjoerg         From->getTypeSourceInfo(), From->getStorageClass(),
14387330f729Sjoerg         /*DefArg=*/nullptr));
14397330f729Sjoerg     CallOpConvTL.setParam(I, From);
14407330f729Sjoerg     CallOpConvNameTL.setParam(I, From);
14417330f729Sjoerg   }
14427330f729Sjoerg 
14437330f729Sjoerg   CXXConversionDecl *Conversion = CXXConversionDecl::Create(
14447330f729Sjoerg       S.Context, Class, Loc,
14457330f729Sjoerg       DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
14467330f729Sjoerg       /*isInline=*/true, ExplicitSpecifier(),
1447*e038c9c4Sjoerg       S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1448*e038c9c4Sjoerg                                   : ConstexprSpecKind::Unspecified,
14497330f729Sjoerg       CallOperator->getBody()->getEndLoc());
14507330f729Sjoerg   Conversion->setAccess(AS_public);
14517330f729Sjoerg   Conversion->setImplicit(true);
14527330f729Sjoerg 
14537330f729Sjoerg   if (Class->isGenericLambda()) {
14547330f729Sjoerg     // Create a template version of the conversion operator, using the template
14557330f729Sjoerg     // parameter list of the function call operator.
14567330f729Sjoerg     FunctionTemplateDecl *TemplateCallOperator =
14577330f729Sjoerg             CallOperator->getDescribedFunctionTemplate();
14587330f729Sjoerg     FunctionTemplateDecl *ConversionTemplate =
14597330f729Sjoerg                   FunctionTemplateDecl::Create(S.Context, Class,
14607330f729Sjoerg                                       Loc, ConversionName,
14617330f729Sjoerg                                       TemplateCallOperator->getTemplateParameters(),
14627330f729Sjoerg                                       Conversion);
14637330f729Sjoerg     ConversionTemplate->setAccess(AS_public);
14647330f729Sjoerg     ConversionTemplate->setImplicit(true);
14657330f729Sjoerg     Conversion->setDescribedFunctionTemplate(ConversionTemplate);
14667330f729Sjoerg     Class->addDecl(ConversionTemplate);
14677330f729Sjoerg   } else
14687330f729Sjoerg     Class->addDecl(Conversion);
14697330f729Sjoerg   // Add a non-static member function that will be the result of
14707330f729Sjoerg   // the conversion with a certain unique ID.
14717330f729Sjoerg   DeclarationName InvokerName = &S.Context.Idents.get(
14727330f729Sjoerg                                                  getLambdaStaticInvokerName());
14737330f729Sjoerg   // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
14747330f729Sjoerg   // we should get a prebuilt TrivialTypeSourceInfo from Context
14757330f729Sjoerg   // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
14767330f729Sjoerg   // then rewire the parameters accordingly, by hoisting up the InvokeParams
14777330f729Sjoerg   // loop below and then use its Params to set Invoke->setParams(...) below.
14787330f729Sjoerg   // This would avoid the 'const' qualifier of the calloperator from
14797330f729Sjoerg   // contaminating the type of the invoker, which is currently adjusted
14807330f729Sjoerg   // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
14817330f729Sjoerg   // trailing return type of the invoker would require a visitor to rebuild
14827330f729Sjoerg   // the trailing return type and adjusting all back DeclRefExpr's to refer
14837330f729Sjoerg   // to the new static invoker parameters - not the call operator's.
14847330f729Sjoerg   CXXMethodDecl *Invoke = CXXMethodDecl::Create(
14857330f729Sjoerg       S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
14867330f729Sjoerg       InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1487*e038c9c4Sjoerg       /*isInline=*/true, ConstexprSpecKind::Unspecified,
1488*e038c9c4Sjoerg       CallOperator->getBody()->getEndLoc());
14897330f729Sjoerg   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
14907330f729Sjoerg     InvokerParams[I]->setOwningFunction(Invoke);
14917330f729Sjoerg   Invoke->setParams(InvokerParams);
14927330f729Sjoerg   Invoke->setAccess(AS_private);
14937330f729Sjoerg   Invoke->setImplicit(true);
14947330f729Sjoerg   if (Class->isGenericLambda()) {
14957330f729Sjoerg     FunctionTemplateDecl *TemplateCallOperator =
14967330f729Sjoerg             CallOperator->getDescribedFunctionTemplate();
14977330f729Sjoerg     FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
14987330f729Sjoerg                           S.Context, Class, Loc, InvokerName,
14997330f729Sjoerg                           TemplateCallOperator->getTemplateParameters(),
15007330f729Sjoerg                           Invoke);
15017330f729Sjoerg     StaticInvokerTemplate->setAccess(AS_private);
15027330f729Sjoerg     StaticInvokerTemplate->setImplicit(true);
15037330f729Sjoerg     Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
15047330f729Sjoerg     Class->addDecl(StaticInvokerTemplate);
15057330f729Sjoerg   } else
15067330f729Sjoerg     Class->addDecl(Invoke);
15077330f729Sjoerg }
15087330f729Sjoerg 
1509*e038c9c4Sjoerg /// Add a lambda's conversion to function pointers, as described in
1510*e038c9c4Sjoerg /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1511*e038c9c4Sjoerg /// single pointer conversion. In the event that the default calling convention
1512*e038c9c4Sjoerg /// for free and member functions is different, it will emit both conventions.
addFunctionPointerConversions(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)1513*e038c9c4Sjoerg static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1514*e038c9c4Sjoerg                                           CXXRecordDecl *Class,
1515*e038c9c4Sjoerg                                           CXXMethodDecl *CallOperator) {
1516*e038c9c4Sjoerg   const FunctionProtoType *CallOpProto =
1517*e038c9c4Sjoerg       CallOperator->getType()->castAs<FunctionProtoType>();
1518*e038c9c4Sjoerg 
1519*e038c9c4Sjoerg   repeatForLambdaConversionFunctionCallingConvs(
1520*e038c9c4Sjoerg       S, *CallOpProto, [&](CallingConv CC) {
1521*e038c9c4Sjoerg         QualType InvokerFunctionTy =
1522*e038c9c4Sjoerg             S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1523*e038c9c4Sjoerg         addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1524*e038c9c4Sjoerg                                      InvokerFunctionTy);
1525*e038c9c4Sjoerg       });
1526*e038c9c4Sjoerg }
1527*e038c9c4Sjoerg 
15287330f729Sjoerg /// Add a lambda's conversion to block pointer.
addBlockPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)15297330f729Sjoerg static void addBlockPointerConversion(Sema &S,
15307330f729Sjoerg                                       SourceRange IntroducerRange,
15317330f729Sjoerg                                       CXXRecordDecl *Class,
15327330f729Sjoerg                                       CXXMethodDecl *CallOperator) {
1533*e038c9c4Sjoerg   const FunctionProtoType *CallOpProto =
1534*e038c9c4Sjoerg       CallOperator->getType()->castAs<FunctionProtoType>();
15357330f729Sjoerg   QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1536*e038c9c4Sjoerg       CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
15377330f729Sjoerg   QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
15387330f729Sjoerg 
15397330f729Sjoerg   FunctionProtoType::ExtProtoInfo ConversionEPI(
15407330f729Sjoerg       S.Context.getDefaultCallingConvention(
15417330f729Sjoerg           /*IsVariadic=*/false, /*IsCXXMethod=*/true));
15427330f729Sjoerg   ConversionEPI.TypeQuals = Qualifiers();
15437330f729Sjoerg   ConversionEPI.TypeQuals.addConst();
15447330f729Sjoerg   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
15457330f729Sjoerg 
15467330f729Sjoerg   SourceLocation Loc = IntroducerRange.getBegin();
15477330f729Sjoerg   DeclarationName Name
15487330f729Sjoerg     = S.Context.DeclarationNames.getCXXConversionFunctionName(
15497330f729Sjoerg         S.Context.getCanonicalType(BlockPtrTy));
1550*e038c9c4Sjoerg   DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1551*e038c9c4Sjoerg       S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
15527330f729Sjoerg   CXXConversionDecl *Conversion = CXXConversionDecl::Create(
15537330f729Sjoerg       S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
15547330f729Sjoerg       S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1555*e038c9c4Sjoerg       /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
15567330f729Sjoerg       CallOperator->getBody()->getEndLoc());
15577330f729Sjoerg   Conversion->setAccess(AS_public);
15587330f729Sjoerg   Conversion->setImplicit(true);
15597330f729Sjoerg   Class->addDecl(Conversion);
15607330f729Sjoerg }
15617330f729Sjoerg 
BuildCaptureInit(const Capture & Cap,SourceLocation ImplicitCaptureLoc,bool IsOpenMPMapping)15627330f729Sjoerg ExprResult Sema::BuildCaptureInit(const Capture &Cap,
15637330f729Sjoerg                                   SourceLocation ImplicitCaptureLoc,
15647330f729Sjoerg                                   bool IsOpenMPMapping) {
15657330f729Sjoerg   // VLA captures don't have a stored initialization expression.
15667330f729Sjoerg   if (Cap.isVLATypeCapture())
15677330f729Sjoerg     return ExprResult();
15687330f729Sjoerg 
15697330f729Sjoerg   // An init-capture is initialized directly from its stored initializer.
15707330f729Sjoerg   if (Cap.isInitCapture())
15717330f729Sjoerg     return Cap.getVariable()->getInit();
15727330f729Sjoerg 
15737330f729Sjoerg   // For anything else, build an initialization expression. For an implicit
15747330f729Sjoerg   // capture, the capture notionally happens at the capture-default, so use
15757330f729Sjoerg   // that location here.
15767330f729Sjoerg   SourceLocation Loc =
15777330f729Sjoerg       ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
15787330f729Sjoerg 
15797330f729Sjoerg   // C++11 [expr.prim.lambda]p21:
15807330f729Sjoerg   //   When the lambda-expression is evaluated, the entities that
15817330f729Sjoerg   //   are captured by copy are used to direct-initialize each
15827330f729Sjoerg   //   corresponding non-static data member of the resulting closure
15837330f729Sjoerg   //   object. (For array members, the array elements are
15847330f729Sjoerg   //   direct-initialized in increasing subscript order.) These
15857330f729Sjoerg   //   initializations are performed in the (unspecified) order in
15867330f729Sjoerg   //   which the non-static data members are declared.
15877330f729Sjoerg 
15887330f729Sjoerg   // C++ [expr.prim.lambda]p12:
15897330f729Sjoerg   //   An entity captured by a lambda-expression is odr-used (3.2) in
15907330f729Sjoerg   //   the scope containing the lambda-expression.
15917330f729Sjoerg   ExprResult Init;
15927330f729Sjoerg   IdentifierInfo *Name = nullptr;
15937330f729Sjoerg   if (Cap.isThisCapture()) {
15947330f729Sjoerg     QualType ThisTy = getCurrentThisType();
15957330f729Sjoerg     Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
15967330f729Sjoerg     if (Cap.isCopyCapture())
15977330f729Sjoerg       Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
15987330f729Sjoerg     else
15997330f729Sjoerg       Init = This;
16007330f729Sjoerg   } else {
16017330f729Sjoerg     assert(Cap.isVariableCapture() && "unknown kind of capture");
16027330f729Sjoerg     VarDecl *Var = Cap.getVariable();
16037330f729Sjoerg     Name = Var->getIdentifier();
16047330f729Sjoerg     Init = BuildDeclarationNameExpr(
16057330f729Sjoerg       CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16067330f729Sjoerg   }
16077330f729Sjoerg 
16087330f729Sjoerg   // In OpenMP, the capture kind doesn't actually describe how to capture:
16097330f729Sjoerg   // variables are "mapped" onto the device in a process that does not formally
16107330f729Sjoerg   // make a copy, even for a "copy capture".
16117330f729Sjoerg   if (IsOpenMPMapping)
16127330f729Sjoerg     return Init;
16137330f729Sjoerg 
16147330f729Sjoerg   if (Init.isInvalid())
16157330f729Sjoerg     return ExprError();
16167330f729Sjoerg 
16177330f729Sjoerg   Expr *InitExpr = Init.get();
16187330f729Sjoerg   InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
16197330f729Sjoerg       Name, Cap.getCaptureType(), Loc);
16207330f729Sjoerg   InitializationKind InitKind =
16217330f729Sjoerg       InitializationKind::CreateDirect(Loc, Loc, Loc);
16227330f729Sjoerg   InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
16237330f729Sjoerg   return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
16247330f729Sjoerg }
16257330f729Sjoerg 
ActOnLambdaExpr(SourceLocation StartLoc,Stmt * Body,Scope * CurScope)16267330f729Sjoerg ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
16277330f729Sjoerg                                  Scope *CurScope) {
16287330f729Sjoerg   LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
16297330f729Sjoerg   ActOnFinishFunctionBody(LSI.CallOperator, Body);
16307330f729Sjoerg   return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
16317330f729Sjoerg }
16327330f729Sjoerg 
16337330f729Sjoerg static LambdaCaptureDefault
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)16347330f729Sjoerg mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
16357330f729Sjoerg   switch (ICS) {
16367330f729Sjoerg   case CapturingScopeInfo::ImpCap_None:
16377330f729Sjoerg     return LCD_None;
16387330f729Sjoerg   case CapturingScopeInfo::ImpCap_LambdaByval:
16397330f729Sjoerg     return LCD_ByCopy;
16407330f729Sjoerg   case CapturingScopeInfo::ImpCap_CapturedRegion:
16417330f729Sjoerg   case CapturingScopeInfo::ImpCap_LambdaByref:
16427330f729Sjoerg     return LCD_ByRef;
16437330f729Sjoerg   case CapturingScopeInfo::ImpCap_Block:
16447330f729Sjoerg     llvm_unreachable("block capture in lambda");
16457330f729Sjoerg   }
16467330f729Sjoerg   llvm_unreachable("Unknown implicit capture style");
16477330f729Sjoerg }
16487330f729Sjoerg 
CaptureHasSideEffects(const Capture & From)16497330f729Sjoerg bool Sema::CaptureHasSideEffects(const Capture &From) {
16507330f729Sjoerg   if (From.isInitCapture()) {
16517330f729Sjoerg     Expr *Init = From.getVariable()->getInit();
16527330f729Sjoerg     if (Init && Init->HasSideEffects(Context))
16537330f729Sjoerg       return true;
16547330f729Sjoerg   }
16557330f729Sjoerg 
16567330f729Sjoerg   if (!From.isCopyCapture())
16577330f729Sjoerg     return false;
16587330f729Sjoerg 
16597330f729Sjoerg   const QualType T = From.isThisCapture()
16607330f729Sjoerg                          ? getCurrentThisType()->getPointeeType()
16617330f729Sjoerg                          : From.getCaptureType();
16627330f729Sjoerg 
16637330f729Sjoerg   if (T.isVolatileQualified())
16647330f729Sjoerg     return true;
16657330f729Sjoerg 
16667330f729Sjoerg   const Type *BaseT = T->getBaseElementTypeUnsafe();
16677330f729Sjoerg   if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
16687330f729Sjoerg     return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
16697330f729Sjoerg            !RD->hasTrivialDestructor();
16707330f729Sjoerg 
16717330f729Sjoerg   return false;
16727330f729Sjoerg }
16737330f729Sjoerg 
DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,const Capture & From)16747330f729Sjoerg bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
16757330f729Sjoerg                                        const Capture &From) {
16767330f729Sjoerg   if (CaptureHasSideEffects(From))
16777330f729Sjoerg     return false;
16787330f729Sjoerg 
16797330f729Sjoerg   if (From.isVLATypeCapture())
16807330f729Sjoerg     return false;
16817330f729Sjoerg 
16827330f729Sjoerg   auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
16837330f729Sjoerg   if (From.isThisCapture())
16847330f729Sjoerg     diag << "'this'";
16857330f729Sjoerg   else
16867330f729Sjoerg     diag << From.getVariable();
16877330f729Sjoerg   diag << From.isNonODRUsed();
16887330f729Sjoerg   diag << FixItHint::CreateRemoval(CaptureRange);
16897330f729Sjoerg   return true;
16907330f729Sjoerg }
16917330f729Sjoerg 
16927330f729Sjoerg /// Create a field within the lambda class or captured statement record for the
16937330f729Sjoerg /// given capture.
BuildCaptureField(RecordDecl * RD,const sema::Capture & Capture)16947330f729Sjoerg FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
16957330f729Sjoerg                                    const sema::Capture &Capture) {
16967330f729Sjoerg   SourceLocation Loc = Capture.getLocation();
16977330f729Sjoerg   QualType FieldType = Capture.getCaptureType();
16987330f729Sjoerg 
16997330f729Sjoerg   TypeSourceInfo *TSI = nullptr;
17007330f729Sjoerg   if (Capture.isVariableCapture()) {
17017330f729Sjoerg     auto *Var = Capture.getVariable();
17027330f729Sjoerg     if (Var->isInitCapture())
17037330f729Sjoerg       TSI = Capture.getVariable()->getTypeSourceInfo();
17047330f729Sjoerg   }
17057330f729Sjoerg 
17067330f729Sjoerg   // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
17077330f729Sjoerg   // appropriate, at least for an implicit capture.
17087330f729Sjoerg   if (!TSI)
17097330f729Sjoerg     TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
17107330f729Sjoerg 
17117330f729Sjoerg   // Build the non-static data member.
17127330f729Sjoerg   FieldDecl *Field =
1713*e038c9c4Sjoerg       FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1714*e038c9c4Sjoerg                         /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1715*e038c9c4Sjoerg                         /*Mutable=*/false, ICIS_NoInit);
17167330f729Sjoerg   // If the variable being captured has an invalid type, mark the class as
17177330f729Sjoerg   // invalid as well.
17187330f729Sjoerg   if (!FieldType->isDependentType()) {
1719*e038c9c4Sjoerg     if (RequireCompleteSizedType(Loc, FieldType,
1720*e038c9c4Sjoerg                                  diag::err_field_incomplete_or_sizeless)) {
17217330f729Sjoerg       RD->setInvalidDecl();
17227330f729Sjoerg       Field->setInvalidDecl();
17237330f729Sjoerg     } else {
17247330f729Sjoerg       NamedDecl *Def;
17257330f729Sjoerg       FieldType->isIncompleteType(&Def);
17267330f729Sjoerg       if (Def && Def->isInvalidDecl()) {
17277330f729Sjoerg         RD->setInvalidDecl();
17287330f729Sjoerg         Field->setInvalidDecl();
17297330f729Sjoerg       }
17307330f729Sjoerg     }
17317330f729Sjoerg   }
17327330f729Sjoerg   Field->setImplicit(true);
17337330f729Sjoerg   Field->setAccess(AS_private);
17347330f729Sjoerg   RD->addDecl(Field);
17357330f729Sjoerg 
17367330f729Sjoerg   if (Capture.isVLATypeCapture())
17377330f729Sjoerg     Field->setCapturedVLAType(Capture.getCapturedVLAType());
17387330f729Sjoerg 
17397330f729Sjoerg   return Field;
17407330f729Sjoerg }
17417330f729Sjoerg 
BuildLambdaExpr(SourceLocation StartLoc,SourceLocation EndLoc,LambdaScopeInfo * LSI)17427330f729Sjoerg ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
17437330f729Sjoerg                                  LambdaScopeInfo *LSI) {
17447330f729Sjoerg   // Collect information from the lambda scope.
17457330f729Sjoerg   SmallVector<LambdaCapture, 4> Captures;
17467330f729Sjoerg   SmallVector<Expr *, 4> CaptureInits;
17477330f729Sjoerg   SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
17487330f729Sjoerg   LambdaCaptureDefault CaptureDefault =
17497330f729Sjoerg       mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
17507330f729Sjoerg   CXXRecordDecl *Class;
17517330f729Sjoerg   CXXMethodDecl *CallOperator;
17527330f729Sjoerg   SourceRange IntroducerRange;
17537330f729Sjoerg   bool ExplicitParams;
17547330f729Sjoerg   bool ExplicitResultType;
17557330f729Sjoerg   CleanupInfo LambdaCleanup;
17567330f729Sjoerg   bool ContainsUnexpandedParameterPack;
17577330f729Sjoerg   bool IsGenericLambda;
17587330f729Sjoerg   {
17597330f729Sjoerg     CallOperator = LSI->CallOperator;
17607330f729Sjoerg     Class = LSI->Lambda;
17617330f729Sjoerg     IntroducerRange = LSI->IntroducerRange;
17627330f729Sjoerg     ExplicitParams = LSI->ExplicitParams;
17637330f729Sjoerg     ExplicitResultType = !LSI->HasImplicitReturnType;
17647330f729Sjoerg     LambdaCleanup = LSI->Cleanup;
17657330f729Sjoerg     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
17667330f729Sjoerg     IsGenericLambda = Class->isGenericLambda();
17677330f729Sjoerg 
17687330f729Sjoerg     CallOperator->setLexicalDeclContext(Class);
17697330f729Sjoerg     Decl *TemplateOrNonTemplateCallOperatorDecl =
17707330f729Sjoerg         CallOperator->getDescribedFunctionTemplate()
17717330f729Sjoerg         ? CallOperator->getDescribedFunctionTemplate()
17727330f729Sjoerg         : cast<Decl>(CallOperator);
17737330f729Sjoerg 
17747330f729Sjoerg     // FIXME: Is this really the best choice? Keeping the lexical decl context
17757330f729Sjoerg     // set as CurContext seems more faithful to the source.
17767330f729Sjoerg     TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
17777330f729Sjoerg 
17787330f729Sjoerg     PopExpressionEvaluationContext();
17797330f729Sjoerg 
17807330f729Sjoerg     // True if the current capture has a used capture or default before it.
17817330f729Sjoerg     bool CurHasPreviousCapture = CaptureDefault != LCD_None;
17827330f729Sjoerg     SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
17837330f729Sjoerg         CaptureDefaultLoc : IntroducerRange.getBegin();
17847330f729Sjoerg 
17857330f729Sjoerg     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
17867330f729Sjoerg       const Capture &From = LSI->Captures[I];
17877330f729Sjoerg 
17887330f729Sjoerg       if (From.isInvalid())
17897330f729Sjoerg         return ExprError();
17907330f729Sjoerg 
17917330f729Sjoerg       assert(!From.isBlockCapture() && "Cannot capture __block variables");
17927330f729Sjoerg       bool IsImplicit = I >= LSI->NumExplicitCaptures;
17937330f729Sjoerg       SourceLocation ImplicitCaptureLoc =
17947330f729Sjoerg           IsImplicit ? CaptureDefaultLoc : SourceLocation();
17957330f729Sjoerg 
17967330f729Sjoerg       // Use source ranges of explicit captures for fixits where available.
17977330f729Sjoerg       SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
17987330f729Sjoerg 
17997330f729Sjoerg       // Warn about unused explicit captures.
18007330f729Sjoerg       bool IsCaptureUsed = true;
18017330f729Sjoerg       if (!CurContext->isDependentContext() && !IsImplicit &&
18027330f729Sjoerg           !From.isODRUsed()) {
18037330f729Sjoerg         // Initialized captures that are non-ODR used may not be eliminated.
18047330f729Sjoerg         // FIXME: Where did the IsGenericLambda here come from?
18057330f729Sjoerg         bool NonODRUsedInitCapture =
18067330f729Sjoerg             IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
18077330f729Sjoerg         if (!NonODRUsedInitCapture) {
18087330f729Sjoerg           bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
18097330f729Sjoerg           SourceRange FixItRange;
18107330f729Sjoerg           if (CaptureRange.isValid()) {
18117330f729Sjoerg             if (!CurHasPreviousCapture && !IsLast) {
18127330f729Sjoerg               // If there are no captures preceding this capture, remove the
18137330f729Sjoerg               // following comma.
18147330f729Sjoerg               FixItRange = SourceRange(CaptureRange.getBegin(),
18157330f729Sjoerg                                        getLocForEndOfToken(CaptureRange.getEnd()));
18167330f729Sjoerg             } else {
18177330f729Sjoerg               // Otherwise, remove the comma since the last used capture.
18187330f729Sjoerg               FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
18197330f729Sjoerg                                        CaptureRange.getEnd());
18207330f729Sjoerg             }
18217330f729Sjoerg           }
18227330f729Sjoerg 
18237330f729Sjoerg           IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
18247330f729Sjoerg         }
18257330f729Sjoerg       }
18267330f729Sjoerg 
18277330f729Sjoerg       if (CaptureRange.isValid()) {
18287330f729Sjoerg         CurHasPreviousCapture |= IsCaptureUsed;
18297330f729Sjoerg         PrevCaptureLoc = CaptureRange.getEnd();
18307330f729Sjoerg       }
18317330f729Sjoerg 
18327330f729Sjoerg       // Map the capture to our AST representation.
18337330f729Sjoerg       LambdaCapture Capture = [&] {
18347330f729Sjoerg         if (From.isThisCapture()) {
18357330f729Sjoerg           // Capturing 'this' implicitly with a default of '[=]' is deprecated,
18367330f729Sjoerg           // because it results in a reference capture. Don't warn prior to
18377330f729Sjoerg           // C++2a; there's nothing that can be done about it before then.
1838*e038c9c4Sjoerg           if (getLangOpts().CPlusPlus20 && IsImplicit &&
18397330f729Sjoerg               CaptureDefault == LCD_ByCopy) {
18407330f729Sjoerg             Diag(From.getLocation(), diag::warn_deprecated_this_capture);
18417330f729Sjoerg             Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
18427330f729Sjoerg                 << FixItHint::CreateInsertion(
18437330f729Sjoerg                        getLocForEndOfToken(CaptureDefaultLoc), ", this");
18447330f729Sjoerg           }
18457330f729Sjoerg           return LambdaCapture(From.getLocation(), IsImplicit,
18467330f729Sjoerg                                From.isCopyCapture() ? LCK_StarThis : LCK_This);
18477330f729Sjoerg         } else if (From.isVLATypeCapture()) {
18487330f729Sjoerg           return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
18497330f729Sjoerg         } else {
18507330f729Sjoerg           assert(From.isVariableCapture() && "unknown kind of capture");
18517330f729Sjoerg           VarDecl *Var = From.getVariable();
18527330f729Sjoerg           LambdaCaptureKind Kind =
18537330f729Sjoerg               From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
18547330f729Sjoerg           return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
18557330f729Sjoerg                                From.getEllipsisLoc());
18567330f729Sjoerg         }
18577330f729Sjoerg       }();
18587330f729Sjoerg 
18597330f729Sjoerg       // Form the initializer for the capture field.
18607330f729Sjoerg       ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
18617330f729Sjoerg 
18627330f729Sjoerg       // FIXME: Skip this capture if the capture is not used, the initializer
18637330f729Sjoerg       // has no side-effects, the type of the capture is trivial, and the
18647330f729Sjoerg       // lambda is not externally visible.
18657330f729Sjoerg 
18667330f729Sjoerg       // Add a FieldDecl for the capture and form its initializer.
18677330f729Sjoerg       BuildCaptureField(Class, From);
18687330f729Sjoerg       Captures.push_back(Capture);
18697330f729Sjoerg       CaptureInits.push_back(Init.get());
1870*e038c9c4Sjoerg 
1871*e038c9c4Sjoerg       if (LangOpts.CUDA)
1872*e038c9c4Sjoerg         CUDACheckLambdaCapture(CallOperator, From);
18737330f729Sjoerg     }
18747330f729Sjoerg 
1875*e038c9c4Sjoerg     Class->setCaptures(Context, Captures);
1876*e038c9c4Sjoerg 
18777330f729Sjoerg     // C++11 [expr.prim.lambda]p6:
18787330f729Sjoerg     //   The closure type for a lambda-expression with no lambda-capture
18797330f729Sjoerg     //   has a public non-virtual non-explicit const conversion function
18807330f729Sjoerg     //   to pointer to function having the same parameter and return
18817330f729Sjoerg     //   types as the closure type's function call operator.
18827330f729Sjoerg     if (Captures.empty() && CaptureDefault == LCD_None)
1883*e038c9c4Sjoerg       addFunctionPointerConversions(*this, IntroducerRange, Class,
18847330f729Sjoerg                                     CallOperator);
18857330f729Sjoerg 
18867330f729Sjoerg     // Objective-C++:
18877330f729Sjoerg     //   The closure type for a lambda-expression has a public non-virtual
18887330f729Sjoerg     //   non-explicit const conversion function to a block pointer having the
18897330f729Sjoerg     //   same parameter and return types as the closure type's function call
18907330f729Sjoerg     //   operator.
18917330f729Sjoerg     // FIXME: Fix generic lambda to block conversions.
18927330f729Sjoerg     if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
18937330f729Sjoerg       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
18947330f729Sjoerg 
18957330f729Sjoerg     // Finalize the lambda class.
18967330f729Sjoerg     SmallVector<Decl*, 4> Fields(Class->fields());
18977330f729Sjoerg     ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
18987330f729Sjoerg                 SourceLocation(), ParsedAttributesView());
1899*e038c9c4Sjoerg     CheckCompletedCXXClass(nullptr, Class);
19007330f729Sjoerg   }
19017330f729Sjoerg 
19027330f729Sjoerg   Cleanup.mergeFrom(LambdaCleanup);
19037330f729Sjoerg 
19047330f729Sjoerg   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
19057330f729Sjoerg                                           CaptureDefault, CaptureDefaultLoc,
19067330f729Sjoerg                                           ExplicitParams, ExplicitResultType,
19077330f729Sjoerg                                           CaptureInits, EndLoc,
19087330f729Sjoerg                                           ContainsUnexpandedParameterPack);
19097330f729Sjoerg   // If the lambda expression's call operator is not explicitly marked constexpr
19107330f729Sjoerg   // and we are not in a dependent context, analyze the call operator to infer
19117330f729Sjoerg   // its constexpr-ness, suppressing diagnostics while doing so.
19127330f729Sjoerg   if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
19137330f729Sjoerg       !CallOperator->isConstexpr() &&
19147330f729Sjoerg       !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
19157330f729Sjoerg       !Class->getDeclContext()->isDependentContext()) {
19167330f729Sjoerg     CallOperator->setConstexprKind(
19177330f729Sjoerg         CheckConstexprFunctionDefinition(CallOperator,
19187330f729Sjoerg                                          CheckConstexprKind::CheckValid)
1919*e038c9c4Sjoerg             ? ConstexprSpecKind::Constexpr
1920*e038c9c4Sjoerg             : ConstexprSpecKind::Unspecified);
19217330f729Sjoerg   }
19227330f729Sjoerg 
19237330f729Sjoerg   // Emit delayed shadowing warnings now that the full capture list is known.
19247330f729Sjoerg   DiagnoseShadowingLambdaDecls(LSI);
19257330f729Sjoerg 
19267330f729Sjoerg   if (!CurContext->isDependentContext()) {
19277330f729Sjoerg     switch (ExprEvalContexts.back().Context) {
19287330f729Sjoerg     // C++11 [expr.prim.lambda]p2:
19297330f729Sjoerg     //   A lambda-expression shall not appear in an unevaluated operand
19307330f729Sjoerg     //   (Clause 5).
19317330f729Sjoerg     case ExpressionEvaluationContext::Unevaluated:
19327330f729Sjoerg     case ExpressionEvaluationContext::UnevaluatedList:
19337330f729Sjoerg     case ExpressionEvaluationContext::UnevaluatedAbstract:
19347330f729Sjoerg     // C++1y [expr.const]p2:
19357330f729Sjoerg     //   A conditional-expression e is a core constant expression unless the
19367330f729Sjoerg     //   evaluation of e, following the rules of the abstract machine, would
19377330f729Sjoerg     //   evaluate [...] a lambda-expression.
19387330f729Sjoerg     //
19397330f729Sjoerg     // This is technically incorrect, there are some constant evaluated contexts
19407330f729Sjoerg     // where this should be allowed.  We should probably fix this when DR1607 is
19417330f729Sjoerg     // ratified, it lays out the exact set of conditions where we shouldn't
19427330f729Sjoerg     // allow a lambda-expression.
19437330f729Sjoerg     case ExpressionEvaluationContext::ConstantEvaluated:
19447330f729Sjoerg       // We don't actually diagnose this case immediately, because we
19457330f729Sjoerg       // could be within a context where we might find out later that
19467330f729Sjoerg       // the expression is potentially evaluated (e.g., for typeid).
19477330f729Sjoerg       ExprEvalContexts.back().Lambdas.push_back(Lambda);
19487330f729Sjoerg       break;
19497330f729Sjoerg 
19507330f729Sjoerg     case ExpressionEvaluationContext::DiscardedStatement:
19517330f729Sjoerg     case ExpressionEvaluationContext::PotentiallyEvaluated:
19527330f729Sjoerg     case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19537330f729Sjoerg       break;
19547330f729Sjoerg     }
19557330f729Sjoerg   }
19567330f729Sjoerg 
19577330f729Sjoerg   return MaybeBindToTemporary(Lambda);
19587330f729Sjoerg }
19597330f729Sjoerg 
BuildBlockForLambdaConversion(SourceLocation CurrentLocation,SourceLocation ConvLocation,CXXConversionDecl * Conv,Expr * Src)19607330f729Sjoerg ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
19617330f729Sjoerg                                                SourceLocation ConvLocation,
19627330f729Sjoerg                                                CXXConversionDecl *Conv,
19637330f729Sjoerg                                                Expr *Src) {
19647330f729Sjoerg   // Make sure that the lambda call operator is marked used.
19657330f729Sjoerg   CXXRecordDecl *Lambda = Conv->getParent();
19667330f729Sjoerg   CXXMethodDecl *CallOperator
19677330f729Sjoerg     = cast<CXXMethodDecl>(
19687330f729Sjoerg         Lambda->lookup(
19697330f729Sjoerg           Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
19707330f729Sjoerg   CallOperator->setReferenced();
19717330f729Sjoerg   CallOperator->markUsed(Context);
19727330f729Sjoerg 
19737330f729Sjoerg   ExprResult Init = PerformCopyInitialization(
19747330f729Sjoerg       InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(),
19757330f729Sjoerg                                                  /*NRVO=*/false),
19767330f729Sjoerg       CurrentLocation, Src);
19777330f729Sjoerg   if (!Init.isInvalid())
19787330f729Sjoerg     Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
19797330f729Sjoerg 
19807330f729Sjoerg   if (Init.isInvalid())
19817330f729Sjoerg     return ExprError();
19827330f729Sjoerg 
19837330f729Sjoerg   // Create the new block to be returned.
19847330f729Sjoerg   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
19857330f729Sjoerg 
19867330f729Sjoerg   // Set the type information.
19877330f729Sjoerg   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
19887330f729Sjoerg   Block->setIsVariadic(CallOperator->isVariadic());
19897330f729Sjoerg   Block->setBlockMissingReturnType(false);
19907330f729Sjoerg 
19917330f729Sjoerg   // Add parameters.
19927330f729Sjoerg   SmallVector<ParmVarDecl *, 4> BlockParams;
19937330f729Sjoerg   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
19947330f729Sjoerg     ParmVarDecl *From = CallOperator->getParamDecl(I);
19957330f729Sjoerg     BlockParams.push_back(ParmVarDecl::Create(
19967330f729Sjoerg         Context, Block, From->getBeginLoc(), From->getLocation(),
19977330f729Sjoerg         From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
19987330f729Sjoerg         From->getStorageClass(),
19997330f729Sjoerg         /*DefArg=*/nullptr));
20007330f729Sjoerg   }
20017330f729Sjoerg   Block->setParams(BlockParams);
20027330f729Sjoerg 
20037330f729Sjoerg   Block->setIsConversionFromLambda(true);
20047330f729Sjoerg 
20057330f729Sjoerg   // Add capture. The capture uses a fake variable, which doesn't correspond
20067330f729Sjoerg   // to any actual memory location. However, the initializer copy-initializes
20077330f729Sjoerg   // the lambda object.
20087330f729Sjoerg   TypeSourceInfo *CapVarTSI =
20097330f729Sjoerg       Context.getTrivialTypeSourceInfo(Src->getType());
20107330f729Sjoerg   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
20117330f729Sjoerg                                     ConvLocation, nullptr,
20127330f729Sjoerg                                     Src->getType(), CapVarTSI,
20137330f729Sjoerg                                     SC_None);
20147330f729Sjoerg   BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
20157330f729Sjoerg                              /*nested=*/false, /*copy=*/Init.get());
20167330f729Sjoerg   Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
20177330f729Sjoerg 
20187330f729Sjoerg   // Add a fake function body to the block. IR generation is responsible
20197330f729Sjoerg   // for filling in the actual body, which cannot be expressed as an AST.
20207330f729Sjoerg   Block->setBody(new (Context) CompoundStmt(ConvLocation));
20217330f729Sjoerg 
20227330f729Sjoerg   // Create the block literal expression.
20237330f729Sjoerg   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
20247330f729Sjoerg   ExprCleanupObjects.push_back(Block);
20257330f729Sjoerg   Cleanup.setExprNeedsCleanups(true);
20267330f729Sjoerg 
20277330f729Sjoerg   return BuildBlock;
20287330f729Sjoerg }
2029