SemaLambda.cpp 78 KB

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