SemaLambda.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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. bool IsInitCapturePack = false;
  744. if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
  745. PETL.setEllipsisLoc(EllipsisLoc);
  746. IsInitCapturePack = true;
  747. }
  748. // Create a dummy variable representing the init-capture. This is not actually
  749. // used as a variable, and only exists as a way to name and refer to the
  750. // init-capture.
  751. // FIXME: Pass in separate source locations for '&' and identifier.
  752. VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
  753. Loc, Id, InitCaptureType, TSI, SC_Auto);
  754. NewVD->setInitCapture(true);
  755. NewVD->setReferenced(true);
  756. // FIXME: Pass in a VarDecl::InitializationStyle.
  757. NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
  758. NewVD->markUsed(Context);
  759. NewVD->setInit(Init);
  760. if (NewVD->isParameterPack())
  761. getCurLambda()->LocalPacks.push_back(NewVD);
  762. return NewVD;
  763. }
  764. void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
  765. assert(Var->isInitCapture() && "init capture flag should be set");
  766. LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
  767. /*isNested*/false, Var->getLocation(), SourceLocation(),
  768. Var->getType(), /*Invalid*/false);
  769. }
  770. void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
  771. Declarator &ParamInfo,
  772. Scope *CurScope) {
  773. LambdaScopeInfo *const LSI = getCurLambda();
  774. assert(LSI && "LambdaScopeInfo should be on stack!");
  775. // Determine if we're within a context where we know that the lambda will
  776. // be dependent, because there are template parameters in scope.
  777. bool KnownDependent;
  778. if (LSI->NumExplicitTemplateParams > 0) {
  779. auto *TemplateParamScope = CurScope->getTemplateParamParent();
  780. assert(TemplateParamScope &&
  781. "Lambda with explicit template param list should establish a "
  782. "template param scope");
  783. assert(TemplateParamScope->getParent());
  784. KnownDependent = TemplateParamScope->getParent()
  785. ->getTemplateParamParent() != nullptr;
  786. } else {
  787. KnownDependent = CurScope->getTemplateParamParent() != nullptr;
  788. }
  789. // Determine the signature of the call operator.
  790. TypeSourceInfo *MethodTyInfo;
  791. bool ExplicitParams = true;
  792. bool ExplicitResultType = true;
  793. bool ContainsUnexpandedParameterPack = false;
  794. SourceLocation EndLoc;
  795. SmallVector<ParmVarDecl *, 8> Params;
  796. if (ParamInfo.getNumTypeObjects() == 0) {
  797. // C++11 [expr.prim.lambda]p4:
  798. // If a lambda-expression does not include a lambda-declarator, it is as
  799. // if the lambda-declarator were ().
  800. FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
  801. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  802. EPI.HasTrailingReturn = true;
  803. EPI.TypeQuals.addConst();
  804. // C++1y [expr.prim.lambda]:
  805. // The lambda return type is 'auto', which is replaced by the
  806. // trailing-return type if provided and/or deduced from 'return'
  807. // statements
  808. // We don't do this before C++1y, because we don't support deduced return
  809. // types there.
  810. QualType DefaultTypeForNoTrailingReturn =
  811. getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
  812. : Context.DependentTy;
  813. QualType MethodTy =
  814. Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
  815. MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
  816. ExplicitParams = false;
  817. ExplicitResultType = false;
  818. EndLoc = Intro.Range.getEnd();
  819. } else {
  820. assert(ParamInfo.isFunctionDeclarator() &&
  821. "lambda-declarator is a function");
  822. DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
  823. // C++11 [expr.prim.lambda]p5:
  824. // This function call operator is declared const (9.3.1) if and only if
  825. // the lambda-expression's parameter-declaration-clause is not followed
  826. // by mutable. It is neither virtual nor declared volatile. [...]
  827. if (!FTI.hasMutableQualifier()) {
  828. FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
  829. SourceLocation());
  830. }
  831. MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
  832. assert(MethodTyInfo && "no type from lambda-declarator");
  833. EndLoc = ParamInfo.getSourceRange().getEnd();
  834. ExplicitResultType = FTI.hasTrailingReturnType();
  835. if (FTIHasNonVoidParameters(FTI)) {
  836. Params.reserve(FTI.NumParams);
  837. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
  838. Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
  839. }
  840. // Check for unexpanded parameter packs in the method type.
  841. if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
  842. DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
  843. UPPC_DeclarationType);
  844. }
  845. CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
  846. KnownDependent, Intro.Default);
  847. CXXMethodDecl *Method =
  848. startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
  849. ParamInfo.getDeclSpec().getConstexprSpecifier());
  850. if (ExplicitParams)
  851. CheckCXXDefaultArguments(Method);
  852. // This represents the function body for the lambda function, check if we
  853. // have to apply optnone due to a pragma.
  854. AddRangeBasedOptnone(Method);
  855. // code_seg attribute on lambda apply to the method.
  856. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  857. Method->addAttr(A);
  858. // Attributes on the lambda apply to the method.
  859. ProcessDeclAttributes(CurScope, Method, ParamInfo);
  860. // CUDA lambdas get implicit attributes based on the scope in which they're
  861. // declared.
  862. if (getLangOpts().CUDA)
  863. CUDASetLambdaAttrs(Method);
  864. // Introduce the function call operator as the current declaration context.
  865. PushDeclContext(CurScope, Method);
  866. // Build the lambda scope.
  867. buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
  868. ExplicitParams, ExplicitResultType, !Method->isConst());
  869. // C++11 [expr.prim.lambda]p9:
  870. // A lambda-expression whose smallest enclosing scope is a block scope is a
  871. // local lambda expression; any other lambda expression shall not have a
  872. // capture-default or simple-capture in its lambda-introducer.
  873. //
  874. // For simple-captures, this is covered by the check below that any named
  875. // entity is a variable that can be captured.
  876. //
  877. // For DR1632, we also allow a capture-default in any context where we can
  878. // odr-use 'this' (in particular, in a default initializer for a non-static
  879. // data member).
  880. if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
  881. (getCurrentThisType().isNull() ||
  882. CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
  883. /*BuildAndDiagnose*/false)))
  884. Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
  885. // Distinct capture names, for diagnostics.
  886. llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
  887. // Handle explicit captures.
  888. SourceLocation PrevCaptureLoc
  889. = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
  890. for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
  891. PrevCaptureLoc = C->Loc, ++C) {
  892. if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
  893. if (C->Kind == LCK_StarThis)
  894. Diag(C->Loc, !getLangOpts().CPlusPlus17
  895. ? diag::ext_star_this_lambda_capture_cxx17
  896. : diag::warn_cxx14_compat_star_this_lambda_capture);
  897. // C++11 [expr.prim.lambda]p8:
  898. // An identifier or this shall not appear more than once in a
  899. // lambda-capture.
  900. if (LSI->isCXXThisCaptured()) {
  901. Diag(C->Loc, diag::err_capture_more_than_once)
  902. << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
  903. << FixItHint::CreateRemoval(
  904. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  905. continue;
  906. }
  907. // C++2a [expr.prim.lambda]p8:
  908. // If a lambda-capture includes a capture-default that is =,
  909. // each simple-capture of that lambda-capture shall be of the form
  910. // "&identifier", "this", or "* this". [ Note: The form [&,this] is
  911. // redundant but accepted for compatibility with ISO C++14. --end note ]
  912. if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
  913. Diag(C->Loc, !getLangOpts().CPlusPlus2a
  914. ? diag::ext_equals_this_lambda_capture_cxx2a
  915. : diag::warn_cxx17_compat_equals_this_lambda_capture);
  916. // C++11 [expr.prim.lambda]p12:
  917. // If this is captured by a local lambda expression, its nearest
  918. // enclosing function shall be a non-static member function.
  919. QualType ThisCaptureType = getCurrentThisType();
  920. if (ThisCaptureType.isNull()) {
  921. Diag(C->Loc, diag::err_this_capture) << true;
  922. continue;
  923. }
  924. CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
  925. /*FunctionScopeIndexToStopAtPtr*/ nullptr,
  926. C->Kind == LCK_StarThis);
  927. if (!LSI->Captures.empty())
  928. LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
  929. continue;
  930. }
  931. assert(C->Id && "missing identifier for capture");
  932. if (C->Init.isInvalid())
  933. continue;
  934. VarDecl *Var = nullptr;
  935. if (C->Init.isUsable()) {
  936. Diag(C->Loc, getLangOpts().CPlusPlus14
  937. ? diag::warn_cxx11_compat_init_capture
  938. : diag::ext_init_capture);
  939. // If the initializer expression is usable, but the InitCaptureType
  940. // is not, then an error has occurred - so ignore the capture for now.
  941. // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
  942. // FIXME: we should create the init capture variable and mark it invalid
  943. // in this case.
  944. if (C->InitCaptureType.get().isNull())
  945. continue;
  946. if (C->Init.get()->containsUnexpandedParameterPack() &&
  947. !C->InitCaptureType.get()->getAs<PackExpansionType>())
  948. DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
  949. unsigned InitStyle;
  950. switch (C->InitKind) {
  951. case LambdaCaptureInitKind::NoInit:
  952. llvm_unreachable("not an init-capture?");
  953. case LambdaCaptureInitKind::CopyInit:
  954. InitStyle = VarDecl::CInit;
  955. break;
  956. case LambdaCaptureInitKind::DirectInit:
  957. InitStyle = VarDecl::CallInit;
  958. break;
  959. case LambdaCaptureInitKind::ListInit:
  960. InitStyle = VarDecl::ListInit;
  961. break;
  962. }
  963. Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
  964. C->EllipsisLoc, C->Id, InitStyle,
  965. C->Init.get());
  966. // C++1y [expr.prim.lambda]p11:
  967. // An init-capture behaves as if it declares and explicitly
  968. // captures a variable [...] whose declarative region is the
  969. // lambda-expression's compound-statement
  970. if (Var)
  971. PushOnScopeChains(Var, CurScope, false);
  972. } else {
  973. assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
  974. "init capture has valid but null init?");
  975. // C++11 [expr.prim.lambda]p8:
  976. // If a lambda-capture includes a capture-default that is &, the
  977. // identifiers in the lambda-capture shall not be preceded by &.
  978. // If a lambda-capture includes a capture-default that is =, [...]
  979. // each identifier it contains shall be preceded by &.
  980. if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
  981. Diag(C->Loc, diag::err_reference_capture_with_reference_default)
  982. << FixItHint::CreateRemoval(
  983. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  984. continue;
  985. } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
  986. Diag(C->Loc, diag::err_copy_capture_with_copy_default)
  987. << FixItHint::CreateRemoval(
  988. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  989. continue;
  990. }
  991. // C++11 [expr.prim.lambda]p10:
  992. // The identifiers in a capture-list are looked up using the usual
  993. // rules for unqualified name lookup (3.4.1)
  994. DeclarationNameInfo Name(C->Id, C->Loc);
  995. LookupResult R(*this, Name, LookupOrdinaryName);
  996. LookupName(R, CurScope);
  997. if (R.isAmbiguous())
  998. continue;
  999. if (R.empty()) {
  1000. // FIXME: Disable corrections that would add qualification?
  1001. CXXScopeSpec ScopeSpec;
  1002. DeclFilterCCC<VarDecl> Validator{};
  1003. if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
  1004. continue;
  1005. }
  1006. Var = R.getAsSingle<VarDecl>();
  1007. if (Var && DiagnoseUseOfDecl(Var, C->Loc))
  1008. continue;
  1009. }
  1010. // C++11 [expr.prim.lambda]p8:
  1011. // An identifier or this shall not appear more than once in a
  1012. // lambda-capture.
  1013. if (!CaptureNames.insert(C->Id).second) {
  1014. if (Var && LSI->isCaptured(Var)) {
  1015. Diag(C->Loc, diag::err_capture_more_than_once)
  1016. << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
  1017. << FixItHint::CreateRemoval(
  1018. SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
  1019. } else
  1020. // Previous capture captured something different (one or both was
  1021. // an init-cpature): no fixit.
  1022. Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
  1023. continue;
  1024. }
  1025. // C++11 [expr.prim.lambda]p10:
  1026. // [...] each such lookup shall find a variable with automatic storage
  1027. // duration declared in the reaching scope of the local lambda expression.
  1028. // Note that the 'reaching scope' check happens in tryCaptureVariable().
  1029. if (!Var) {
  1030. Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
  1031. continue;
  1032. }
  1033. // Ignore invalid decls; they'll just confuse the code later.
  1034. if (Var->isInvalidDecl())
  1035. continue;
  1036. if (!Var->hasLocalStorage()) {
  1037. Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
  1038. Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
  1039. continue;
  1040. }
  1041. // C++11 [expr.prim.lambda]p23:
  1042. // A capture followed by an ellipsis is a pack expansion (14.5.3).
  1043. SourceLocation EllipsisLoc;
  1044. if (C->EllipsisLoc.isValid()) {
  1045. if (Var->isParameterPack()) {
  1046. EllipsisLoc = C->EllipsisLoc;
  1047. } else {
  1048. Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1049. << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
  1050. : SourceRange(C->Loc));
  1051. // Just ignore the ellipsis.
  1052. }
  1053. } else if (Var->isParameterPack()) {
  1054. ContainsUnexpandedParameterPack = true;
  1055. }
  1056. if (C->Init.isUsable()) {
  1057. addInitCapture(LSI, Var);
  1058. } else {
  1059. TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
  1060. TryCapture_ExplicitByVal;
  1061. tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
  1062. }
  1063. if (!LSI->Captures.empty())
  1064. LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
  1065. }
  1066. finishLambdaExplicitCaptures(LSI);
  1067. LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
  1068. // Add lambda parameters into scope.
  1069. addLambdaParameters(Intro.Captures, Method, CurScope);
  1070. // Enter a new evaluation context to insulate the lambda from any
  1071. // cleanups from the enclosing full-expression.
  1072. PushExpressionEvaluationContext(
  1073. ExpressionEvaluationContext::PotentiallyEvaluated);
  1074. }
  1075. void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
  1076. bool IsInstantiation) {
  1077. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
  1078. // Leave the expression-evaluation context.
  1079. DiscardCleanupsInEvaluationContext();
  1080. PopExpressionEvaluationContext();
  1081. // Leave the context of the lambda.
  1082. if (!IsInstantiation)
  1083. PopDeclContext();
  1084. // Finalize the lambda.
  1085. CXXRecordDecl *Class = LSI->Lambda;
  1086. Class->setInvalidDecl();
  1087. SmallVector<Decl*, 4> Fields(Class->fields());
  1088. ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
  1089. SourceLocation(), ParsedAttributesView());
  1090. CheckCompletedCXXClass(Class);
  1091. PopFunctionScopeInfo();
  1092. }
  1093. QualType Sema::getLambdaConversionFunctionResultType(
  1094. const FunctionProtoType *CallOpProto) {
  1095. // The function type inside the pointer type is the same as the call
  1096. // operator with some tweaks. The calling convention is the default free
  1097. // function convention, and the type qualifications are lost.
  1098. const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
  1099. CallOpProto->getExtProtoInfo();
  1100. FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
  1101. CallingConv CC = Context.getDefaultCallingConvention(
  1102. CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
  1103. InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
  1104. InvokerExtInfo.TypeQuals = Qualifiers();
  1105. assert(InvokerExtInfo.RefQualifier == RQ_None &&
  1106. "Lambda's call operator should not have a reference qualifier");
  1107. return Context.getFunctionType(CallOpProto->getReturnType(),
  1108. CallOpProto->getParamTypes(), InvokerExtInfo);
  1109. }
  1110. /// Add a lambda's conversion to function pointer, as described in
  1111. /// C++11 [expr.prim.lambda]p6.
  1112. static void addFunctionPointerConversion(Sema &S,
  1113. SourceRange IntroducerRange,
  1114. CXXRecordDecl *Class,
  1115. CXXMethodDecl *CallOperator) {
  1116. // This conversion is explicitly disabled if the lambda's function has
  1117. // pass_object_size attributes on any of its parameters.
  1118. auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
  1119. return P->hasAttr<PassObjectSizeAttr>();
  1120. };
  1121. if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
  1122. return;
  1123. // Add the conversion to function pointer.
  1124. QualType InvokerFunctionTy = S.getLambdaConversionFunctionResultType(
  1125. CallOperator->getType()->castAs<FunctionProtoType>());
  1126. QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
  1127. // Create the type of the conversion function.
  1128. FunctionProtoType::ExtProtoInfo ConvExtInfo(
  1129. S.Context.getDefaultCallingConvention(
  1130. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  1131. // The conversion function is always const and noexcept.
  1132. ConvExtInfo.TypeQuals = Qualifiers();
  1133. ConvExtInfo.TypeQuals.addConst();
  1134. ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
  1135. QualType ConvTy =
  1136. S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
  1137. SourceLocation Loc = IntroducerRange.getBegin();
  1138. DeclarationName ConversionName
  1139. = S.Context.DeclarationNames.getCXXConversionFunctionName(
  1140. S.Context.getCanonicalType(PtrToFunctionTy));
  1141. DeclarationNameLoc ConvNameLoc;
  1142. // Construct a TypeSourceInfo for the conversion function, and wire
  1143. // all the parameters appropriately for the FunctionProtoTypeLoc
  1144. // so that everything works during transformation/instantiation of
  1145. // generic lambdas.
  1146. // The main reason for wiring up the parameters of the conversion
  1147. // function with that of the call operator is so that constructs
  1148. // like the following work:
  1149. // auto L = [](auto b) { <-- 1
  1150. // return [](auto a) -> decltype(a) { <-- 2
  1151. // return a;
  1152. // };
  1153. // };
  1154. // int (*fp)(int) = L(5);
  1155. // Because the trailing return type can contain DeclRefExprs that refer
  1156. // to the original call operator's variables, we hijack the call
  1157. // operators ParmVarDecls below.
  1158. TypeSourceInfo *ConvNamePtrToFunctionTSI =
  1159. S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
  1160. ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
  1161. // The conversion function is a conversion to a pointer-to-function.
  1162. TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
  1163. FunctionProtoTypeLoc ConvTL =
  1164. ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  1165. // Get the result of the conversion function which is a pointer-to-function.
  1166. PointerTypeLoc PtrToFunctionTL =
  1167. ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
  1168. // Do the same for the TypeSourceInfo that is used to name the conversion
  1169. // operator.
  1170. PointerTypeLoc ConvNamePtrToFunctionTL =
  1171. ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
  1172. // Get the underlying function types that the conversion function will
  1173. // be converting to (should match the type of the call operator).
  1174. FunctionProtoTypeLoc CallOpConvTL =
  1175. PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
  1176. FunctionProtoTypeLoc CallOpConvNameTL =
  1177. ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
  1178. // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
  1179. // These parameter's are essentially used to transform the name and
  1180. // the type of the conversion operator. By using the same parameters
  1181. // as the call operator's we don't have to fix any back references that
  1182. // the trailing return type of the call operator's uses (such as
  1183. // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
  1184. // - we can simply use the return type of the call operator, and
  1185. // everything should work.
  1186. SmallVector<ParmVarDecl *, 4> InvokerParams;
  1187. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
  1188. ParmVarDecl *From = CallOperator->getParamDecl(I);
  1189. InvokerParams.push_back(ParmVarDecl::Create(
  1190. S.Context,
  1191. // Temporarily add to the TU. This is set to the invoker below.
  1192. S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
  1193. From->getLocation(), From->getIdentifier(), From->getType(),
  1194. From->getTypeSourceInfo(), From->getStorageClass(),
  1195. /*DefArg=*/nullptr));
  1196. CallOpConvTL.setParam(I, From);
  1197. CallOpConvNameTL.setParam(I, From);
  1198. }
  1199. CXXConversionDecl *Conversion = CXXConversionDecl::Create(
  1200. S.Context, Class, Loc,
  1201. DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
  1202. /*isInline=*/true, ExplicitSpecifier(),
  1203. S.getLangOpts().CPlusPlus17 ? CSK_constexpr : CSK_unspecified,
  1204. CallOperator->getBody()->getEndLoc());
  1205. Conversion->setAccess(AS_public);
  1206. Conversion->setImplicit(true);
  1207. if (Class->isGenericLambda()) {
  1208. // Create a template version of the conversion operator, using the template
  1209. // parameter list of the function call operator.
  1210. FunctionTemplateDecl *TemplateCallOperator =
  1211. CallOperator->getDescribedFunctionTemplate();
  1212. FunctionTemplateDecl *ConversionTemplate =
  1213. FunctionTemplateDecl::Create(S.Context, Class,
  1214. Loc, ConversionName,
  1215. TemplateCallOperator->getTemplateParameters(),
  1216. Conversion);
  1217. ConversionTemplate->setAccess(AS_public);
  1218. ConversionTemplate->setImplicit(true);
  1219. Conversion->setDescribedFunctionTemplate(ConversionTemplate);
  1220. Class->addDecl(ConversionTemplate);
  1221. } else
  1222. Class->addDecl(Conversion);
  1223. // Add a non-static member function that will be the result of
  1224. // the conversion with a certain unique ID.
  1225. DeclarationName InvokerName = &S.Context.Idents.get(
  1226. getLambdaStaticInvokerName());
  1227. // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
  1228. // we should get a prebuilt TrivialTypeSourceInfo from Context
  1229. // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
  1230. // then rewire the parameters accordingly, by hoisting up the InvokeParams
  1231. // loop below and then use its Params to set Invoke->setParams(...) below.
  1232. // This would avoid the 'const' qualifier of the calloperator from
  1233. // contaminating the type of the invoker, which is currently adjusted
  1234. // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
  1235. // trailing return type of the invoker would require a visitor to rebuild
  1236. // the trailing return type and adjusting all back DeclRefExpr's to refer
  1237. // to the new static invoker parameters - not the call operator's.
  1238. CXXMethodDecl *Invoke = CXXMethodDecl::Create(
  1239. S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
  1240. InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
  1241. /*isInline=*/true, CSK_unspecified, CallOperator->getBody()->getEndLoc());
  1242. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
  1243. InvokerParams[I]->setOwningFunction(Invoke);
  1244. Invoke->setParams(InvokerParams);
  1245. Invoke->setAccess(AS_private);
  1246. Invoke->setImplicit(true);
  1247. if (Class->isGenericLambda()) {
  1248. FunctionTemplateDecl *TemplateCallOperator =
  1249. CallOperator->getDescribedFunctionTemplate();
  1250. FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
  1251. S.Context, Class, Loc, InvokerName,
  1252. TemplateCallOperator->getTemplateParameters(),
  1253. Invoke);
  1254. StaticInvokerTemplate->setAccess(AS_private);
  1255. StaticInvokerTemplate->setImplicit(true);
  1256. Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
  1257. Class->addDecl(StaticInvokerTemplate);
  1258. } else
  1259. Class->addDecl(Invoke);
  1260. }
  1261. /// Add a lambda's conversion to block pointer.
  1262. static void addBlockPointerConversion(Sema &S,
  1263. SourceRange IntroducerRange,
  1264. CXXRecordDecl *Class,
  1265. CXXMethodDecl *CallOperator) {
  1266. QualType FunctionTy = S.getLambdaConversionFunctionResultType(
  1267. CallOperator->getType()->castAs<FunctionProtoType>());
  1268. QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
  1269. FunctionProtoType::ExtProtoInfo ConversionEPI(
  1270. S.Context.getDefaultCallingConvention(
  1271. /*IsVariadic=*/false, /*IsCXXMethod=*/true));
  1272. ConversionEPI.TypeQuals = Qualifiers();
  1273. ConversionEPI.TypeQuals.addConst();
  1274. QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
  1275. SourceLocation Loc = IntroducerRange.getBegin();
  1276. DeclarationName Name
  1277. = S.Context.DeclarationNames.getCXXConversionFunctionName(
  1278. S.Context.getCanonicalType(BlockPtrTy));
  1279. DeclarationNameLoc NameLoc;
  1280. NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
  1281. CXXConversionDecl *Conversion = CXXConversionDecl::Create(
  1282. S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
  1283. S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
  1284. /*isInline=*/true, ExplicitSpecifier(), CSK_unspecified,
  1285. CallOperator->getBody()->getEndLoc());
  1286. Conversion->setAccess(AS_public);
  1287. Conversion->setImplicit(true);
  1288. Class->addDecl(Conversion);
  1289. }
  1290. ExprResult Sema::BuildCaptureInit(const Capture &Cap,
  1291. SourceLocation ImplicitCaptureLoc,
  1292. bool IsOpenMPMapping) {
  1293. // VLA captures don't have a stored initialization expression.
  1294. if (Cap.isVLATypeCapture())
  1295. return ExprResult();
  1296. // An init-capture is initialized directly from its stored initializer.
  1297. if (Cap.isInitCapture())
  1298. return Cap.getVariable()->getInit();
  1299. // For anything else, build an initialization expression. For an implicit
  1300. // capture, the capture notionally happens at the capture-default, so use
  1301. // that location here.
  1302. SourceLocation Loc =
  1303. ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
  1304. // C++11 [expr.prim.lambda]p21:
  1305. // When the lambda-expression is evaluated, the entities that
  1306. // are captured by copy are used to direct-initialize each
  1307. // corresponding non-static data member of the resulting closure
  1308. // object. (For array members, the array elements are
  1309. // direct-initialized in increasing subscript order.) These
  1310. // initializations are performed in the (unspecified) order in
  1311. // which the non-static data members are declared.
  1312. // C++ [expr.prim.lambda]p12:
  1313. // An entity captured by a lambda-expression is odr-used (3.2) in
  1314. // the scope containing the lambda-expression.
  1315. ExprResult Init;
  1316. IdentifierInfo *Name = nullptr;
  1317. if (Cap.isThisCapture()) {
  1318. QualType ThisTy = getCurrentThisType();
  1319. Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
  1320. if (Cap.isCopyCapture())
  1321. Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
  1322. else
  1323. Init = This;
  1324. } else {
  1325. assert(Cap.isVariableCapture() && "unknown kind of capture");
  1326. VarDecl *Var = Cap.getVariable();
  1327. Name = Var->getIdentifier();
  1328. Init = BuildDeclarationNameExpr(
  1329. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  1330. }
  1331. // In OpenMP, the capture kind doesn't actually describe how to capture:
  1332. // variables are "mapped" onto the device in a process that does not formally
  1333. // make a copy, even for a "copy capture".
  1334. if (IsOpenMPMapping)
  1335. return Init;
  1336. if (Init.isInvalid())
  1337. return ExprError();
  1338. Expr *InitExpr = Init.get();
  1339. InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
  1340. Name, Cap.getCaptureType(), Loc);
  1341. InitializationKind InitKind =
  1342. InitializationKind::CreateDirect(Loc, Loc, Loc);
  1343. InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
  1344. return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
  1345. }
  1346. ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
  1347. Scope *CurScope) {
  1348. LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
  1349. ActOnFinishFunctionBody(LSI.CallOperator, Body);
  1350. return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
  1351. }
  1352. static LambdaCaptureDefault
  1353. mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
  1354. switch (ICS) {
  1355. case CapturingScopeInfo::ImpCap_None:
  1356. return LCD_None;
  1357. case CapturingScopeInfo::ImpCap_LambdaByval:
  1358. return LCD_ByCopy;
  1359. case CapturingScopeInfo::ImpCap_CapturedRegion:
  1360. case CapturingScopeInfo::ImpCap_LambdaByref:
  1361. return LCD_ByRef;
  1362. case CapturingScopeInfo::ImpCap_Block:
  1363. llvm_unreachable("block capture in lambda");
  1364. }
  1365. llvm_unreachable("Unknown implicit capture style");
  1366. }
  1367. bool Sema::CaptureHasSideEffects(const Capture &From) {
  1368. if (From.isInitCapture()) {
  1369. Expr *Init = From.getVariable()->getInit();
  1370. if (Init && Init->HasSideEffects(Context))
  1371. return true;
  1372. }
  1373. if (!From.isCopyCapture())
  1374. return false;
  1375. const QualType T = From.isThisCapture()
  1376. ? getCurrentThisType()->getPointeeType()
  1377. : From.getCaptureType();
  1378. if (T.isVolatileQualified())
  1379. return true;
  1380. const Type *BaseT = T->getBaseElementTypeUnsafe();
  1381. if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
  1382. return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
  1383. !RD->hasTrivialDestructor();
  1384. return false;
  1385. }
  1386. bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
  1387. const Capture &From) {
  1388. if (CaptureHasSideEffects(From))
  1389. return false;
  1390. if (From.isVLATypeCapture())
  1391. return false;
  1392. auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
  1393. if (From.isThisCapture())
  1394. diag << "'this'";
  1395. else
  1396. diag << From.getVariable();
  1397. diag << From.isNonODRUsed();
  1398. diag << FixItHint::CreateRemoval(CaptureRange);
  1399. return true;
  1400. }
  1401. /// Create a field within the lambda class or captured statement record for the
  1402. /// given capture.
  1403. FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
  1404. const sema::Capture &Capture) {
  1405. SourceLocation Loc = Capture.getLocation();
  1406. QualType FieldType = Capture.getCaptureType();
  1407. TypeSourceInfo *TSI = nullptr;
  1408. if (Capture.isVariableCapture()) {
  1409. auto *Var = Capture.getVariable();
  1410. if (Var->isInitCapture())
  1411. TSI = Capture.getVariable()->getTypeSourceInfo();
  1412. }
  1413. // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
  1414. // appropriate, at least for an implicit capture.
  1415. if (!TSI)
  1416. TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
  1417. // Build the non-static data member.
  1418. FieldDecl *Field =
  1419. FieldDecl::Create(Context, RD, Loc, Loc, nullptr, FieldType, TSI, nullptr,
  1420. false, ICIS_NoInit);
  1421. // If the variable being captured has an invalid type, mark the class as
  1422. // invalid as well.
  1423. if (!FieldType->isDependentType()) {
  1424. if (RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
  1425. RD->setInvalidDecl();
  1426. Field->setInvalidDecl();
  1427. } else {
  1428. NamedDecl *Def;
  1429. FieldType->isIncompleteType(&Def);
  1430. if (Def && Def->isInvalidDecl()) {
  1431. RD->setInvalidDecl();
  1432. Field->setInvalidDecl();
  1433. }
  1434. }
  1435. }
  1436. Field->setImplicit(true);
  1437. Field->setAccess(AS_private);
  1438. RD->addDecl(Field);
  1439. if (Capture.isVLATypeCapture())
  1440. Field->setCapturedVLAType(Capture.getCapturedVLAType());
  1441. return Field;
  1442. }
  1443. ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
  1444. LambdaScopeInfo *LSI) {
  1445. // Collect information from the lambda scope.
  1446. SmallVector<LambdaCapture, 4> Captures;
  1447. SmallVector<Expr *, 4> CaptureInits;
  1448. SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
  1449. LambdaCaptureDefault CaptureDefault =
  1450. mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
  1451. CXXRecordDecl *Class;
  1452. CXXMethodDecl *CallOperator;
  1453. SourceRange IntroducerRange;
  1454. bool ExplicitParams;
  1455. bool ExplicitResultType;
  1456. CleanupInfo LambdaCleanup;
  1457. bool ContainsUnexpandedParameterPack;
  1458. bool IsGenericLambda;
  1459. {
  1460. CallOperator = LSI->CallOperator;
  1461. Class = LSI->Lambda;
  1462. IntroducerRange = LSI->IntroducerRange;
  1463. ExplicitParams = LSI->ExplicitParams;
  1464. ExplicitResultType = !LSI->HasImplicitReturnType;
  1465. LambdaCleanup = LSI->Cleanup;
  1466. ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
  1467. IsGenericLambda = Class->isGenericLambda();
  1468. CallOperator->setLexicalDeclContext(Class);
  1469. Decl *TemplateOrNonTemplateCallOperatorDecl =
  1470. CallOperator->getDescribedFunctionTemplate()
  1471. ? CallOperator->getDescribedFunctionTemplate()
  1472. : cast<Decl>(CallOperator);
  1473. TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
  1474. Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
  1475. PopExpressionEvaluationContext();
  1476. // True if the current capture has a used capture or default before it.
  1477. bool CurHasPreviousCapture = CaptureDefault != LCD_None;
  1478. SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
  1479. CaptureDefaultLoc : IntroducerRange.getBegin();
  1480. for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
  1481. const Capture &From = LSI->Captures[I];
  1482. if (From.isInvalid())
  1483. return ExprError();
  1484. assert(!From.isBlockCapture() && "Cannot capture __block variables");
  1485. bool IsImplicit = I >= LSI->NumExplicitCaptures;
  1486. SourceLocation ImplicitCaptureLoc =
  1487. IsImplicit ? CaptureDefaultLoc : SourceLocation();
  1488. // Use source ranges of explicit captures for fixits where available.
  1489. SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
  1490. // Warn about unused explicit captures.
  1491. bool IsCaptureUsed = true;
  1492. if (!CurContext->isDependentContext() && !IsImplicit &&
  1493. !From.isODRUsed()) {
  1494. // Initialized captures that are non-ODR used may not be eliminated.
  1495. // FIXME: Where did the IsGenericLambda here come from?
  1496. bool NonODRUsedInitCapture =
  1497. IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
  1498. if (!NonODRUsedInitCapture) {
  1499. bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
  1500. SourceRange FixItRange;
  1501. if (CaptureRange.isValid()) {
  1502. if (!CurHasPreviousCapture && !IsLast) {
  1503. // If there are no captures preceding this capture, remove the
  1504. // following comma.
  1505. FixItRange = SourceRange(CaptureRange.getBegin(),
  1506. getLocForEndOfToken(CaptureRange.getEnd()));
  1507. } else {
  1508. // Otherwise, remove the comma since the last used capture.
  1509. FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
  1510. CaptureRange.getEnd());
  1511. }
  1512. }
  1513. IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
  1514. }
  1515. }
  1516. if (CaptureRange.isValid()) {
  1517. CurHasPreviousCapture |= IsCaptureUsed;
  1518. PrevCaptureLoc = CaptureRange.getEnd();
  1519. }
  1520. // Map the capture to our AST representation.
  1521. LambdaCapture Capture = [&] {
  1522. if (From.isThisCapture()) {
  1523. // Capturing 'this' implicitly with a default of '[=]' is deprecated,
  1524. // because it results in a reference capture. Don't warn prior to
  1525. // C++2a; there's nothing that can be done about it before then.
  1526. if (getLangOpts().CPlusPlus2a && IsImplicit &&
  1527. CaptureDefault == LCD_ByCopy) {
  1528. Diag(From.getLocation(), diag::warn_deprecated_this_capture);
  1529. Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
  1530. << FixItHint::CreateInsertion(
  1531. getLocForEndOfToken(CaptureDefaultLoc), ", this");
  1532. }
  1533. return LambdaCapture(From.getLocation(), IsImplicit,
  1534. From.isCopyCapture() ? LCK_StarThis : LCK_This);
  1535. } else if (From.isVLATypeCapture()) {
  1536. return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
  1537. } else {
  1538. assert(From.isVariableCapture() && "unknown kind of capture");
  1539. VarDecl *Var = From.getVariable();
  1540. LambdaCaptureKind Kind =
  1541. From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
  1542. return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
  1543. From.getEllipsisLoc());
  1544. }
  1545. }();
  1546. // Form the initializer for the capture field.
  1547. ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
  1548. // FIXME: Skip this capture if the capture is not used, the initializer
  1549. // has no side-effects, the type of the capture is trivial, and the
  1550. // lambda is not externally visible.
  1551. // Add a FieldDecl for the capture and form its initializer.
  1552. BuildCaptureField(Class, From);
  1553. Captures.push_back(Capture);
  1554. CaptureInits.push_back(Init.get());
  1555. }
  1556. // C++11 [expr.prim.lambda]p6:
  1557. // The closure type for a lambda-expression with no lambda-capture
  1558. // has a public non-virtual non-explicit const conversion function
  1559. // to pointer to function having the same parameter and return
  1560. // types as the closure type's function call operator.
  1561. if (Captures.empty() && CaptureDefault == LCD_None)
  1562. addFunctionPointerConversion(*this, IntroducerRange, Class,
  1563. CallOperator);
  1564. // Objective-C++:
  1565. // The closure type for a lambda-expression has a public non-virtual
  1566. // non-explicit const conversion function to a block pointer having the
  1567. // same parameter and return types as the closure type's function call
  1568. // operator.
  1569. // FIXME: Fix generic lambda to block conversions.
  1570. if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
  1571. addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
  1572. // Finalize the lambda class.
  1573. SmallVector<Decl*, 4> Fields(Class->fields());
  1574. ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
  1575. SourceLocation(), ParsedAttributesView());
  1576. CheckCompletedCXXClass(Class);
  1577. }
  1578. Cleanup.mergeFrom(LambdaCleanup);
  1579. LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
  1580. CaptureDefault, CaptureDefaultLoc,
  1581. Captures,
  1582. ExplicitParams, ExplicitResultType,
  1583. CaptureInits, EndLoc,
  1584. ContainsUnexpandedParameterPack);
  1585. // If the lambda expression's call operator is not explicitly marked constexpr
  1586. // and we are not in a dependent context, analyze the call operator to infer
  1587. // its constexpr-ness, suppressing diagnostics while doing so.
  1588. if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
  1589. !CallOperator->isConstexpr() &&
  1590. !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
  1591. !Class->getDeclContext()->isDependentContext()) {
  1592. CallOperator->setConstexprKind(
  1593. CheckConstexprFunctionDefinition(CallOperator,
  1594. CheckConstexprKind::CheckValid)
  1595. ? CSK_constexpr
  1596. : CSK_unspecified);
  1597. }
  1598. // Emit delayed shadowing warnings now that the full capture list is known.
  1599. DiagnoseShadowingLambdaDecls(LSI);
  1600. if (!CurContext->isDependentContext()) {
  1601. switch (ExprEvalContexts.back().Context) {
  1602. // C++11 [expr.prim.lambda]p2:
  1603. // A lambda-expression shall not appear in an unevaluated operand
  1604. // (Clause 5).
  1605. case ExpressionEvaluationContext::Unevaluated:
  1606. case ExpressionEvaluationContext::UnevaluatedList:
  1607. case ExpressionEvaluationContext::UnevaluatedAbstract:
  1608. // C++1y [expr.const]p2:
  1609. // A conditional-expression e is a core constant expression unless the
  1610. // evaluation of e, following the rules of the abstract machine, would
  1611. // evaluate [...] a lambda-expression.
  1612. //
  1613. // This is technically incorrect, there are some constant evaluated contexts
  1614. // where this should be allowed. We should probably fix this when DR1607 is
  1615. // ratified, it lays out the exact set of conditions where we shouldn't
  1616. // allow a lambda-expression.
  1617. case ExpressionEvaluationContext::ConstantEvaluated:
  1618. // We don't actually diagnose this case immediately, because we
  1619. // could be within a context where we might find out later that
  1620. // the expression is potentially evaluated (e.g., for typeid).
  1621. ExprEvalContexts.back().Lambdas.push_back(Lambda);
  1622. break;
  1623. case ExpressionEvaluationContext::DiscardedStatement:
  1624. case ExpressionEvaluationContext::PotentiallyEvaluated:
  1625. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  1626. break;
  1627. }
  1628. }
  1629. return MaybeBindToTemporary(Lambda);
  1630. }
  1631. ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
  1632. SourceLocation ConvLocation,
  1633. CXXConversionDecl *Conv,
  1634. Expr *Src) {
  1635. // Make sure that the lambda call operator is marked used.
  1636. CXXRecordDecl *Lambda = Conv->getParent();
  1637. CXXMethodDecl *CallOperator
  1638. = cast<CXXMethodDecl>(
  1639. Lambda->lookup(
  1640. Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
  1641. CallOperator->setReferenced();
  1642. CallOperator->markUsed(Context);
  1643. ExprResult Init = PerformCopyInitialization(
  1644. InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(),
  1645. /*NRVO=*/false),
  1646. CurrentLocation, Src);
  1647. if (!Init.isInvalid())
  1648. Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  1649. if (Init.isInvalid())
  1650. return ExprError();
  1651. // Create the new block to be returned.
  1652. BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
  1653. // Set the type information.
  1654. Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
  1655. Block->setIsVariadic(CallOperator->isVariadic());
  1656. Block->setBlockMissingReturnType(false);
  1657. // Add parameters.
  1658. SmallVector<ParmVarDecl *, 4> BlockParams;
  1659. for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
  1660. ParmVarDecl *From = CallOperator->getParamDecl(I);
  1661. BlockParams.push_back(ParmVarDecl::Create(
  1662. Context, Block, From->getBeginLoc(), From->getLocation(),
  1663. From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
  1664. From->getStorageClass(),
  1665. /*DefArg=*/nullptr));
  1666. }
  1667. Block->setParams(BlockParams);
  1668. Block->setIsConversionFromLambda(true);
  1669. // Add capture. The capture uses a fake variable, which doesn't correspond
  1670. // to any actual memory location. However, the initializer copy-initializes
  1671. // the lambda object.
  1672. TypeSourceInfo *CapVarTSI =
  1673. Context.getTrivialTypeSourceInfo(Src->getType());
  1674. VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
  1675. ConvLocation, nullptr,
  1676. Src->getType(), CapVarTSI,
  1677. SC_None);
  1678. BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
  1679. /*nested=*/false, /*copy=*/Init.get());
  1680. Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
  1681. // Add a fake function body to the block. IR generation is responsible
  1682. // for filling in the actual body, which cannot be expressed as an AST.
  1683. Block->setBody(new (Context) CompoundStmt(ConvLocation));
  1684. // Create the block literal expression.
  1685. Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
  1686. ExprCleanupObjects.push_back(Block);
  1687. Cleanup.setExprNeedsCleanups(true);
  1688. return BuildBlock;
  1689. }