SemaLambda.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  1. //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for C++ lambda expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/DeclSpec.h"
  13. #include "TypeLocBuilder.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/ExprCXX.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/Scope.h"
  20. #include "clang/Sema/ScopeInfo.h"
  21. #include "clang/Sema/SemaInternal.h"
  22. #include "clang/Sema/SemaLambda.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. using namespace clang;
  25. using namespace sema;
  26. /// Examines the FunctionScopeInfo stack to determine the nearest
  27. /// enclosing lambda (to the current lambda) that is 'capture-ready' for
  28. /// the variable referenced in the current lambda (i.e. \p VarToCapture).
  29. /// If successful, returns the index into Sema's FunctionScopeInfo stack
  30. /// of the capture-ready lambda's LambdaScopeInfo.
  31. ///
  32. /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
  33. /// lambda - is on top) to determine the index of the nearest enclosing/outer
  34. /// lambda that is ready to capture the \p VarToCapture being referenced in
  35. /// the current lambda.
  36. /// As we climb down the stack, we want the index of the first such lambda -
  37. /// that is the lambda with the highest index that is 'capture-ready'.
  38. ///
  39. /// A lambda 'L' is capture-ready for 'V' (var or this) if:
  40. /// - its enclosing context is non-dependent
  41. /// - and if the chain of lambdas between L and the lambda in which
  42. /// V is potentially used (i.e. the lambda at the top of the scope info
  43. /// stack), can all capture or have already captured V.
  44. /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
  45. ///
  46. /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
  47. /// for whether it is 'capture-capable' (see
  48. /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
  49. /// capture.
  50. ///
  51. /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
  52. /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
  53. /// is at the top of the stack and has the highest index.
  54. /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
  55. ///
  56. /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
  57. /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
  58. /// which is capture-ready. If the return value evaluates to 'false' then
  59. /// no lambda is capture-ready for \p VarToCapture.
  60. static inline Optional<unsigned>
  61. getStackIndexOfNearestEnclosingCaptureReadyLambda(
  62. ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
  63. VarDecl *VarToCapture) {
  64. // Label failure to capture.
  65. const Optional<unsigned> NoLambdaIsCaptureReady;
  66. // Ignore all inner captured regions.
  67. unsigned CurScopeIndex = FunctionScopes.size() - 1;
  68. while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
  69. FunctionScopes[CurScopeIndex]))
  70. --CurScopeIndex;
  71. assert(
  72. isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
  73. "The function on the top of sema's function-info stack must be a lambda");
  74. // If VarToCapture is null, we are attempting to capture 'this'.
  75. const bool IsCapturingThis = !VarToCapture;
  76. const bool IsCapturingVariable = !IsCapturingThis;
  77. // Start with the current lambda at the top of the stack (highest index).
  78. DeclContext *EnclosingDC =
  79. cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
  80. do {
  81. const clang::sema::LambdaScopeInfo *LSI =
  82. cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
  83. // IF we have climbed down to an intervening enclosing lambda that contains
  84. // the variable declaration - it obviously can/must not capture the
  85. // variable.
  86. // Since its enclosing DC is dependent, all the lambdas between it and the
  87. // innermost nested lambda are dependent (otherwise we wouldn't have
  88. // arrived here) - so we don't yet have a lambda that can capture the
  89. // variable.
  90. if (IsCapturingVariable &&
  91. VarToCapture->getDeclContext()->Equals(EnclosingDC))
  92. return NoLambdaIsCaptureReady;
  93. // For an enclosing lambda to be capture ready for an entity, all
  94. // intervening lambda's have to be able to capture that entity. If even
  95. // one of the intervening lambda's is not capable of capturing the entity
  96. // then no enclosing lambda can ever capture that entity.
  97. // For e.g.
  98. // const int x = 10;
  99. // [=](auto a) { #1
  100. // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
  101. // [=](auto c) { #3
  102. // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
  103. // }; }; };
  104. // If they do not have a default implicit capture, check to see
  105. // if the entity has already been explicitly captured.
  106. // If even a single dependent enclosing lambda lacks the capability
  107. // to ever capture this variable, there is no further enclosing
  108. // non-dependent lambda that can capture this variable.
  109. if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
  110. if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
  111. return NoLambdaIsCaptureReady;
  112. if (IsCapturingThis && !LSI->isCXXThisCaptured())
  113. return NoLambdaIsCaptureReady;
  114. }
  115. EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
  116. assert(CurScopeIndex);
  117. --CurScopeIndex;
  118. } while (!EnclosingDC->isTranslationUnit() &&
  119. EnclosingDC->isDependentContext() &&
  120. isLambdaCallOperator(EnclosingDC));
  121. assert(CurScopeIndex < (FunctionScopes.size() - 1));
  122. // If the enclosingDC is not dependent, then the immediately nested lambda
  123. // (one index above) is capture-ready.
  124. if (!EnclosingDC->isDependentContext())
  125. return CurScopeIndex + 1;
  126. return NoLambdaIsCaptureReady;
  127. }
  128. /// Examines the FunctionScopeInfo stack to determine the nearest
  129. /// enclosing lambda (to the current lambda) that is 'capture-capable' for
  130. /// the variable referenced in the current lambda (i.e. \p VarToCapture).
  131. /// If successful, returns the index into Sema's FunctionScopeInfo stack
  132. /// of the capture-capable lambda's LambdaScopeInfo.
  133. ///
  134. /// Given the current stack of lambdas being processed by Sema and
  135. /// the variable of interest, to identify the nearest enclosing lambda (to the
  136. /// current lambda at the top of the stack) that can truly capture
  137. /// a variable, it has to have the following two properties:
  138. /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
  139. /// - climb down the stack (i.e. starting from the innermost and examining
  140. /// each outer lambda step by step) checking if each enclosing
  141. /// lambda can either implicitly or explicitly capture the variable.
  142. /// Record the first such lambda that is enclosed in a non-dependent
  143. /// context. If no such lambda currently exists return failure.
  144. /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
  145. /// capture the variable by checking all its enclosing lambdas:
  146. /// - check if all outer lambdas enclosing the 'capture-ready' lambda
  147. /// identified above in 'a' can also capture the variable (this is done
  148. /// via tryCaptureVariable for variables and CheckCXXThisCapture for
  149. /// 'this' by passing in the index of the Lambda identified in step 'a')
  150. ///
  151. /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
  152. /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
  153. /// is at the top of the stack.
  154. ///
  155. /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
  156. ///
  157. ///
  158. /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
  159. /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
  160. /// which is capture-capable. If the return value evaluates to 'false' then
  161. /// no lambda is capture-capable for \p VarToCapture.
  162. Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
  163. ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
  164. VarDecl *VarToCapture, Sema &S) {
  165. const Optional<unsigned> NoLambdaIsCaptureCapable;
  166. const Optional<unsigned> OptionalStackIndex =
  167. getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
  168. VarToCapture);
  169. if (!OptionalStackIndex)
  170. return NoLambdaIsCaptureCapable;
  171. const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
  172. assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
  173. S.getCurGenericLambda()) &&
  174. "The capture ready lambda for a potential capture can only be the "
  175. "current lambda if it is a generic lambda");
  176. const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
  177. cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
  178. // If VarToCapture is null, we are attempting to capture 'this'
  179. const bool IsCapturingThis = !VarToCapture;
  180. const bool IsCapturingVariable = !IsCapturingThis;
  181. if (IsCapturingVariable) {
  182. // Check if the capture-ready lambda can truly capture the variable, by
  183. // checking whether all enclosing lambdas of the capture-ready lambda allow
  184. // the capture - i.e. make sure it is capture-capable.
  185. QualType CaptureType, DeclRefType;
  186. const bool CanCaptureVariable =
  187. !S.tryCaptureVariable(VarToCapture,
  188. /*ExprVarIsUsedInLoc*/ SourceLocation(),
  189. clang::Sema::TryCapture_Implicit,
  190. /*EllipsisLoc*/ SourceLocation(),
  191. /*BuildAndDiagnose*/ false, CaptureType,
  192. DeclRefType, &IndexOfCaptureReadyLambda);
  193. if (!CanCaptureVariable)
  194. return NoLambdaIsCaptureCapable;
  195. } else {
  196. // Check if the capture-ready lambda can truly capture 'this' by checking
  197. // whether all enclosing lambdas of the capture-ready lambda can capture
  198. // 'this'.
  199. const bool CanCaptureThis =
  200. !S.CheckCXXThisCapture(
  201. CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
  202. /*Explicit*/ false, /*BuildAndDiagnose*/ false,
  203. &IndexOfCaptureReadyLambda);
  204. if (!CanCaptureThis)
  205. return NoLambdaIsCaptureCapable;
  206. }
  207. return IndexOfCaptureReadyLambda;
  208. }
  209. static inline TemplateParameterList *
  210. getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
  211. if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
  212. LSI->GLTemplateParameterList = TemplateParameterList::Create(
  213. SemaRef.Context,
  214. /*Template kw loc*/ SourceLocation(),
  215. /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
  216. LSI->TemplateParams,
  217. /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
  218. LSI->RequiresClause.get());
  219. }
  220. return LSI->GLTemplateParameterList;
  221. }
  222. CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
  223. TypeSourceInfo *Info,
  224. bool KnownDependent,
  225. LambdaCaptureDefault CaptureDefault) {
  226. DeclContext *DC = CurContext;
  227. while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
  228. DC = DC->getParent();
  229. bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
  230. *this);
  231. // Start constructing the lambda class.
  232. CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
  233. IntroducerRange.getBegin(),
  234. KnownDependent,
  235. IsGenericLambda,
  236. CaptureDefault);
  237. DC->addDecl(Class);
  238. return Class;
  239. }
  240. /// Determine whether the given context is or is enclosed in an inline
  241. /// function.
  242. static bool isInInlineFunction(const DeclContext *DC) {
  243. while (!DC->isFileContext()) {
  244. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  245. if (FD->isInlined())
  246. return true;
  247. DC = DC->getLexicalParent();
  248. }
  249. return false;
  250. }
  251. std::tuple<MangleNumberingContext *, Decl *>
  252. Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
  253. // Compute the context for allocating mangling numbers in the current
  254. // expression, if the ABI requires them.
  255. Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  256. enum ContextKind {
  257. Normal,
  258. DefaultArgument,
  259. DataMember,
  260. StaticDataMember,
  261. InlineVariable,
  262. VariableTemplate
  263. } Kind = Normal;
  264. // Default arguments of member function parameters that appear in a class
  265. // definition, as well as the initializers of data members, receive special
  266. // treatment. Identify them.
  267. if (ManglingContextDecl) {
  268. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
  269. if (const DeclContext *LexicalDC
  270. = Param->getDeclContext()->getLexicalParent())
  271. if (LexicalDC->isRecord())
  272. Kind = DefaultArgument;
  273. } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
  274. if (Var->getDeclContext()->isRecord())
  275. Kind = StaticDataMember;
  276. else if (Var->getMostRecentDecl()->isInline())
  277. Kind = InlineVariable;
  278. else if (Var->getDescribedVarTemplate())
  279. Kind = VariableTemplate;
  280. else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
  281. if (!VTS->isExplicitSpecialization())
  282. Kind = VariableTemplate;
  283. }
  284. } else if (isa<FieldDecl>(ManglingContextDecl)) {
  285. Kind = DataMember;
  286. }
  287. }
  288. // Itanium ABI [5.1.7]:
  289. // In the following contexts [...] the one-definition rule requires closure
  290. // types in different translation units to "correspond":
  291. bool IsInNonspecializedTemplate =
  292. inTemplateInstantiation() || CurContext->isDependentContext();
  293. switch (Kind) {
  294. case Normal: {
  295. // -- the bodies of non-exported nonspecialized template functions
  296. // -- the bodies of inline functions
  297. if ((IsInNonspecializedTemplate &&
  298. !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
  299. isInInlineFunction(CurContext)) {
  300. while (auto *CD = dyn_cast<CapturedDecl>(DC))
  301. DC = CD->getParent();
  302. return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
  303. }
  304. return std::make_tuple(nullptr, nullptr);
  305. }
  306. case StaticDataMember:
  307. // -- the initializers of nonspecialized static members of template classes
  308. if (!IsInNonspecializedTemplate)
  309. return std::make_tuple(nullptr, ManglingContextDecl);
  310. // Fall through to get the current context.
  311. LLVM_FALLTHROUGH;
  312. case DataMember:
  313. // -- the in-class initializers of class members
  314. case DefaultArgument:
  315. // -- default arguments appearing in class definitions
  316. case InlineVariable:
  317. // -- the initializers of inline variables
  318. case VariableTemplate:
  319. // -- the initializers of templated variables
  320. return std::make_tuple(
  321. &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
  322. ManglingContextDecl),
  323. ManglingContextDecl);
  324. }
  325. llvm_unreachable("unexpected context");
  326. }
  327. CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
  328. SourceRange IntroducerRange,
  329. TypeSourceInfo *MethodTypeInfo,
  330. SourceLocation EndLoc,
  331. ArrayRef<ParmVarDecl *> Params,
  332. ConstexprSpecKind ConstexprKind,
  333. Expr *TrailingRequiresClause) {
  334. QualType MethodType = MethodTypeInfo->getType();
  335. TemplateParameterList *TemplateParams =
  336. getGenericLambdaTemplateParameterList(getCurLambda(), *this);
  337. // If a lambda appears in a dependent context or is a generic lambda (has
  338. // template parameters) and has an 'auto' return type, deduce it to a
  339. // dependent type.
  340. if (Class->isDependentContext() || TemplateParams) {
  341. const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
  342. QualType Result = FPT->getReturnType();
  343. if (Result->isUndeducedType()) {
  344. Result = SubstAutoTypeDependent(Result);
  345. MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
  346. FPT->getExtProtoInfo());
  347. }
  348. }
  349. // C++11 [expr.prim.lambda]p5:
  350. // The closure type for a lambda-expression has a public inline function
  351. // call operator (13.5.4) whose parameters and return type are described by
  352. // the lambda-expression's parameter-declaration-clause and
  353. // trailing-return-type respectively.
  354. DeclarationName MethodName
  355. = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  356. DeclarationNameLoc MethodNameLoc =
  357. DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange);
  358. CXXMethodDecl *Method = CXXMethodDecl::Create(
  359. Context, Class, EndLoc,
  360. DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
  361. MethodNameLoc),
  362. MethodType, MethodTypeInfo, SC_None, getCurFPFeatures().isFPConstrained(),
  363. /*isInline=*/true, ConstexprKind, EndLoc, TrailingRequiresClause);
  364. Method->setAccess(AS_public);
  365. if (!TemplateParams)
  366. Class->addDecl(Method);
  367. // Temporarily set the lexical declaration context to the current
  368. // context, so that the Scope stack matches the lexical nesting.
  369. Method->setLexicalDeclContext(CurContext);
  370. // Create a function template if we have a template parameter list
  371. FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
  372. FunctionTemplateDecl::Create(Context, Class,
  373. Method->getLocation(), MethodName,
  374. TemplateParams,
  375. Method) : nullptr;
  376. if (TemplateMethod) {
  377. TemplateMethod->setAccess(AS_public);
  378. Method->setDescribedFunctionTemplate(TemplateMethod);
  379. Class->addDecl(TemplateMethod);
  380. TemplateMethod->setLexicalDeclContext(CurContext);
  381. }
  382. // Add parameters.
  383. if (!Params.empty()) {
  384. Method->setParams(Params);
  385. CheckParmsForFunctionDef(Params,
  386. /*CheckParameterNames=*/false);
  387. for (auto P : Method->parameters())
  388. P->setOwningFunction(Method);
  389. }
  390. return Method;
  391. }
  392. void Sema::handleLambdaNumbering(
  393. CXXRecordDecl *Class, CXXMethodDecl *Method,
  394. Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
  395. if (Mangling) {
  396. bool HasKnownInternalLinkage;
  397. unsigned ManglingNumber, DeviceManglingNumber;
  398. Decl *ManglingContextDecl;
  399. std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
  400. ManglingContextDecl) = Mangling.getValue();
  401. Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
  402. HasKnownInternalLinkage);
  403. Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
  404. return;
  405. }
  406. auto getMangleNumberingContext =
  407. [this](CXXRecordDecl *Class,
  408. Decl *ManglingContextDecl) -> MangleNumberingContext * {
  409. // Get mangle numbering context if there's any extra decl context.
  410. if (ManglingContextDecl)
  411. return &Context.getManglingNumberContext(
  412. ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
  413. // Otherwise, from that lambda's decl context.
  414. auto DC = Class->getDeclContext();
  415. while (auto *CD = dyn_cast<CapturedDecl>(DC))
  416. DC = CD->getParent();
  417. return &Context.getManglingNumberContext(DC);
  418. };
  419. MangleNumberingContext *MCtx;
  420. Decl *ManglingContextDecl;
  421. std::tie(MCtx, ManglingContextDecl) =
  422. getCurrentMangleNumberContext(Class->getDeclContext());
  423. bool HasKnownInternalLinkage = false;
  424. if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
  425. getLangOpts().SYCLIsHost)) {
  426. // Force lambda numbering in CUDA/HIP as we need to name lambdas following
  427. // ODR. Both device- and host-compilation need to have a consistent naming
  428. // on kernel functions. As lambdas are potential part of these `__global__`
  429. // function names, they needs numbering following ODR.
  430. // Also force for SYCL, since we need this for the
  431. // __builtin_sycl_unique_stable_name implementation, which depends on lambda
  432. // mangling.
  433. MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
  434. assert(MCtx && "Retrieving mangle numbering context failed!");
  435. HasKnownInternalLinkage = true;
  436. }
  437. if (MCtx) {
  438. unsigned ManglingNumber = MCtx->getManglingNumber(Method);
  439. Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
  440. HasKnownInternalLinkage);
  441. Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
  442. }
  443. }
  444. void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
  445. CXXMethodDecl *CallOperator,
  446. SourceRange IntroducerRange,
  447. LambdaCaptureDefault CaptureDefault,
  448. SourceLocation CaptureDefaultLoc,
  449. bool ExplicitParams,
  450. bool ExplicitResultType,
  451. bool Mutable) {
  452. LSI->CallOperator = CallOperator;
  453. CXXRecordDecl *LambdaClass = CallOperator->getParent();
  454. LSI->Lambda = LambdaClass;
  455. if (CaptureDefault == LCD_ByCopy)
  456. LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
  457. else if (CaptureDefault == LCD_ByRef)
  458. LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
  459. LSI->CaptureDefaultLoc = CaptureDefaultLoc;
  460. LSI->IntroducerRange = IntroducerRange;
  461. LSI->ExplicitParams = ExplicitParams;
  462. LSI->Mutable = Mutable;
  463. if (ExplicitResultType) {
  464. LSI->ReturnType = CallOperator->getReturnType();
  465. if (!LSI->ReturnType->isDependentType() &&
  466. !LSI->ReturnType->isVoidType()) {
  467. if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
  468. diag::err_lambda_incomplete_result)) {
  469. // Do nothing.
  470. }
  471. }
  472. } else {
  473. LSI->HasImplicitReturnType = true;
  474. }
  475. }
  476. void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
  477. LSI->finishedExplicitCaptures();
  478. }
  479. void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
  480. ArrayRef<NamedDecl *> TParams,
  481. SourceLocation RAngleLoc,
  482. ExprResult RequiresClause) {
  483. LambdaScopeInfo *LSI = getCurLambda();
  484. assert(LSI && "Expected a lambda scope");
  485. assert(LSI->NumExplicitTemplateParams == 0 &&
  486. "Already acted on explicit template parameters");
  487. assert(LSI->TemplateParams.empty() &&
  488. "Explicit template parameters should come "
  489. "before invented (auto) ones");
  490. assert(!TParams.empty() &&
  491. "No template parameters to act on");
  492. LSI->TemplateParams.append(TParams.begin(), TParams.end());
  493. LSI->NumExplicitTemplateParams = TParams.size();
  494. LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
  495. LSI->RequiresClause = RequiresClause;
  496. }
  497. void Sema::addLambdaParameters(
  498. ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
  499. CXXMethodDecl *CallOperator, Scope *CurScope) {
  500. // Introduce our parameters into the function scope
  501. for (unsigned p = 0, NumParams = CallOperator->getNumParams();
  502. p < NumParams; ++p) {
  503. ParmVarDecl *Param = CallOperator->getParamDecl(p);
  504. // If this has an identifier, add it to the scope stack.
  505. if (CurScope && Param->getIdentifier()) {
  506. bool Error = false;
  507. // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
  508. // retroactively apply it.
  509. for (const auto &Capture : Captures) {
  510. if (Capture.Id == Param->getIdentifier()) {
  511. Error = true;
  512. Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
  513. Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
  514. << Capture.Id << true;
  515. }
  516. }
  517. if (!Error)
  518. CheckShadow(CurScope, Param);
  519. PushOnScopeChains(Param, CurScope);
  520. }
  521. }
  522. }
  523. /// If this expression is an enumerator-like expression of some type
  524. /// T, return the type T; otherwise, return null.
  525. ///
  526. /// Pointer comparisons on the result here should always work because
  527. /// it's derived from either the parent of an EnumConstantDecl
  528. /// (i.e. the definition) or the declaration returned by
  529. /// EnumType::getDecl() (i.e. the definition).
  530. static EnumDecl *findEnumForBlockReturn(Expr *E) {
  531. // An expression is an enumerator-like expression of type T if,
  532. // ignoring parens and parens-like expressions:
  533. E = E->IgnoreParens();
  534. // - it is an enumerator whose enum type is T or
  535. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  536. if (EnumConstantDecl *D
  537. = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  538. return cast<EnumDecl>(D->getDeclContext());
  539. }
  540. return nullptr;
  541. }
  542. // - it is a comma expression whose RHS is an enumerator-like
  543. // expression of type T or
  544. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  545. if (BO->getOpcode() == BO_Comma)
  546. return findEnumForBlockReturn(BO->getRHS());
  547. return nullptr;
  548. }
  549. // - it is a statement-expression whose value expression is an
  550. // enumerator-like expression of type T or
  551. if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
  552. if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
  553. return findEnumForBlockReturn(last);
  554. return nullptr;
  555. }
  556. // - it is a ternary conditional operator (not the GNU ?:
  557. // extension) whose second and third operands are
  558. // enumerator-like expressions of type T or
  559. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  560. if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
  561. if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
  562. return ED;
  563. return nullptr;
  564. }
  565. // (implicitly:)
  566. // - it is an implicit integral conversion applied to an
  567. // enumerator-like expression of type T or
  568. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  569. // We can sometimes see integral conversions in valid
  570. // enumerator-like expressions.
  571. if (ICE->getCastKind() == CK_IntegralCast)
  572. return findEnumForBlockReturn(ICE->getSubExpr());
  573. // Otherwise, just rely on the type.
  574. }
  575. // - it is an expression of that formal enum type.
  576. if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
  577. return ET->getDecl();
  578. }
  579. // Otherwise, nope.
  580. return nullptr;
  581. }
  582. /// Attempt to find a type T for which the returned expression of the
  583. /// given statement is an enumerator-like expression of that type.
  584. static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
  585. if (Expr *retValue = ret->getRetValue())
  586. return findEnumForBlockReturn(retValue);
  587. return nullptr;
  588. }
  589. /// Attempt to find a common type T for which all of the returned
  590. /// expressions in a block are enumerator-like expressions of that
  591. /// type.
  592. static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
  593. ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
  594. // Try to find one for the first return.
  595. EnumDecl *ED = findEnumForBlockReturn(*i);
  596. if (!ED) return nullptr;
  597. // Check that the rest of the returns have the same enum.
  598. for (++i; i != e; ++i) {
  599. if (findEnumForBlockReturn(*i) != ED)
  600. return nullptr;
  601. }
  602. // Never infer an anonymous enum type.
  603. if (!ED->hasNameForLinkage()) return nullptr;
  604. return ED;
  605. }
  606. /// Adjust the given return statements so that they formally return
  607. /// the given type. It should require, at most, an IntegralCast.
  608. static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
  609. QualType returnType) {
  610. for (ArrayRef<ReturnStmt*>::iterator
  611. i = returns.begin(), e = returns.end(); i != e; ++i) {
  612. ReturnStmt *ret = *i;
  613. Expr *retValue = ret->getRetValue();
  614. if (S.Context.hasSameType(retValue->getType(), returnType))
  615. continue;
  616. // Right now we only support integral fixup casts.
  617. assert(returnType->isIntegralOrUnscopedEnumerationType());
  618. assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
  619. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
  620. Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
  621. E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
  622. /*base path*/ nullptr, VK_PRValue,
  623. FPOptionsOverride());
  624. if (cleanups) {
  625. cleanups->setSubExpr(E);
  626. } else {
  627. ret->setRetValue(E);
  628. }
  629. }
  630. }
  631. void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
  632. assert(CSI.HasImplicitReturnType);
  633. // If it was ever a placeholder, it had to been deduced to DependentTy.
  634. assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
  635. assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
  636. "lambda expressions use auto deduction in C++14 onwards");
  637. // C++ core issue 975:
  638. // If a lambda-expression does not include a trailing-return-type,
  639. // it is as if the trailing-return-type denotes the following type:
  640. // - if there are no return statements in the compound-statement,
  641. // or all return statements return either an expression of type
  642. // void or no expression or braced-init-list, the type void;
  643. // - otherwise, if all return statements return an expression
  644. // and the types of the returned expressions after
  645. // lvalue-to-rvalue conversion (4.1 [conv.lval]),
  646. // array-to-pointer conversion (4.2 [conv.array]), and
  647. // function-to-pointer conversion (4.3 [conv.func]) are the
  648. // same, that common type;
  649. // - otherwise, the program is ill-formed.
  650. //
  651. // C++ core issue 1048 additionally removes top-level cv-qualifiers
  652. // from the types of returned expressions to match the C++14 auto
  653. // deduction rules.
  654. //
  655. // In addition, in blocks in non-C++ modes, if all of the return
  656. // statements are enumerator-like expressions of some type T, where
  657. // T has a name for linkage, then we infer the return type of the
  658. // block to be that type.
  659. // First case: no return statements, implicit void return type.
  660. ASTContext &Ctx = getASTContext();
  661. if (CSI.Returns.empty()) {
  662. // It's possible there were simply no /valid/ return statements.
  663. // In this case, the first one we found may have at least given us a type.
  664. if (CSI.ReturnType.isNull())
  665. CSI.ReturnType = Ctx.VoidTy;
  666. return;
  667. }
  668. // Second case: at least one return statement has dependent type.
  669. // Delay type checking until instantiation.
  670. assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
  671. if (CSI.ReturnType->isDependentType())
  672. return;
  673. // Try to apply the enum-fuzz rule.
  674. if (!getLangOpts().CPlusPlus) {
  675. assert(isa<BlockScopeInfo>(CSI));
  676. const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
  677. if (ED) {
  678. CSI.ReturnType = Context.getTypeDeclType(ED);
  679. adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
  680. return;
  681. }
  682. }
  683. // Third case: only one return statement. Don't bother doing extra work!
  684. if (CSI.Returns.size() == 1)
  685. return;
  686. // General case: many return statements.
  687. // Check that they all have compatible return types.
  688. // We require the return types to strictly match here.
  689. // Note that we've already done the required promotions as part of
  690. // processing the return statement.
  691. for (const ReturnStmt *RS : CSI.Returns) {
  692. const Expr *RetE = RS->getRetValue();
  693. QualType ReturnType =
  694. (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
  695. if (Context.getCanonicalFunctionResultType(ReturnType) ==
  696. Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
  697. // Use the return type with the strictest possible nullability annotation.
  698. auto RetTyNullability = ReturnType->getNullability(Ctx);
  699. auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
  700. if (BlockNullability &&
  701. (!RetTyNullability ||
  702. hasWeakerNullability(*RetTyNullability, *BlockNullability)))
  703. CSI.ReturnType = ReturnType;
  704. continue;
  705. }
  706. // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
  707. // TODO: It's possible that the *first* return is the divergent one.
  708. Diag(RS->getBeginLoc(),
  709. diag::err_typecheck_missing_return_type_incompatible)
  710. << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
  711. // Continue iterating so that we keep emitting diagnostics.
  712. }
  713. }
  714. QualType Sema::buildLambdaInitCaptureInitialization(
  715. SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
  716. Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
  717. Expr *&Init) {
  718. // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
  719. // deduce against.
  720. QualType DeductType = Context.getAutoDeductType();
  721. TypeLocBuilder TLB;
  722. AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
  723. TL.setNameLoc(Loc);
  724. if (ByRef) {
  725. DeductType = BuildReferenceType(DeductType, true, Loc, Id);
  726. assert(!DeductType.isNull() && "can't build reference to auto");
  727. TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
  728. }
  729. if (EllipsisLoc.isValid()) {
  730. if (Init->containsUnexpandedParameterPack()) {
  731. Diag(EllipsisLoc, getLangOpts().CPlusPlus20
  732. ? diag::warn_cxx17_compat_init_capture_pack
  733. : diag::ext_init_capture_pack);
  734. DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
  735. /*ExpectPackInType=*/false);
  736. TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
  737. } else {
  738. // Just ignore the ellipsis for now and form a non-pack variable. We'll
  739. // diagnose this later when we try to capture it.
  740. }
  741. }
  742. TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
  743. // Deduce the type of the init capture.
  744. QualType DeducedType = deduceVarTypeFromInitializer(
  745. /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
  746. SourceRange(Loc, Loc), IsDirectInit, Init);
  747. if (DeducedType.isNull())
  748. return QualType();
  749. // Are we a non-list direct initialization?
  750. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  751. // Perform initialization analysis and ensure any implicit conversions
  752. // (such as lvalue-to-rvalue) are enforced.
  753. InitializedEntity Entity =
  754. InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
  755. InitializationKind Kind =
  756. IsDirectInit
  757. ? (CXXDirectInit ? InitializationKind::CreateDirect(
  758. Loc, Init->getBeginLoc(), Init->getEndLoc())
  759. : InitializationKind::CreateDirectList(Loc))
  760. : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
  761. MultiExprArg Args = Init;
  762. if (CXXDirectInit)
  763. Args =
  764. MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
  765. QualType DclT;
  766. InitializationSequence InitSeq(*this, Entity, Kind, Args);
  767. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  768. if (Result.isInvalid())
  769. return QualType();
  770. Init = Result.getAs<Expr>();
  771. return DeducedType;
  772. }
  773. VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
  774. QualType InitCaptureType,
  775. SourceLocation EllipsisLoc,
  776. IdentifierInfo *Id,
  777. unsigned InitStyle, Expr *Init) {
  778. // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
  779. // rather than reconstructing it here.
  780. TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
  781. if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
  782. PETL.setEllipsisLoc(EllipsisLoc);
  783. // Create a dummy variable representing the init-capture. This is not actually
  784. // used as a variable, and only exists as a way to name and refer to the
  785. // init-capture.
  786. // FIXME: Pass in separate source locations for '&' and identifier.
  787. VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
  788. Loc, Id, InitCaptureType, TSI, SC_Auto);
  789. NewVD->setInitCapture(true);
  790. NewVD->setReferenced(true);
  791. // FIXME: Pass in a VarDecl::InitializationStyle.
  792. NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
  793. NewVD->markUsed(Context);
  794. NewVD->setInit(Init);
  795. if (NewVD->isParameterPack())
  796. getCurLambda()->LocalPacks.push_back(NewVD);
  797. return NewVD;
  798. }
  799. void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
  800. assert(Var->isInitCapture() && "init capture flag should be set");
  801. LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
  802. /*isNested*/false, Var->getLocation(), SourceLocation(),
  803. Var->getType(), /*Invalid*/false);
  804. }
  805. void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
  806. Declarator &ParamInfo,
  807. Scope *CurScope) {
  808. LambdaScopeInfo *const LSI = getCurLambda();
  809. assert(LSI && "LambdaScopeInfo should be on stack!");
  810. // Determine if we're within a context where we know that the lambda will
  811. // be dependent, because there are template parameters in scope.
  812. bool KnownDependent;
  813. if (LSI->NumExplicitTemplateParams > 0) {
  814. auto *TemplateParamScope = CurScope->getTemplateParamParent();
  815. assert(TemplateParamScope &&
  816. "Lambda with explicit template param list should establish a "
  817. "template param scope");
  818. assert(TemplateParamScope->getParent());
  819. KnownDependent = TemplateParamScope->getParent()
  820. ->getTemplateParamParent() != nullptr;
  821. } else {
  822. KnownDependent = CurScope->getTemplateParamParent() != nullptr;
  823. }
  824. // Determine the signature of the call operator.
  825. TypeSourceInfo *MethodTyInfo;
  826. bool ExplicitParams = true;
  827. bool ExplicitResultType = true;
  828. bool ContainsUnexpandedParameterPack = false;
  829. SourceLocation EndLoc;
  830. SmallVector<ParmVarDecl *, 8> Params;
  831. if (ParamInfo.getNumTypeObjects() == 0) {
  832. // C++11 [expr.prim.lambda]p4:
  833. // If a lambda-expression does not include a lambda-declarator, it is as
  834. // if the lambda-declarator were ().
  835. FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
  836. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  837. EPI.HasTrailingReturn = true;
  838. EPI.TypeQuals.addConst();
  839. LangAS AS = getDefaultCXXMethodAddrSpace();
  840. if (AS != LangAS::Default)
  841. EPI.TypeQuals.addAddressSpace(AS);
  842. // C++1y [expr.prim.lambda]:
  843. // The lambda return type is 'auto', which is replaced by the
  844. // trailing-return type if provided and/or deduced from 'return'
  845. // statements
  846. // We don't do this before C++1y, because we don't support deduced return
  847. // types there.
  848. QualType DefaultTypeForNoTrailingReturn =
  849. getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
  850. : Context.DependentTy;
  851. QualType MethodTy =
  852. Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
  853. MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
  854. ExplicitParams = false;
  855. ExplicitResultType = false;
  856. EndLoc = Intro.Range.getEnd();
  857. } else {
  858. assert(ParamInfo.isFunctionDeclarator() &&
  859. "lambda-declarator is a function");
  860. DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
  861. // C++11 [expr.prim.lambda]p5:
  862. // This function call operator is declared const (9.3.1) if and only if
  863. // the lambda-expression's parameter-declaration-clause is not followed
  864. // by mutable. It is neither virtual nor declared volatile. [...]
  865. if (!FTI.hasMutableQualifier()) {
  866. FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
  867. SourceLocation());
  868. }
  869. MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
  870. assert(MethodTyInfo && "no type from lambda-declarator");
  871. EndLoc = ParamInfo.getSourceRange().getEnd();
  872. ExplicitResultType = FTI.hasTrailingReturnType();
  873. if (FTIHasNonVoidParameters(FTI)) {
  874. Params.reserve(FTI.NumParams);
  875. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
  876. Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
  877. }
  878. // Check for unexpanded parameter packs in the method type.
  879. if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
  880. DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
  881. UPPC_DeclarationType);
  882. }
  883. CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
  884. KnownDependent, Intro.Default);
  885. CXXMethodDecl *Method =
  886. startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
  887. ParamInfo.getDeclSpec().getConstexprSpecifier(),
  888. ParamInfo.getTrailingRequiresClause());
  889. if (ExplicitParams)
  890. CheckCXXDefaultArguments(Method);
  891. // This represents the function body for the lambda function, check if we
  892. // have to apply optnone due to a pragma.
  893. AddRangeBasedOptnone(Method);
  894. // code_seg attribute on lambda apply to the method.
  895. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  896. Method->addAttr(A);
  897. // Attributes on the lambda apply to the method.
  898. ProcessDeclAttributes(CurScope, Method, ParamInfo);
  899. // CUDA lambdas get implicit host and device attributes.
  900. if (getLangOpts().CUDA)
  901. CUDASetLambdaAttrs(Method);
  902. // OpenMP lambdas might get assumumption attributes.
  903. if (LangOpts.OpenMP)
  904. ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
  905. // Number the lambda for linkage purposes if necessary.
  906. handleLambdaNumbering(Class, Method);
  907. // Introduce the function call operator as the current declaration context.
  908. PushDeclContext(CurScope, Method);
  909. // Build the lambda scope.
  910. buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
  911. ExplicitParams, ExplicitResultType, !Method->isConst());
  912. // C++11 [expr.prim.lambda]p9:
  913. // A lambda-expression whose smallest enclosing scope is a block scope is a
  914. // local lambda expression; any other lambda expression shall not have a
  915. // capture-default or simple-capture in its lambda-introducer.
  916. //
  917. // For simple-captures, this is covered by the check below that any named
  918. // entity is a variable that can be captured.
  919. //
  920. // For DR1632, we also allow a capture-default in any context where we can
  921. // odr-use 'this' (in particular, in a default initializer for a non-static
  922. // data member).
  923. if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
  924. (getCurrentThisType().isNull() ||
  925. CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
  926. /*BuildAndDiagnose*/false)))
  927. Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
  928. // Distinct capture names, for diagnostics.
  929. llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
  930. // Handle explicit captures.
  931. SourceLocation PrevCaptureLoc
  932. = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
  933. for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
  934. PrevCaptureLoc = C->Loc, ++C) {
  935. if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
  936. if (C->Kind == LCK_StarThis)
  937. Diag(C->Loc, !getLangOpts().CPlusPlus17
  938. ? diag::ext_star_this_lambda_capture_cxx17
  939. : diag::warn_cxx14_compat_star_this_lambda_capture);
  940. // C++11 [expr.prim.lambda]p8:
  941. // An identifier or this shall not appear more than once in a
  942. // lambda-capture.
  943. if (LSI->isCXXThisCaptured()) {
  944. Diag(C->Loc, diag::err_capture_more_than_once)
  945. << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
  946. << FixItHint::CreateRemoval(
  947. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  948. continue;
  949. }
  950. // C++2a [expr.prim.lambda]p8:
  951. // If a lambda-capture includes a capture-default that is =,
  952. // each simple-capture of that lambda-capture shall be of the form
  953. // "&identifier", "this", or "* this". [ Note: The form [&,this] is
  954. // redundant but accepted for compatibility with ISO C++14. --end note ]
  955. if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
  956. Diag(C->Loc, !getLangOpts().CPlusPlus20
  957. ? diag::ext_equals_this_lambda_capture_cxx20
  958. : diag::warn_cxx17_compat_equals_this_lambda_capture);
  959. // C++11 [expr.prim.lambda]p12:
  960. // If this is captured by a local lambda expression, its nearest
  961. // enclosing function shall be a non-static member function.
  962. QualType ThisCaptureType = getCurrentThisType();
  963. if (ThisCaptureType.isNull()) {
  964. Diag(C->Loc, diag::err_this_capture) << true;
  965. continue;
  966. }
  967. CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
  968. /*FunctionScopeIndexToStopAtPtr*/ nullptr,
  969. C->Kind == LCK_StarThis);
  970. if (!LSI->Captures.empty())
  971. LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
  972. continue;
  973. }
  974. assert(C->Id && "missing identifier for capture");
  975. if (C->Init.isInvalid())
  976. continue;
  977. VarDecl *Var = nullptr;
  978. if (C->Init.isUsable()) {
  979. Diag(C->Loc, getLangOpts().CPlusPlus14
  980. ? diag::warn_cxx11_compat_init_capture
  981. : diag::ext_init_capture);
  982. // If the initializer expression is usable, but the InitCaptureType
  983. // is not, then an error has occurred - so ignore the capture for now.
  984. // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
  985. // FIXME: we should create the init capture variable and mark it invalid
  986. // in this case.
  987. if (C->InitCaptureType.get().isNull())
  988. continue;
  989. if (C->Init.get()->containsUnexpandedParameterPack() &&
  990. !C->InitCaptureType.get()->getAs<PackExpansionType>())
  991. DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
  992. unsigned InitStyle;
  993. switch (C->InitKind) {
  994. case LambdaCaptureInitKind::NoInit:
  995. llvm_unreachable("not an init-capture?");
  996. case LambdaCaptureInitKind::CopyInit:
  997. InitStyle = VarDecl::CInit;
  998. break;
  999. case LambdaCaptureInitKind::DirectInit:
  1000. InitStyle = VarDecl::CallInit;
  1001. break;
  1002. case LambdaCaptureInitKind::ListInit:
  1003. InitStyle = VarDecl::ListInit;
  1004. break;
  1005. }
  1006. Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
  1007. C->EllipsisLoc, C->Id, InitStyle,
  1008. C->Init.get());
  1009. // C++1y [expr.prim.lambda]p11:
  1010. // An init-capture behaves as if it declares and explicitly
  1011. // captures a variable [...] whose declarative region is the
  1012. // lambda-expression's compound-statement
  1013. if (Var)
  1014. PushOnScopeChains(Var, CurScope, false);
  1015. } else {
  1016. assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
  1017. "init capture has valid but null init?");
  1018. // C++11 [expr.prim.lambda]p8:
  1019. // If a lambda-capture includes a capture-default that is &, the
  1020. // identifiers in the lambda-capture shall not be preceded by &.
  1021. // If a lambda-capture includes a capture-default that is =, [...]
  1022. // each identifier it contains shall be preceded by &.
  1023. if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
  1024. Diag(C->Loc, diag::err_reference_capture_with_reference_default)
  1025. << FixItHint::CreateRemoval(
  1026. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  1027. continue;
  1028. } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
  1029. Diag(C->Loc, diag::err_copy_capture_with_copy_default)
  1030. << FixItHint::CreateRemoval(
  1031. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  1032. continue;
  1033. }
  1034. // C++11 [expr.prim.lambda]p10:
  1035. // The identifiers in a capture-list are looked up using the usual
  1036. // rules for unqualified name lookup (3.4.1)
  1037. DeclarationNameInfo Name(C->Id, C->Loc);
  1038. LookupResult R(*this, Name, LookupOrdinaryName);
  1039. LookupName(R, CurScope);
  1040. if (R.isAmbiguous())
  1041. continue;
  1042. if (R.empty()) {
  1043. // FIXME: Disable corrections that would add qualification?
  1044. CXXScopeSpec ScopeSpec;
  1045. DeclFilterCCC<VarDecl> Validator{};
  1046. if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
  1047. continue;
  1048. }
  1049. Var = R.getAsSingle<VarDecl>();
  1050. if (Var && DiagnoseUseOfDecl(Var, C->Loc))
  1051. continue;
  1052. }
  1053. // C++11 [expr.prim.lambda]p8:
  1054. // An identifier or this shall not appear more than once in a
  1055. // lambda-capture.
  1056. if (!CaptureNames.insert(C->Id).second) {
  1057. if (Var && LSI->isCaptured(Var)) {
  1058. Diag(C->Loc, diag::err_capture_more_than_once)
  1059. << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
  1060. << FixItHint::CreateRemoval(
  1061. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  1062. } else
  1063. // Previous capture captured something different (one or both was
  1064. // an init-cpature): no fixit.
  1065. Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
  1066. continue;
  1067. }
  1068. // C++11 [expr.prim.lambda]p10:
  1069. // [...] each such lookup shall find a variable with automatic storage
  1070. // duration declared in the reaching scope of the local lambda expression.
  1071. // Note that the 'reaching scope' check happens in tryCaptureVariable().
  1072. if (!Var) {
  1073. Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
  1074. continue;
  1075. }
  1076. // Ignore invalid decls; they'll just confuse the code later.
  1077. if (Var->isInvalidDecl())
  1078. continue;
  1079. if (!Var->hasLocalStorage()) {
  1080. Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
  1081. Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
  1082. continue;
  1083. }
  1084. // C++11 [expr.prim.lambda]p23:
  1085. // A capture followed by an ellipsis is a pack expansion (14.5.3).
  1086. SourceLocation EllipsisLoc;
  1087. if (C->EllipsisLoc.isValid()) {
  1088. if (Var->isParameterPack()) {
  1089. EllipsisLoc = C->EllipsisLoc;
  1090. } else {
  1091. Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1092. << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
  1093. : SourceRange(C->Loc));
  1094. // Just ignore the ellipsis.
  1095. }
  1096. } else if (Var->isParameterPack()) {
  1097. ContainsUnexpandedParameterPack = true;
  1098. }
  1099. if (C->Init.isUsable()) {
  1100. addInitCapture(LSI, Var);
  1101. } else {
  1102. TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
  1103. TryCapture_ExplicitByVal;
  1104. tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
  1105. }
  1106. if (!LSI->Captures.empty())
  1107. LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
  1108. }
  1109. finishLambdaExplicitCaptures(LSI);
  1110. LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
  1111. // Add lambda parameters into scope.
  1112. addLambdaParameters(Intro.Captures, Method, CurScope);
  1113. // Enter a new evaluation context to insulate the lambda from any
  1114. // cleanups from the enclosing full-expression.
  1115. PushExpressionEvaluationContext(
  1116. LSI->CallOperator->isConsteval()
  1117. ? ExpressionEvaluationContext::ImmediateFunctionContext
  1118. : ExpressionEvaluationContext::PotentiallyEvaluated);
  1119. }
  1120. void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
  1121. bool IsInstantiation) {
  1122. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
  1123. // Leave the expression-evaluation context.
  1124. DiscardCleanupsInEvaluationContext();
  1125. PopExpressionEvaluationContext();
  1126. // Leave the context of the lambda.
  1127. if (!IsInstantiation)
  1128. PopDeclContext();
  1129. // Finalize the lambda.
  1130. CXXRecordDecl *Class = LSI->Lambda;
  1131. Class->setInvalidDecl();
  1132. SmallVector<Decl*, 4> Fields(Class->fields());
  1133. ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
  1134. SourceLocation(), ParsedAttributesView());
  1135. CheckCompletedCXXClass(nullptr, Class);
  1136. PopFunctionScopeInfo();
  1137. }
  1138. template <typename Func>
  1139. static void repeatForLambdaConversionFunctionCallingConvs(
  1140. Sema &S, const FunctionProtoType &CallOpProto, Func F) {
  1141. CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
  1142. CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
  1143. CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
  1144. CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
  1145. CallingConv CallOpCC = CallOpProto.getCallConv();
  1146. /// Implement emitting a version of the operator for many of the calling
  1147. /// conventions for MSVC, as described here:
  1148. /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
  1149. /// Experimentally, we determined that cdecl, stdcall, fastcall, and
  1150. /// vectorcall are generated by MSVC when it is supported by the target.
  1151. /// Additionally, we are ensuring that the default-free/default-member and
  1152. /// call-operator calling convention are generated as well.
  1153. /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
  1154. /// 'member default', despite MSVC not doing so. We do this in order to ensure
  1155. /// that someone who intentionally places 'thiscall' on the lambda call
  1156. /// operator will still get that overload, since we don't have the a way of
  1157. /// detecting the attribute by the time we get here.
  1158. if (S.getLangOpts().MSVCCompat) {
  1159. CallingConv Convs[] = {
  1160. CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
  1161. DefaultFree, DefaultMember, CallOpCC};
  1162. llvm::sort(Convs);
  1163. llvm::iterator_range<CallingConv *> Range(
  1164. std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
  1165. const TargetInfo &TI = S.getASTContext().getTargetInfo();
  1166. for (CallingConv C : Range) {
  1167. if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
  1168. F(C);
  1169. }
  1170. return;
  1171. }
  1172. if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
  1173. F(DefaultFree);
  1174. F(DefaultMember);
  1175. } else {
  1176. F(CallOpCC);
  1177. }
  1178. }
  1179. // Returns the 'standard' calling convention to be used for the lambda
  1180. // conversion function, that is, the 'free' function calling convention unless
  1181. // it is overridden by a non-default calling convention attribute.
  1182. static CallingConv
  1183. getLambdaConversionFunctionCallConv(Sema &S,
  1184. const FunctionProtoType *CallOpProto) {
  1185. CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
  1186. CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
  1187. CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
  1188. CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
  1189. CallingConv CallOpCC = CallOpProto->getCallConv();
  1190. // If the call-operator hasn't been changed, return both the 'free' and
  1191. // 'member' function calling convention.
  1192. if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
  1193. return DefaultFree;
  1194. return CallOpCC;
  1195. }
  1196. QualType Sema::getLambdaConversionFunctionResultType(
  1197. const FunctionProtoType *CallOpProto, CallingConv CC) {
  1198. const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
  1199. CallOpProto->getExtProtoInfo();
  1200. FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
  1201. InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
  1202. InvokerExtInfo.TypeQuals = Qualifiers();
  1203. assert(InvokerExtInfo.RefQualifier == RQ_None &&
  1204. "Lambda's call operator should not have a reference qualifier");
  1205. return Context.getFunctionType(CallOpProto->getReturnType(),
  1206. CallOpProto->getParamTypes(), InvokerExtInfo);
  1207. }
  1208. /// Add a lambda's conversion to function pointer, as described in
  1209. /// C++11 [expr.prim.lambda]p6.
  1210. static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
  1211. CXXRecordDecl *Class,
  1212. CXXMethodDecl *CallOperator,
  1213. QualType InvokerFunctionTy) {
  1214. // This conversion is explicitly disabled if the lambda's function has
  1215. // pass_object_size attributes on any of its parameters.
  1216. auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
  1217. return P->hasAttr<PassObjectSizeAttr>();
  1218. };
  1219. if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
  1220. return;
  1221. // Add the conversion to function pointer.
  1222. QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
  1223. // Create the type of the conversion function.
  1224. FunctionProtoType::ExtProtoInfo ConvExtInfo(
  1225. S.Context.getDefaultCallingConvention(
  1226. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  1227. // The conversion function is always const and noexcept.
  1228. ConvExtInfo.TypeQuals = Qualifiers();
  1229. ConvExtInfo.TypeQuals.addConst();
  1230. ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
  1231. QualType ConvTy =
  1232. S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
  1233. SourceLocation Loc = IntroducerRange.getBegin();
  1234. DeclarationName ConversionName
  1235. = S.Context.DeclarationNames.getCXXConversionFunctionName(
  1236. S.Context.getCanonicalType(PtrToFunctionTy));
  1237. // Construct a TypeSourceInfo for the conversion function, and wire
  1238. // all the parameters appropriately for the FunctionProtoTypeLoc
  1239. // so that everything works during transformation/instantiation of
  1240. // generic lambdas.
  1241. // The main reason for wiring up the parameters of the conversion
  1242. // function with that of the call operator is so that constructs
  1243. // like the following work:
  1244. // auto L = [](auto b) { <-- 1
  1245. // return [](auto a) -> decltype(a) { <-- 2
  1246. // return a;
  1247. // };
  1248. // };
  1249. // int (*fp)(int) = L(5);
  1250. // Because the trailing return type can contain DeclRefExprs that refer
  1251. // to the original call operator's variables, we hijack the call
  1252. // operators ParmVarDecls below.
  1253. TypeSourceInfo *ConvNamePtrToFunctionTSI =
  1254. S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
  1255. DeclarationNameLoc ConvNameLoc =
  1256. DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
  1257. // The conversion function is a conversion to a pointer-to-function.
  1258. TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
  1259. FunctionProtoTypeLoc ConvTL =
  1260. ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  1261. // Get the result of the conversion function which is a pointer-to-function.
  1262. PointerTypeLoc PtrToFunctionTL =
  1263. ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
  1264. // Do the same for the TypeSourceInfo that is used to name the conversion
  1265. // operator.
  1266. PointerTypeLoc ConvNamePtrToFunctionTL =
  1267. ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
  1268. // Get the underlying function types that the conversion function will
  1269. // be converting to (should match the type of the call operator).
  1270. FunctionProtoTypeLoc CallOpConvTL =
  1271. PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
  1272. FunctionProtoTypeLoc CallOpConvNameTL =
  1273. ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
  1274. // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
  1275. // These parameter's are essentially used to transform the name and
  1276. // the type of the conversion operator. By using the same parameters
  1277. // as the call operator's we don't have to fix any back references that
  1278. // the trailing return type of the call operator's uses (such as
  1279. // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
  1280. // - we can simply use the return type of the call operator, and
  1281. // everything should work.
  1282. SmallVector<ParmVarDecl *, 4> InvokerParams;
  1283. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
  1284. ParmVarDecl *From = CallOperator->getParamDecl(I);
  1285. InvokerParams.push_back(ParmVarDecl::Create(
  1286. S.Context,
  1287. // Temporarily add to the TU. This is set to the invoker below.
  1288. S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
  1289. From->getLocation(), From->getIdentifier(), From->getType(),
  1290. From->getTypeSourceInfo(), From->getStorageClass(),
  1291. /*DefArg=*/nullptr));
  1292. CallOpConvTL.setParam(I, From);
  1293. CallOpConvNameTL.setParam(I, From);
  1294. }
  1295. CXXConversionDecl *Conversion = CXXConversionDecl::Create(
  1296. S.Context, Class, Loc,
  1297. DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
  1298. S.getCurFPFeatures().isFPConstrained(),
  1299. /*isInline=*/true, ExplicitSpecifier(),
  1300. S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
  1301. : ConstexprSpecKind::Unspecified,
  1302. CallOperator->getBody()->getEndLoc());
  1303. Conversion->setAccess(AS_public);
  1304. Conversion->setImplicit(true);
  1305. if (Class->isGenericLambda()) {
  1306. // Create a template version of the conversion operator, using the template
  1307. // parameter list of the function call operator.
  1308. FunctionTemplateDecl *TemplateCallOperator =
  1309. CallOperator->getDescribedFunctionTemplate();
  1310. FunctionTemplateDecl *ConversionTemplate =
  1311. FunctionTemplateDecl::Create(S.Context, Class,
  1312. Loc, ConversionName,
  1313. TemplateCallOperator->getTemplateParameters(),
  1314. Conversion);
  1315. ConversionTemplate->setAccess(AS_public);
  1316. ConversionTemplate->setImplicit(true);
  1317. Conversion->setDescribedFunctionTemplate(ConversionTemplate);
  1318. Class->addDecl(ConversionTemplate);
  1319. } else
  1320. Class->addDecl(Conversion);
  1321. // Add a non-static member function that will be the result of
  1322. // the conversion with a certain unique ID.
  1323. DeclarationName InvokerName = &S.Context.Idents.get(
  1324. getLambdaStaticInvokerName());
  1325. // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
  1326. // we should get a prebuilt TrivialTypeSourceInfo from Context
  1327. // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
  1328. // then rewire the parameters accordingly, by hoisting up the InvokeParams
  1329. // loop below and then use its Params to set Invoke->setParams(...) below.
  1330. // This would avoid the 'const' qualifier of the calloperator from
  1331. // contaminating the type of the invoker, which is currently adjusted
  1332. // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
  1333. // trailing return type of the invoker would require a visitor to rebuild
  1334. // the trailing return type and adjusting all back DeclRefExpr's to refer
  1335. // to the new static invoker parameters - not the call operator's.
  1336. CXXMethodDecl *Invoke = CXXMethodDecl::Create(
  1337. S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
  1338. InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
  1339. S.getCurFPFeatures().isFPConstrained(),
  1340. /*isInline=*/true, ConstexprSpecKind::Unspecified,
  1341. CallOperator->getBody()->getEndLoc());
  1342. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
  1343. InvokerParams[I]->setOwningFunction(Invoke);
  1344. Invoke->setParams(InvokerParams);
  1345. Invoke->setAccess(AS_private);
  1346. Invoke->setImplicit(true);
  1347. if (Class->isGenericLambda()) {
  1348. FunctionTemplateDecl *TemplateCallOperator =
  1349. CallOperator->getDescribedFunctionTemplate();
  1350. FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
  1351. S.Context, Class, Loc, InvokerName,
  1352. TemplateCallOperator->getTemplateParameters(),
  1353. Invoke);
  1354. StaticInvokerTemplate->setAccess(AS_private);
  1355. StaticInvokerTemplate->setImplicit(true);
  1356. Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
  1357. Class->addDecl(StaticInvokerTemplate);
  1358. } else
  1359. Class->addDecl(Invoke);
  1360. }
  1361. /// Add a lambda's conversion to function pointers, as described in
  1362. /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
  1363. /// single pointer conversion. In the event that the default calling convention
  1364. /// for free and member functions is different, it will emit both conventions.
  1365. static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
  1366. CXXRecordDecl *Class,
  1367. CXXMethodDecl *CallOperator) {
  1368. const FunctionProtoType *CallOpProto =
  1369. CallOperator->getType()->castAs<FunctionProtoType>();
  1370. repeatForLambdaConversionFunctionCallingConvs(
  1371. S, *CallOpProto, [&](CallingConv CC) {
  1372. QualType InvokerFunctionTy =
  1373. S.getLambdaConversionFunctionResultType(CallOpProto, CC);
  1374. addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
  1375. InvokerFunctionTy);
  1376. });
  1377. }
  1378. /// Add a lambda's conversion to block pointer.
  1379. static void addBlockPointerConversion(Sema &S,
  1380. SourceRange IntroducerRange,
  1381. CXXRecordDecl *Class,
  1382. CXXMethodDecl *CallOperator) {
  1383. const FunctionProtoType *CallOpProto =
  1384. CallOperator->getType()->castAs<FunctionProtoType>();
  1385. QualType FunctionTy = S.getLambdaConversionFunctionResultType(
  1386. CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
  1387. QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
  1388. FunctionProtoType::ExtProtoInfo ConversionEPI(
  1389. S.Context.getDefaultCallingConvention(
  1390. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  1391. ConversionEPI.TypeQuals = Qualifiers();
  1392. ConversionEPI.TypeQuals.addConst();
  1393. QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
  1394. SourceLocation Loc = IntroducerRange.getBegin();
  1395. DeclarationName Name
  1396. = S.Context.DeclarationNames.getCXXConversionFunctionName(
  1397. S.Context.getCanonicalType(BlockPtrTy));
  1398. DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
  1399. S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
  1400. CXXConversionDecl *Conversion = CXXConversionDecl::Create(
  1401. S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
  1402. S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
  1403. S.getCurFPFeatures().isFPConstrained(),
  1404. /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
  1405. CallOperator->getBody()->getEndLoc());
  1406. Conversion->setAccess(AS_public);
  1407. Conversion->setImplicit(true);
  1408. Class->addDecl(Conversion);
  1409. }
  1410. ExprResult Sema::BuildCaptureInit(const Capture &Cap,
  1411. SourceLocation ImplicitCaptureLoc,
  1412. bool IsOpenMPMapping) {
  1413. // VLA captures don't have a stored initialization expression.
  1414. if (Cap.isVLATypeCapture())
  1415. return ExprResult();
  1416. // An init-capture is initialized directly from its stored initializer.
  1417. if (Cap.isInitCapture())
  1418. return Cap.getVariable()->getInit();
  1419. // For anything else, build an initialization expression. For an implicit
  1420. // capture, the capture notionally happens at the capture-default, so use
  1421. // that location here.
  1422. SourceLocation Loc =
  1423. ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
  1424. // C++11 [expr.prim.lambda]p21:
  1425. // When the lambda-expression is evaluated, the entities that
  1426. // are captured by copy are used to direct-initialize each
  1427. // corresponding non-static data member of the resulting closure
  1428. // object. (For array members, the array elements are
  1429. // direct-initialized in increasing subscript order.) These
  1430. // initializations are performed in the (unspecified) order in
  1431. // which the non-static data members are declared.
  1432. // C++ [expr.prim.lambda]p12:
  1433. // An entity captured by a lambda-expression is odr-used (3.2) in
  1434. // the scope containing the lambda-expression.
  1435. ExprResult Init;
  1436. IdentifierInfo *Name = nullptr;
  1437. if (Cap.isThisCapture()) {
  1438. QualType ThisTy = getCurrentThisType();
  1439. Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
  1440. if (Cap.isCopyCapture())
  1441. Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
  1442. else
  1443. Init = This;
  1444. } else {
  1445. assert(Cap.isVariableCapture() && "unknown kind of capture");
  1446. VarDecl *Var = Cap.getVariable();
  1447. Name = Var->getIdentifier();
  1448. Init = BuildDeclarationNameExpr(
  1449. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  1450. }
  1451. // In OpenMP, the capture kind doesn't actually describe how to capture:
  1452. // variables are "mapped" onto the device in a process that does not formally
  1453. // make a copy, even for a "copy capture".
  1454. if (IsOpenMPMapping)
  1455. return Init;
  1456. if (Init.isInvalid())
  1457. return ExprError();
  1458. Expr *InitExpr = Init.get();
  1459. InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
  1460. Name, Cap.getCaptureType(), Loc);
  1461. InitializationKind InitKind =
  1462. InitializationKind::CreateDirect(Loc, Loc, Loc);
  1463. InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
  1464. return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
  1465. }
  1466. ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
  1467. Scope *CurScope) {
  1468. LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
  1469. ActOnFinishFunctionBody(LSI.CallOperator, Body);
  1470. return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
  1471. }
  1472. static LambdaCaptureDefault
  1473. mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
  1474. switch (ICS) {
  1475. case CapturingScopeInfo::ImpCap_None:
  1476. return LCD_None;
  1477. case CapturingScopeInfo::ImpCap_LambdaByval:
  1478. return LCD_ByCopy;
  1479. case CapturingScopeInfo::ImpCap_CapturedRegion:
  1480. case CapturingScopeInfo::ImpCap_LambdaByref:
  1481. return LCD_ByRef;
  1482. case CapturingScopeInfo::ImpCap_Block:
  1483. llvm_unreachable("block capture in lambda");
  1484. }
  1485. llvm_unreachable("Unknown implicit capture style");
  1486. }
  1487. bool Sema::CaptureHasSideEffects(const Capture &From) {
  1488. if (From.isInitCapture()) {
  1489. Expr *Init = From.getVariable()->getInit();
  1490. if (Init && Init->HasSideEffects(Context))
  1491. return true;
  1492. }
  1493. if (!From.isCopyCapture())
  1494. return false;
  1495. const QualType T = From.isThisCapture()
  1496. ? getCurrentThisType()->getPointeeType()
  1497. : From.getCaptureType();
  1498. if (T.isVolatileQualified())
  1499. return true;
  1500. const Type *BaseT = T->getBaseElementTypeUnsafe();
  1501. if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
  1502. return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
  1503. !RD->hasTrivialDestructor();
  1504. return false;
  1505. }
  1506. bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
  1507. const Capture &From) {
  1508. if (CaptureHasSideEffects(From))
  1509. return false;
  1510. if (From.isVLATypeCapture())
  1511. return false;
  1512. auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
  1513. if (From.isThisCapture())
  1514. diag << "'this'";
  1515. else
  1516. diag << From.getVariable();
  1517. diag << From.isNonODRUsed();
  1518. diag << FixItHint::CreateRemoval(CaptureRange);
  1519. return true;
  1520. }
  1521. /// Create a field within the lambda class or captured statement record for the
  1522. /// given capture.
  1523. FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
  1524. const sema::Capture &Capture) {
  1525. SourceLocation Loc = Capture.getLocation();
  1526. QualType FieldType = Capture.getCaptureType();
  1527. TypeSourceInfo *TSI = nullptr;
  1528. if (Capture.isVariableCapture()) {
  1529. auto *Var = Capture.getVariable();
  1530. if (Var->isInitCapture())
  1531. TSI = Capture.getVariable()->getTypeSourceInfo();
  1532. }
  1533. // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
  1534. // appropriate, at least for an implicit capture.
  1535. if (!TSI)
  1536. TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
  1537. // Build the non-static data member.
  1538. FieldDecl *Field =
  1539. FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
  1540. /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
  1541. /*Mutable=*/false, ICIS_NoInit);
  1542. // If the variable being captured has an invalid type, mark the class as
  1543. // invalid as well.
  1544. if (!FieldType->isDependentType()) {
  1545. if (RequireCompleteSizedType(Loc, FieldType,
  1546. diag::err_field_incomplete_or_sizeless)) {
  1547. RD->setInvalidDecl();
  1548. Field->setInvalidDecl();
  1549. } else {
  1550. NamedDecl *Def;
  1551. FieldType->isIncompleteType(&Def);
  1552. if (Def && Def->isInvalidDecl()) {
  1553. RD->setInvalidDecl();
  1554. Field->setInvalidDecl();
  1555. }
  1556. }
  1557. }
  1558. Field->setImplicit(true);
  1559. Field->setAccess(AS_private);
  1560. RD->addDecl(Field);
  1561. if (Capture.isVLATypeCapture())
  1562. Field->setCapturedVLAType(Capture.getCapturedVLAType());
  1563. return Field;
  1564. }
  1565. ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
  1566. LambdaScopeInfo *LSI) {
  1567. // Collect information from the lambda scope.
  1568. SmallVector<LambdaCapture, 4> Captures;
  1569. SmallVector<Expr *, 4> CaptureInits;
  1570. SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
  1571. LambdaCaptureDefault CaptureDefault =
  1572. mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
  1573. CXXRecordDecl *Class;
  1574. CXXMethodDecl *CallOperator;
  1575. SourceRange IntroducerRange;
  1576. bool ExplicitParams;
  1577. bool ExplicitResultType;
  1578. CleanupInfo LambdaCleanup;
  1579. bool ContainsUnexpandedParameterPack;
  1580. bool IsGenericLambda;
  1581. {
  1582. CallOperator = LSI->CallOperator;
  1583. Class = LSI->Lambda;
  1584. IntroducerRange = LSI->IntroducerRange;
  1585. ExplicitParams = LSI->ExplicitParams;
  1586. ExplicitResultType = !LSI->HasImplicitReturnType;
  1587. LambdaCleanup = LSI->Cleanup;
  1588. ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
  1589. IsGenericLambda = Class->isGenericLambda();
  1590. CallOperator->setLexicalDeclContext(Class);
  1591. Decl *TemplateOrNonTemplateCallOperatorDecl =
  1592. CallOperator->getDescribedFunctionTemplate()
  1593. ? CallOperator->getDescribedFunctionTemplate()
  1594. : cast<Decl>(CallOperator);
  1595. // FIXME: Is this really the best choice? Keeping the lexical decl context
  1596. // set as CurContext seems more faithful to the source.
  1597. TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
  1598. PopExpressionEvaluationContext();
  1599. // True if the current capture has a used capture or default before it.
  1600. bool CurHasPreviousCapture = CaptureDefault != LCD_None;
  1601. SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
  1602. CaptureDefaultLoc : IntroducerRange.getBegin();
  1603. for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
  1604. const Capture &From = LSI->Captures[I];
  1605. if (From.isInvalid())
  1606. return ExprError();
  1607. assert(!From.isBlockCapture() && "Cannot capture __block variables");
  1608. bool IsImplicit = I >= LSI->NumExplicitCaptures;
  1609. SourceLocation ImplicitCaptureLoc =
  1610. IsImplicit ? CaptureDefaultLoc : SourceLocation();
  1611. // Use source ranges of explicit captures for fixits where available.
  1612. SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
  1613. // Warn about unused explicit captures.
  1614. bool IsCaptureUsed = true;
  1615. if (!CurContext->isDependentContext() && !IsImplicit &&
  1616. !From.isODRUsed()) {
  1617. // Initialized captures that are non-ODR used may not be eliminated.
  1618. // FIXME: Where did the IsGenericLambda here come from?
  1619. bool NonODRUsedInitCapture =
  1620. IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
  1621. if (!NonODRUsedInitCapture) {
  1622. bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
  1623. SourceRange FixItRange;
  1624. if (CaptureRange.isValid()) {
  1625. if (!CurHasPreviousCapture && !IsLast) {
  1626. // If there are no captures preceding this capture, remove the
  1627. // following comma.
  1628. FixItRange = SourceRange(CaptureRange.getBegin(),
  1629. getLocForEndOfToken(CaptureRange.getEnd()));
  1630. } else {
  1631. // Otherwise, remove the comma since the last used capture.
  1632. FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
  1633. CaptureRange.getEnd());
  1634. }
  1635. }
  1636. IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
  1637. }
  1638. }
  1639. if (CaptureRange.isValid()) {
  1640. CurHasPreviousCapture |= IsCaptureUsed;
  1641. PrevCaptureLoc = CaptureRange.getEnd();
  1642. }
  1643. // Map the capture to our AST representation.
  1644. LambdaCapture Capture = [&] {
  1645. if (From.isThisCapture()) {
  1646. // Capturing 'this' implicitly with a default of '[=]' is deprecated,
  1647. // because it results in a reference capture. Don't warn prior to
  1648. // C++2a; there's nothing that can be done about it before then.
  1649. if (getLangOpts().CPlusPlus20 && IsImplicit &&
  1650. CaptureDefault == LCD_ByCopy) {
  1651. Diag(From.getLocation(), diag::warn_deprecated_this_capture);
  1652. Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
  1653. << FixItHint::CreateInsertion(
  1654. getLocForEndOfToken(CaptureDefaultLoc), ", this");
  1655. }
  1656. return LambdaCapture(From.getLocation(), IsImplicit,
  1657. From.isCopyCapture() ? LCK_StarThis : LCK_This);
  1658. } else if (From.isVLATypeCapture()) {
  1659. return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
  1660. } else {
  1661. assert(From.isVariableCapture() && "unknown kind of capture");
  1662. VarDecl *Var = From.getVariable();
  1663. LambdaCaptureKind Kind =
  1664. From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
  1665. return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
  1666. From.getEllipsisLoc());
  1667. }
  1668. }();
  1669. // Form the initializer for the capture field.
  1670. ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
  1671. // FIXME: Skip this capture if the capture is not used, the initializer
  1672. // has no side-effects, the type of the capture is trivial, and the
  1673. // lambda is not externally visible.
  1674. // Add a FieldDecl for the capture and form its initializer.
  1675. BuildCaptureField(Class, From);
  1676. Captures.push_back(Capture);
  1677. CaptureInits.push_back(Init.get());
  1678. if (LangOpts.CUDA)
  1679. CUDACheckLambdaCapture(CallOperator, From);
  1680. }
  1681. Class->setCaptures(Context, Captures);
  1682. // C++11 [expr.prim.lambda]p6:
  1683. // The closure type for a lambda-expression with no lambda-capture
  1684. // has a public non-virtual non-explicit const conversion function
  1685. // to pointer to function having the same parameter and return
  1686. // types as the closure type's function call operator.
  1687. if (Captures.empty() && CaptureDefault == LCD_None)
  1688. addFunctionPointerConversions(*this, IntroducerRange, Class,
  1689. CallOperator);
  1690. // Objective-C++:
  1691. // The closure type for a lambda-expression has a public non-virtual
  1692. // non-explicit const conversion function to a block pointer having the
  1693. // same parameter and return types as the closure type's function call
  1694. // operator.
  1695. // FIXME: Fix generic lambda to block conversions.
  1696. if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
  1697. addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
  1698. // Finalize the lambda class.
  1699. SmallVector<Decl*, 4> Fields(Class->fields());
  1700. ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
  1701. SourceLocation(), ParsedAttributesView());
  1702. CheckCompletedCXXClass(nullptr, Class);
  1703. }
  1704. Cleanup.mergeFrom(LambdaCleanup);
  1705. LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
  1706. CaptureDefault, CaptureDefaultLoc,
  1707. ExplicitParams, ExplicitResultType,
  1708. CaptureInits, EndLoc,
  1709. ContainsUnexpandedParameterPack);
  1710. // If the lambda expression's call operator is not explicitly marked constexpr
  1711. // and we are not in a dependent context, analyze the call operator to infer
  1712. // its constexpr-ness, suppressing diagnostics while doing so.
  1713. if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
  1714. !CallOperator->isConstexpr() &&
  1715. !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
  1716. !Class->getDeclContext()->isDependentContext()) {
  1717. CallOperator->setConstexprKind(
  1718. CheckConstexprFunctionDefinition(CallOperator,
  1719. CheckConstexprKind::CheckValid)
  1720. ? ConstexprSpecKind::Constexpr
  1721. : ConstexprSpecKind::Unspecified);
  1722. }
  1723. // Emit delayed shadowing warnings now that the full capture list is known.
  1724. DiagnoseShadowingLambdaDecls(LSI);
  1725. if (!CurContext->isDependentContext()) {
  1726. switch (ExprEvalContexts.back().Context) {
  1727. // C++11 [expr.prim.lambda]p2:
  1728. // A lambda-expression shall not appear in an unevaluated operand
  1729. // (Clause 5).
  1730. case ExpressionEvaluationContext::Unevaluated:
  1731. case ExpressionEvaluationContext::UnevaluatedList:
  1732. case ExpressionEvaluationContext::UnevaluatedAbstract:
  1733. // C++1y [expr.const]p2:
  1734. // A conditional-expression e is a core constant expression unless the
  1735. // evaluation of e, following the rules of the abstract machine, would
  1736. // evaluate [...] a lambda-expression.
  1737. //
  1738. // This is technically incorrect, there are some constant evaluated contexts
  1739. // where this should be allowed. We should probably fix this when DR1607 is
  1740. // ratified, it lays out the exact set of conditions where we shouldn't
  1741. // allow a lambda-expression.
  1742. case ExpressionEvaluationContext::ConstantEvaluated:
  1743. case ExpressionEvaluationContext::ImmediateFunctionContext:
  1744. // We don't actually diagnose this case immediately, because we
  1745. // could be within a context where we might find out later that
  1746. // the expression is potentially evaluated (e.g., for typeid).
  1747. ExprEvalContexts.back().Lambdas.push_back(Lambda);
  1748. break;
  1749. case ExpressionEvaluationContext::DiscardedStatement:
  1750. case ExpressionEvaluationContext::PotentiallyEvaluated:
  1751. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  1752. break;
  1753. }
  1754. }
  1755. return MaybeBindToTemporary(Lambda);
  1756. }
  1757. ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
  1758. SourceLocation ConvLocation,
  1759. CXXConversionDecl *Conv,
  1760. Expr *Src) {
  1761. // Make sure that the lambda call operator is marked used.
  1762. CXXRecordDecl *Lambda = Conv->getParent();
  1763. CXXMethodDecl *CallOperator
  1764. = cast<CXXMethodDecl>(
  1765. Lambda->lookup(
  1766. Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
  1767. CallOperator->setReferenced();
  1768. CallOperator->markUsed(Context);
  1769. ExprResult Init = PerformCopyInitialization(
  1770. InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),
  1771. CurrentLocation, Src);
  1772. if (!Init.isInvalid())
  1773. Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  1774. if (Init.isInvalid())
  1775. return ExprError();
  1776. // Create the new block to be returned.
  1777. BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
  1778. // Set the type information.
  1779. Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
  1780. Block->setIsVariadic(CallOperator->isVariadic());
  1781. Block->setBlockMissingReturnType(false);
  1782. // Add parameters.
  1783. SmallVector<ParmVarDecl *, 4> BlockParams;
  1784. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
  1785. ParmVarDecl *From = CallOperator->getParamDecl(I);
  1786. BlockParams.push_back(ParmVarDecl::Create(
  1787. Context, Block, From->getBeginLoc(), From->getLocation(),
  1788. From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
  1789. From->getStorageClass(),
  1790. /*DefArg=*/nullptr));
  1791. }
  1792. Block->setParams(BlockParams);
  1793. Block->setIsConversionFromLambda(true);
  1794. // Add capture. The capture uses a fake variable, which doesn't correspond
  1795. // to any actual memory location. However, the initializer copy-initializes
  1796. // the lambda object.
  1797. TypeSourceInfo *CapVarTSI =
  1798. Context.getTrivialTypeSourceInfo(Src->getType());
  1799. VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
  1800. ConvLocation, nullptr,
  1801. Src->getType(), CapVarTSI,
  1802. SC_None);
  1803. BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
  1804. /*nested=*/false, /*copy=*/Init.get());
  1805. Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
  1806. // Add a fake function body to the block. IR generation is responsible
  1807. // for filling in the actual body, which cannot be expressed as an AST.
  1808. Block->setBody(new (Context) CompoundStmt(ConvLocation));
  1809. // Create the block literal expression.
  1810. Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
  1811. ExprCleanupObjects.push_back(Block);
  1812. Cleanup.setExprNeedsCleanups(true);
  1813. return BuildBlock;
  1814. }