SemaLambda.cpp revision 7dd900ed308506f9cf1cb72c70db1652f94cab37
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 "clang/Sema/Initialization.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/ScopeInfo.h"
18#include "clang/Sema/SemaInternal.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/AST/ExprCXX.h"
21using namespace clang;
22using namespace sema;
23
24CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
25                                             bool KnownDependent) {
26  DeclContext *DC = CurContext;
27  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
28    DC = DC->getParent();
29
30  // Start constructing the lambda class.
31  CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
32                                                     IntroducerRange.getBegin(),
33                                                     KnownDependent);
34  DC->addDecl(Class);
35
36  return Class;
37}
38
39/// \brief Determine whether the given context is or is enclosed in an inline
40/// function.
41static bool isInInlineFunction(const DeclContext *DC) {
42  while (!DC->isFileContext()) {
43    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
44      if (FD->isInlined())
45        return true;
46
47    DC = DC->getLexicalParent();
48  }
49
50  return false;
51}
52
53CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
54                 SourceRange IntroducerRange,
55                 TypeSourceInfo *MethodType,
56                 SourceLocation EndLoc,
57                 llvm::ArrayRef<ParmVarDecl *> Params,
58                 llvm::Optional<unsigned> ManglingNumber,
59                 Decl *ContextDecl) {
60  // C++11 [expr.prim.lambda]p5:
61  //   The closure type for a lambda-expression has a public inline function
62  //   call operator (13.5.4) whose parameters and return type are described by
63  //   the lambda-expression's parameter-declaration-clause and
64  //   trailing-return-type respectively.
65  DeclarationName MethodName
66    = Context.DeclarationNames.getCXXOperatorName(OO_Call);
67  DeclarationNameLoc MethodNameLoc;
68  MethodNameLoc.CXXOperatorName.BeginOpNameLoc
69    = IntroducerRange.getBegin().getRawEncoding();
70  MethodNameLoc.CXXOperatorName.EndOpNameLoc
71    = IntroducerRange.getEnd().getRawEncoding();
72  CXXMethodDecl *Method
73    = CXXMethodDecl::Create(Context, Class, EndLoc,
74                            DeclarationNameInfo(MethodName,
75                                                IntroducerRange.getBegin(),
76                                                MethodNameLoc),
77                            MethodType->getType(), MethodType,
78                            /*isStatic=*/false,
79                            SC_None,
80                            /*isInline=*/true,
81                            /*isConstExpr=*/false,
82                            EndLoc);
83  Method->setAccess(AS_public);
84
85  // Temporarily set the lexical declaration context to the current
86  // context, so that the Scope stack matches the lexical nesting.
87  Method->setLexicalDeclContext(CurContext);
88
89  // Add parameters.
90  if (!Params.empty()) {
91    Method->setParams(Params);
92    CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
93                             const_cast<ParmVarDecl **>(Params.end()),
94                             /*CheckParameterNames=*/false);
95
96    for (CXXMethodDecl::param_iterator P = Method->param_begin(),
97                                    PEnd = Method->param_end();
98         P != PEnd; ++P)
99      (*P)->setOwningFunction(Method);
100  }
101
102  // If we don't already have a mangling number for this lambda expression,
103  // allocate one now.
104  if (!ManglingNumber) {
105    ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
106
107    enum ContextKind {
108      Normal,
109      DefaultArgument,
110      DataMember,
111      StaticDataMember
112    } Kind = Normal;
113
114    // Default arguments of member function parameters that appear in a class
115    // definition, as well as the initializers of data members, receive special
116    // treatment. Identify them.
117    if (ContextDecl) {
118      if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
119        if (const DeclContext *LexicalDC
120            = Param->getDeclContext()->getLexicalParent())
121          if (LexicalDC->isRecord())
122            Kind = DefaultArgument;
123      } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
124        if (Var->getDeclContext()->isRecord())
125          Kind = StaticDataMember;
126      } else if (isa<FieldDecl>(ContextDecl)) {
127        Kind = DataMember;
128      }
129    }
130
131    switch (Kind) {
132      case Normal:
133        if (CurContext->isDependentContext() || isInInlineFunction(CurContext))
134          ManglingNumber = Context.getLambdaManglingNumber(Method);
135        else
136          ManglingNumber = 0;
137
138        // There is no special context for this lambda.
139        ContextDecl = 0;
140        break;
141
142      case StaticDataMember:
143        if (!CurContext->isDependentContext()) {
144          ManglingNumber = 0;
145          ContextDecl = 0;
146          break;
147        }
148        // Fall through to assign a mangling number.
149
150      case DataMember:
151      case DefaultArgument:
152        ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
153                           .getManglingNumber(Method);
154        break;
155    }
156  }
157
158  Class->setLambdaMangling(*ManglingNumber, ContextDecl);
159  return Method;
160}
161
162LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
163                                        SourceRange IntroducerRange,
164                                        LambdaCaptureDefault CaptureDefault,
165                                        bool ExplicitParams,
166                                        bool ExplicitResultType,
167                                        bool Mutable) {
168  PushLambdaScope(CallOperator->getParent(), CallOperator);
169  LambdaScopeInfo *LSI = getCurLambda();
170  if (CaptureDefault == LCD_ByCopy)
171    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
172  else if (CaptureDefault == LCD_ByRef)
173    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
174  LSI->IntroducerRange = IntroducerRange;
175  LSI->ExplicitParams = ExplicitParams;
176  LSI->Mutable = Mutable;
177
178  if (ExplicitResultType) {
179    LSI->ReturnType = CallOperator->getResultType();
180
181    if (!LSI->ReturnType->isDependentType() &&
182        !LSI->ReturnType->isVoidType()) {
183      if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
184                              diag::err_lambda_incomplete_result)) {
185        // Do nothing.
186      } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
187        Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
188          << LSI->ReturnType;
189      }
190    }
191  } else {
192    LSI->HasImplicitReturnType = true;
193  }
194
195  return LSI;
196}
197
198void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
199  LSI->finishedExplicitCaptures();
200}
201
202void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
203  // Introduce our parameters into the function scope
204  for (unsigned p = 0, NumParams = CallOperator->getNumParams();
205       p < NumParams; ++p) {
206    ParmVarDecl *Param = CallOperator->getParamDecl(p);
207
208    // If this has an identifier, add it to the scope stack.
209    if (CurScope && Param->getIdentifier()) {
210      CheckShadow(CurScope, Param);
211
212      PushOnScopeChains(Param, CurScope);
213    }
214  }
215}
216
217static bool checkReturnValueType(const ASTContext &Ctx, const Expr *E,
218                                 QualType &DeducedType,
219                                 QualType &AlternateType) {
220  // Handle ReturnStmts with no expressions.
221  if (!E) {
222    if (AlternateType.isNull())
223      AlternateType = Ctx.VoidTy;
224
225    return Ctx.hasSameType(DeducedType, Ctx.VoidTy);
226  }
227
228  QualType StrictType = E->getType();
229  QualType LooseType = StrictType;
230
231  // In C, enum constants have the type of their underlying integer type,
232  // not the enum. When inferring block return types, we should allow
233  // the enum type if an enum constant is used, unless the enum is
234  // anonymous (in which case there can be no variables of its type).
235  if (!Ctx.getLangOpts().CPlusPlus) {
236    const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
237    if (DRE) {
238      const Decl *D = DRE->getDecl();
239      if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
240        const EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
241        if (Enum->getDeclName() || Enum->getTypedefNameForAnonDecl())
242          LooseType = Ctx.getTypeDeclType(Enum);
243      }
244    }
245  }
246
247  // Special case for the first return statement we find.
248  // The return type has already been tentatively set, but we might still
249  // have an alternate type we should prefer.
250  if (AlternateType.isNull())
251    AlternateType = LooseType;
252
253  if (Ctx.hasSameType(DeducedType, StrictType)) {
254    // FIXME: The loose type is different when there are constants from two
255    // different enums. We could consider warning here.
256    if (AlternateType != Ctx.DependentTy)
257      if (!Ctx.hasSameType(AlternateType, LooseType))
258        AlternateType = Ctx.VoidTy;
259    return true;
260  }
261
262  if (Ctx.hasSameType(DeducedType, LooseType)) {
263    // Use DependentTy to signal that we're using an alternate type and may
264    // need to add casts somewhere.
265    AlternateType = Ctx.DependentTy;
266    return true;
267  }
268
269  if (Ctx.hasSameType(AlternateType, StrictType) ||
270      Ctx.hasSameType(AlternateType, LooseType)) {
271    DeducedType = AlternateType;
272    // Use DependentTy to signal that we're using an alternate type and may
273    // need to add casts somewhere.
274    AlternateType = Ctx.DependentTy;
275    return true;
276  }
277
278  return false;
279}
280
281void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
282  assert(CSI.HasImplicitReturnType);
283
284  // First case: no return statements, implicit void return type.
285  ASTContext &Ctx = getASTContext();
286  if (CSI.Returns.empty()) {
287    // It's possible there were simply no /valid/ return statements.
288    // In this case, the first one we found may have at least given us a type.
289    if (CSI.ReturnType.isNull())
290      CSI.ReturnType = Ctx.VoidTy;
291    return;
292  }
293
294  // Second case: at least one return statement has dependent type.
295  // Delay type checking until instantiation.
296  assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
297  if (CSI.ReturnType->isDependentType())
298    return;
299
300  // Third case: only one return statement. Don't bother doing extra work!
301  SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
302                                         E = CSI.Returns.end();
303  if (I+1 == E)
304    return;
305
306  // General case: many return statements.
307  // Check that they all have compatible return types.
308  // For now, that means "identical", with an exception for enum constants.
309  // (In C, enum constants have the type of their underlying integer type,
310  // not the type of the enum. C++ uses the type of the enum.)
311  QualType AlternateType;
312
313  // We require the return types to strictly match here.
314  for (; I != E; ++I) {
315    const ReturnStmt *RS = *I;
316    const Expr *RetE = RS->getRetValue();
317    if (!checkReturnValueType(Ctx, RetE, CSI.ReturnType, AlternateType)) {
318      // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
319      Diag(RS->getLocStart(),
320           diag::err_typecheck_missing_return_type_incompatible)
321        << (RetE ? RetE->getType() : Ctx.VoidTy) << CSI.ReturnType
322        << isa<LambdaScopeInfo>(CSI);
323      // Don't bother fixing up the return statements in the block if some of
324      // them are unfixable anyway.
325      AlternateType = Ctx.VoidTy;
326      // Continue iterating so that we keep emitting diagnostics.
327    }
328  }
329
330  // If our return statements turned out to be compatible, but we needed to
331  // pick a different return type, go through and fix the ones that need it.
332  if (AlternateType == Ctx.DependentTy) {
333    for (SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
334                                                E = CSI.Returns.end();
335         I != E; ++I) {
336      ReturnStmt *RS = *I;
337      Expr *RetE = RS->getRetValue();
338      if (RetE->getType() == CSI.ReturnType)
339        continue;
340
341      // Right now we only support integral fixup casts.
342      assert(CSI.ReturnType->isIntegralOrUnscopedEnumerationType());
343      assert(RetE->getType()->isIntegralOrUnscopedEnumerationType());
344      ExprResult Casted = ImpCastExprToType(RetE, CSI.ReturnType,
345                                            CK_IntegralCast);
346      assert(Casted.isUsable());
347      RS->setRetValue(Casted.take());
348    }
349  }
350}
351
352void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
353                                        Declarator &ParamInfo,
354                                        Scope *CurScope) {
355  // Determine if we're within a context where we know that the lambda will
356  // be dependent, because there are template parameters in scope.
357  bool KnownDependent = false;
358  if (Scope *TmplScope = CurScope->getTemplateParamParent())
359    if (!TmplScope->decl_empty())
360      KnownDependent = true;
361
362  CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
363
364  // Determine the signature of the call operator.
365  TypeSourceInfo *MethodTyInfo;
366  bool ExplicitParams = true;
367  bool ExplicitResultType = true;
368  SourceLocation EndLoc;
369  llvm::ArrayRef<ParmVarDecl *> Params;
370  if (ParamInfo.getNumTypeObjects() == 0) {
371    // C++11 [expr.prim.lambda]p4:
372    //   If a lambda-expression does not include a lambda-declarator, it is as
373    //   if the lambda-declarator were ().
374    FunctionProtoType::ExtProtoInfo EPI;
375    EPI.HasTrailingReturn = true;
376    EPI.TypeQuals |= DeclSpec::TQ_const;
377    QualType MethodTy = Context.getFunctionType(Context.DependentTy,
378                                                /*Args=*/0, /*NumArgs=*/0, EPI);
379    MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
380    ExplicitParams = false;
381    ExplicitResultType = false;
382    EndLoc = Intro.Range.getEnd();
383  } else {
384    assert(ParamInfo.isFunctionDeclarator() &&
385           "lambda-declarator is a function");
386    DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
387
388    // C++11 [expr.prim.lambda]p5:
389    //   This function call operator is declared const (9.3.1) if and only if
390    //   the lambda-expression's parameter-declaration-clause is not followed
391    //   by mutable. It is neither virtual nor declared volatile. [...]
392    if (!FTI.hasMutableQualifier())
393      FTI.TypeQuals |= DeclSpec::TQ_const;
394
395    MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
396    assert(MethodTyInfo && "no type from lambda-declarator");
397    EndLoc = ParamInfo.getSourceRange().getEnd();
398
399    ExplicitResultType
400      = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
401                                                        != Context.DependentTy;
402
403    TypeLoc TL = MethodTyInfo->getTypeLoc();
404    FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
405    Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
406                                           Proto.getNumArgs());
407
408    // Check for unexpanded parameter packs in the method type.
409    // FIXME: We should allow unexpanded parameter packs here, but that would,
410    // in turn, make the lambda expression contain unexpanded parameter packs.
411    if (DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
412                                        UPPC_Lambda)) {
413      // Drop the parameters.
414      Params = llvm::ArrayRef<ParmVarDecl *>();
415      FunctionProtoType::ExtProtoInfo EPI;
416      EPI.HasTrailingReturn = false;
417      EPI.TypeQuals |= DeclSpec::TQ_const;
418      QualType MethodTy = Context.getFunctionType(Context.DependentTy,
419                                                  /*Args=*/0, /*NumArgs=*/0, EPI);
420      MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
421      ExplicitParams = false;
422      ExplicitResultType = false;
423    }
424  }
425
426  CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
427                                                MethodTyInfo, EndLoc, Params);
428
429  if (ExplicitParams)
430    CheckCXXDefaultArguments(Method);
431
432  // Attributes on the lambda apply to the method.
433  ProcessDeclAttributes(CurScope, Method, ParamInfo);
434
435  // Introduce the function call operator as the current declaration context.
436  PushDeclContext(CurScope, Method);
437
438  // Introduce the lambda scope.
439  LambdaScopeInfo *LSI
440    = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
441                       ExplicitResultType,
442                       (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
443
444  // Handle explicit captures.
445  SourceLocation PrevCaptureLoc
446    = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
447  for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
448         C = Intro.Captures.begin(),
449         E = Intro.Captures.end();
450       C != E;
451       PrevCaptureLoc = C->Loc, ++C) {
452    if (C->Kind == LCK_This) {
453      // C++11 [expr.prim.lambda]p8:
454      //   An identifier or this shall not appear more than once in a
455      //   lambda-capture.
456      if (LSI->isCXXThisCaptured()) {
457        Diag(C->Loc, diag::err_capture_more_than_once)
458          << "'this'"
459          << SourceRange(LSI->getCXXThisCapture().getLocation())
460          << FixItHint::CreateRemoval(
461               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
462        continue;
463      }
464
465      // C++11 [expr.prim.lambda]p8:
466      //   If a lambda-capture includes a capture-default that is =, the
467      //   lambda-capture shall not contain this [...].
468      if (Intro.Default == LCD_ByCopy) {
469        Diag(C->Loc, diag::err_this_capture_with_copy_default)
470          << FixItHint::CreateRemoval(
471               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
472        continue;
473      }
474
475      // C++11 [expr.prim.lambda]p12:
476      //   If this is captured by a local lambda expression, its nearest
477      //   enclosing function shall be a non-static member function.
478      QualType ThisCaptureType = getCurrentThisType();
479      if (ThisCaptureType.isNull()) {
480        Diag(C->Loc, diag::err_this_capture) << true;
481        continue;
482      }
483
484      CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
485      continue;
486    }
487
488    assert(C->Id && "missing identifier for capture");
489
490    // C++11 [expr.prim.lambda]p8:
491    //   If a lambda-capture includes a capture-default that is &, the
492    //   identifiers in the lambda-capture shall not be preceded by &.
493    //   If a lambda-capture includes a capture-default that is =, [...]
494    //   each identifier it contains shall be preceded by &.
495    if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
496      Diag(C->Loc, diag::err_reference_capture_with_reference_default)
497        << FixItHint::CreateRemoval(
498             SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
499      continue;
500    } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
501      Diag(C->Loc, diag::err_copy_capture_with_copy_default)
502        << FixItHint::CreateRemoval(
503             SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
504      continue;
505    }
506
507    DeclarationNameInfo Name(C->Id, C->Loc);
508    LookupResult R(*this, Name, LookupOrdinaryName);
509    LookupName(R, CurScope);
510    if (R.isAmbiguous())
511      continue;
512    if (R.empty()) {
513      // FIXME: Disable corrections that would add qualification?
514      CXXScopeSpec ScopeSpec;
515      DeclFilterCCC<VarDecl> Validator;
516      if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
517        continue;
518    }
519
520    // C++11 [expr.prim.lambda]p10:
521    //   The identifiers in a capture-list are looked up using the usual rules
522    //   for unqualified name lookup (3.4.1); each such lookup shall find a
523    //   variable with automatic storage duration declared in the reaching
524    //   scope of the local lambda expression.
525    //
526    // Note that the 'reaching scope' check happens in tryCaptureVariable().
527    VarDecl *Var = R.getAsSingle<VarDecl>();
528    if (!Var) {
529      Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
530      continue;
531    }
532
533    if (!Var->hasLocalStorage()) {
534      Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
535      Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
536      continue;
537    }
538
539    // C++11 [expr.prim.lambda]p8:
540    //   An identifier or this shall not appear more than once in a
541    //   lambda-capture.
542    if (LSI->isCaptured(Var)) {
543      Diag(C->Loc, diag::err_capture_more_than_once)
544        << C->Id
545        << SourceRange(LSI->getCapture(Var).getLocation())
546        << FixItHint::CreateRemoval(
547             SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
548      continue;
549    }
550
551    // C++11 [expr.prim.lambda]p23:
552    //   A capture followed by an ellipsis is a pack expansion (14.5.3).
553    SourceLocation EllipsisLoc;
554    if (C->EllipsisLoc.isValid()) {
555      if (Var->isParameterPack()) {
556        EllipsisLoc = C->EllipsisLoc;
557      } else {
558        Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
559          << SourceRange(C->Loc);
560
561        // Just ignore the ellipsis.
562      }
563    } else if (Var->isParameterPack()) {
564      Diag(C->Loc, diag::err_lambda_unexpanded_pack);
565      continue;
566    }
567
568    TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
569                                                 TryCapture_ExplicitByVal;
570    tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
571  }
572  finishLambdaExplicitCaptures(LSI);
573
574  // Add lambda parameters into scope.
575  addLambdaParameters(Method, CurScope);
576
577  // Enter a new evaluation context to insulate the lambda from any
578  // cleanups from the enclosing full-expression.
579  PushExpressionEvaluationContext(PotentiallyEvaluated);
580}
581
582void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
583                            bool IsInstantiation) {
584  // Leave the expression-evaluation context.
585  DiscardCleanupsInEvaluationContext();
586  PopExpressionEvaluationContext();
587
588  // Leave the context of the lambda.
589  if (!IsInstantiation)
590    PopDeclContext();
591
592  // Finalize the lambda.
593  LambdaScopeInfo *LSI = getCurLambda();
594  CXXRecordDecl *Class = LSI->Lambda;
595  Class->setInvalidDecl();
596  SmallVector<Decl*, 4> Fields;
597  for (RecordDecl::field_iterator i = Class->field_begin(),
598                                  e = Class->field_end(); i != e; ++i)
599    Fields.push_back(*i);
600  ActOnFields(0, Class->getLocation(), Class, Fields,
601              SourceLocation(), SourceLocation(), 0);
602  CheckCompletedCXXClass(Class);
603
604  PopFunctionScopeInfo();
605}
606
607/// \brief Add a lambda's conversion to function pointer, as described in
608/// C++11 [expr.prim.lambda]p6.
609static void addFunctionPointerConversion(Sema &S,
610                                         SourceRange IntroducerRange,
611                                         CXXRecordDecl *Class,
612                                         CXXMethodDecl *CallOperator) {
613  // Add the conversion to function pointer.
614  const FunctionProtoType *Proto
615    = CallOperator->getType()->getAs<FunctionProtoType>();
616  QualType FunctionPtrTy;
617  QualType FunctionTy;
618  {
619    FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
620    ExtInfo.TypeQuals = 0;
621    FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
622                                           Proto->arg_type_begin(),
623                                           Proto->getNumArgs(),
624                                           ExtInfo);
625    FunctionPtrTy = S.Context.getPointerType(FunctionTy);
626  }
627
628  FunctionProtoType::ExtProtoInfo ExtInfo;
629  ExtInfo.TypeQuals = Qualifiers::Const;
630  QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
631
632  SourceLocation Loc = IntroducerRange.getBegin();
633  DeclarationName Name
634    = S.Context.DeclarationNames.getCXXConversionFunctionName(
635        S.Context.getCanonicalType(FunctionPtrTy));
636  DeclarationNameLoc NameLoc;
637  NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
638                                                               Loc);
639  CXXConversionDecl *Conversion
640    = CXXConversionDecl::Create(S.Context, Class, Loc,
641                                DeclarationNameInfo(Name, Loc, NameLoc),
642                                ConvTy,
643                                S.Context.getTrivialTypeSourceInfo(ConvTy,
644                                                                   Loc),
645                                /*isInline=*/false, /*isExplicit=*/false,
646                                /*isConstexpr=*/false,
647                                CallOperator->getBody()->getLocEnd());
648  Conversion->setAccess(AS_public);
649  Conversion->setImplicit(true);
650  Class->addDecl(Conversion);
651
652  // Add a non-static member function "__invoke" that will be the result of
653  // the conversion.
654  Name = &S.Context.Idents.get("__invoke");
655  CXXMethodDecl *Invoke
656    = CXXMethodDecl::Create(S.Context, Class, Loc,
657                            DeclarationNameInfo(Name, Loc), FunctionTy,
658                            CallOperator->getTypeSourceInfo(),
659                            /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
660                            /*IsConstexpr=*/false,
661                            CallOperator->getBody()->getLocEnd());
662  SmallVector<ParmVarDecl *, 4> InvokeParams;
663  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
664    ParmVarDecl *From = CallOperator->getParamDecl(I);
665    InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
666                                               From->getLocStart(),
667                                               From->getLocation(),
668                                               From->getIdentifier(),
669                                               From->getType(),
670                                               From->getTypeSourceInfo(),
671                                               From->getStorageClass(),
672                                               From->getStorageClassAsWritten(),
673                                               /*DefaultArg=*/0));
674  }
675  Invoke->setParams(InvokeParams);
676  Invoke->setAccess(AS_private);
677  Invoke->setImplicit(true);
678  Class->addDecl(Invoke);
679}
680
681/// \brief Add a lambda's conversion to block pointer.
682static void addBlockPointerConversion(Sema &S,
683                                      SourceRange IntroducerRange,
684                                      CXXRecordDecl *Class,
685                                      CXXMethodDecl *CallOperator) {
686  const FunctionProtoType *Proto
687    = CallOperator->getType()->getAs<FunctionProtoType>();
688  QualType BlockPtrTy;
689  {
690    FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
691    ExtInfo.TypeQuals = 0;
692    QualType FunctionTy
693      = S.Context.getFunctionType(Proto->getResultType(),
694                                  Proto->arg_type_begin(),
695                                  Proto->getNumArgs(),
696                                  ExtInfo);
697    BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
698  }
699
700  FunctionProtoType::ExtProtoInfo ExtInfo;
701  ExtInfo.TypeQuals = Qualifiers::Const;
702  QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
703
704  SourceLocation Loc = IntroducerRange.getBegin();
705  DeclarationName Name
706    = S.Context.DeclarationNames.getCXXConversionFunctionName(
707        S.Context.getCanonicalType(BlockPtrTy));
708  DeclarationNameLoc NameLoc;
709  NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
710  CXXConversionDecl *Conversion
711    = CXXConversionDecl::Create(S.Context, Class, Loc,
712                                DeclarationNameInfo(Name, Loc, NameLoc),
713                                ConvTy,
714                                S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
715                                /*isInline=*/false, /*isExplicit=*/false,
716                                /*isConstexpr=*/false,
717                                CallOperator->getBody()->getLocEnd());
718  Conversion->setAccess(AS_public);
719  Conversion->setImplicit(true);
720  Class->addDecl(Conversion);
721}
722
723ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
724                                 Scope *CurScope,
725                                 bool IsInstantiation) {
726  // Collect information from the lambda scope.
727  llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
728  llvm::SmallVector<Expr *, 4> CaptureInits;
729  LambdaCaptureDefault CaptureDefault;
730  CXXRecordDecl *Class;
731  CXXMethodDecl *CallOperator;
732  SourceRange IntroducerRange;
733  bool ExplicitParams;
734  bool ExplicitResultType;
735  bool LambdaExprNeedsCleanups;
736  llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
737  llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
738  {
739    LambdaScopeInfo *LSI = getCurLambda();
740    CallOperator = LSI->CallOperator;
741    Class = LSI->Lambda;
742    IntroducerRange = LSI->IntroducerRange;
743    ExplicitParams = LSI->ExplicitParams;
744    ExplicitResultType = !LSI->HasImplicitReturnType;
745    LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
746    ArrayIndexVars.swap(LSI->ArrayIndexVars);
747    ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
748
749    // Translate captures.
750    for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
751      LambdaScopeInfo::Capture From = LSI->Captures[I];
752      assert(!From.isBlockCapture() && "Cannot capture __block variables");
753      bool IsImplicit = I >= LSI->NumExplicitCaptures;
754
755      // Handle 'this' capture.
756      if (From.isThisCapture()) {
757        Captures.push_back(LambdaExpr::Capture(From.getLocation(),
758                                               IsImplicit,
759                                               LCK_This));
760        CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
761                                                         getCurrentThisType(),
762                                                         /*isImplicit=*/true));
763        continue;
764      }
765
766      VarDecl *Var = From.getVariable();
767      LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
768      Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
769                                             Kind, Var, From.getEllipsisLoc()));
770      CaptureInits.push_back(From.getCopyExpr());
771    }
772
773    switch (LSI->ImpCaptureStyle) {
774    case CapturingScopeInfo::ImpCap_None:
775      CaptureDefault = LCD_None;
776      break;
777
778    case CapturingScopeInfo::ImpCap_LambdaByval:
779      CaptureDefault = LCD_ByCopy;
780      break;
781
782    case CapturingScopeInfo::ImpCap_LambdaByref:
783      CaptureDefault = LCD_ByRef;
784      break;
785
786    case CapturingScopeInfo::ImpCap_Block:
787      llvm_unreachable("block capture in lambda");
788      break;
789    }
790
791    // C++11 [expr.prim.lambda]p4:
792    //   If a lambda-expression does not include a
793    //   trailing-return-type, it is as if the trailing-return-type
794    //   denotes the following type:
795    // FIXME: Assumes current resolution to core issue 975.
796    if (LSI->HasImplicitReturnType) {
797      deduceClosureReturnType(*LSI);
798
799      //   - if there are no return statements in the
800      //     compound-statement, or all return statements return
801      //     either an expression of type void or no expression or
802      //     braced-init-list, the type void;
803      if (LSI->ReturnType.isNull()) {
804        LSI->ReturnType = Context.VoidTy;
805      }
806
807      // Create a function type with the inferred return type.
808      const FunctionProtoType *Proto
809        = CallOperator->getType()->getAs<FunctionProtoType>();
810      QualType FunctionTy
811        = Context.getFunctionType(LSI->ReturnType,
812                                  Proto->arg_type_begin(),
813                                  Proto->getNumArgs(),
814                                  Proto->getExtProtoInfo());
815      CallOperator->setType(FunctionTy);
816    }
817
818    // C++ [expr.prim.lambda]p7:
819    //   The lambda-expression's compound-statement yields the
820    //   function-body (8.4) of the function call operator [...].
821    ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
822    CallOperator->setLexicalDeclContext(Class);
823    Class->addDecl(CallOperator);
824    PopExpressionEvaluationContext();
825
826    // C++11 [expr.prim.lambda]p6:
827    //   The closure type for a lambda-expression with no lambda-capture
828    //   has a public non-virtual non-explicit const conversion function
829    //   to pointer to function having the same parameter and return
830    //   types as the closure type's function call operator.
831    if (Captures.empty() && CaptureDefault == LCD_None)
832      addFunctionPointerConversion(*this, IntroducerRange, Class,
833                                   CallOperator);
834
835    // Objective-C++:
836    //   The closure type for a lambda-expression has a public non-virtual
837    //   non-explicit const conversion function to a block pointer having the
838    //   same parameter and return types as the closure type's function call
839    //   operator.
840    if (getLangOpts().Blocks && getLangOpts().ObjC1)
841      addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
842
843    // Finalize the lambda class.
844    SmallVector<Decl*, 4> Fields;
845    for (RecordDecl::field_iterator i = Class->field_begin(),
846                                    e = Class->field_end(); i != e; ++i)
847      Fields.push_back(*i);
848    ActOnFields(0, Class->getLocation(), Class, Fields,
849                SourceLocation(), SourceLocation(), 0);
850    CheckCompletedCXXClass(Class);
851  }
852
853  if (LambdaExprNeedsCleanups)
854    ExprNeedsCleanups = true;
855
856  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
857                                          CaptureDefault, Captures,
858                                          ExplicitParams, ExplicitResultType,
859                                          CaptureInits, ArrayIndexVars,
860                                          ArrayIndexStarts, Body->getLocEnd());
861
862  // C++11 [expr.prim.lambda]p2:
863  //   A lambda-expression shall not appear in an unevaluated operand
864  //   (Clause 5).
865  if (!CurContext->isDependentContext()) {
866    switch (ExprEvalContexts.back().Context) {
867    case Unevaluated:
868      // We don't actually diagnose this case immediately, because we
869      // could be within a context where we might find out later that
870      // the expression is potentially evaluated (e.g., for typeid).
871      ExprEvalContexts.back().Lambdas.push_back(Lambda);
872      break;
873
874    case ConstantEvaluated:
875    case PotentiallyEvaluated:
876    case PotentiallyEvaluatedIfUsed:
877      break;
878    }
879  }
880
881  return MaybeBindToTemporary(Lambda);
882}
883
884ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
885                                               SourceLocation ConvLocation,
886                                               CXXConversionDecl *Conv,
887                                               Expr *Src) {
888  // Make sure that the lambda call operator is marked used.
889  CXXRecordDecl *Lambda = Conv->getParent();
890  CXXMethodDecl *CallOperator
891    = cast<CXXMethodDecl>(
892        *Lambda->lookup(
893          Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
894  CallOperator->setReferenced();
895  CallOperator->setUsed();
896
897  ExprResult Init = PerformCopyInitialization(
898                      InitializedEntity::InitializeBlock(ConvLocation,
899                                                         Src->getType(),
900                                                         /*NRVO=*/false),
901                      CurrentLocation, Src);
902  if (!Init.isInvalid())
903    Init = ActOnFinishFullExpr(Init.take());
904
905  if (Init.isInvalid())
906    return ExprError();
907
908  // Create the new block to be returned.
909  BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
910
911  // Set the type information.
912  Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
913  Block->setIsVariadic(CallOperator->isVariadic());
914  Block->setBlockMissingReturnType(false);
915
916  // Add parameters.
917  SmallVector<ParmVarDecl *, 4> BlockParams;
918  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
919    ParmVarDecl *From = CallOperator->getParamDecl(I);
920    BlockParams.push_back(ParmVarDecl::Create(Context, Block,
921                                              From->getLocStart(),
922                                              From->getLocation(),
923                                              From->getIdentifier(),
924                                              From->getType(),
925                                              From->getTypeSourceInfo(),
926                                              From->getStorageClass(),
927                                            From->getStorageClassAsWritten(),
928                                              /*DefaultArg=*/0));
929  }
930  Block->setParams(BlockParams);
931
932  Block->setIsConversionFromLambda(true);
933
934  // Add capture. The capture uses a fake variable, which doesn't correspond
935  // to any actual memory location. However, the initializer copy-initializes
936  // the lambda object.
937  TypeSourceInfo *CapVarTSI =
938      Context.getTrivialTypeSourceInfo(Src->getType());
939  VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
940                                    ConvLocation, 0,
941                                    Src->getType(), CapVarTSI,
942                                    SC_None, SC_None);
943  BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
944                             /*Nested=*/false, /*Copy=*/Init.take());
945  Block->setCaptures(Context, &Capture, &Capture + 1,
946                     /*CapturesCXXThis=*/false);
947
948  // Add a fake function body to the block. IR generation is responsible
949  // for filling in the actual body, which cannot be expressed as an AST.
950  Block->setBody(new (Context) CompoundStmt(Context, 0, 0,
951                                            ConvLocation,
952                                            ConvLocation));
953
954  // Create the block literal expression.
955  Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
956  ExprCleanupObjects.push_back(Block);
957  ExprNeedsCleanups = true;
958
959  return BuildBlock;
960}
961