Make sure Sema creates a field for 'this' captures.  (Doug, please double-check that this is correct.)



git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@150292 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/include/clang/Sema/ScopeInfo.h b/include/clang/Sema/ScopeInfo.h
index 91f468b..ea77ff4 100644
--- a/include/clang/Sema/ScopeInfo.h
+++ b/include/clang/Sema/ScopeInfo.h
@@ -156,8 +156,8 @@
         CopyExprAndNested(Cpy, isNested) {}
 
     enum IsThisCapture { ThisCapture };
-    Capture(IsThisCapture, bool isNested, SourceLocation Loc)
-      : VarAndKind(0, Cap_This), CopyExprAndNested(0, isNested), Loc(Loc) {
+    Capture(IsThisCapture, bool isNested, SourceLocation Loc, Expr *Cpy)
+      : VarAndKind(0, Cap_This), CopyExprAndNested(Cpy, isNested), Loc(Loc) {
     }
 
     bool isThisCapture() const { return VarAndKind.getInt() == Cap_This; }
@@ -208,8 +208,8 @@
     CaptureMap[Var] = Captures.size();
   }
 
-  void AddThisCapture(bool isNested, SourceLocation Loc) {
-    Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc));
+  void AddThisCapture(bool isNested, SourceLocation Loc, Expr *Cpy) {
+    Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, Cpy));
     CXXThisCaptureIndex = Captures.size();
   }
 
diff --git a/lib/Sema/SemaExprCXX.cpp b/lib/Sema/SemaExprCXX.cpp
index 5a2a827..c16d7e2 100644
--- a/lib/Sema/SemaExprCXX.cpp
+++ b/lib/Sema/SemaExprCXX.cpp
@@ -707,8 +707,22 @@
   for (unsigned idx = FunctionScopes.size() - 1;
        NumClosures; --idx, --NumClosures) {
     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
+    Expr *ThisExpr = 0;
+    if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
+      // For lambda expressions, build a field and an initializing expression.
+      QualType ThisTy = getCurrentThisType();
+      CXXRecordDecl *Lambda = LSI->Lambda;
+      FieldDecl *Field
+        = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
+                            Context.getTrivialTypeSourceInfo(ThisTy, Loc),
+                            0, false, false);
+      Field->setImplicit(true);
+      Field->setAccess(AS_private);
+      Lambda->addDecl(Field);
+      ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
+    }
     bool isNested = NumClosures > 1;
-    CSI->AddThisCapture(isNested, Loc);
+    CSI->AddThisCapture(isNested, Loc, ThisExpr);
   }
 }
 
diff --git a/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp b/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp
index ad603e1..1f7580e 100644
--- a/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp
+++ b/test/CXX/expr/expr.prim/expr.prim.lambda/p14.cpp
@@ -55,3 +55,11 @@
   };
   static_assert(sizeof(x) == sizeof(ExpectedLayout), "Layout mismatch!");
 }
+
+struct ExpectedThisLayout {
+  ExpectedThisLayout* a;
+  void f() {
+    auto x = [this]() -> void {};
+    static_assert(sizeof(x) == sizeof(ExpectedThisLayout), "Layout mismatch!");
+  }
+};