SemaLambda.cpp 72 KB

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