SemaLambda.cpp 78 KB

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