SemaLambda.cpp 78 KB

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