Make sure that ScopedDecls passed to DeclContext::addDecl are added into their lexical context

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@61998 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index 8521b9b..f29417e 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -164,6 +164,13 @@
 // ScopedDecl Implementation
 //===----------------------------------------------------------------------===//
 
+void ScopedDecl::setDeclContext(DeclContext *DC) {
+  if (isOutOfSemaDC())
+    delete getMultipleDC();
+  
+  DeclCtx = reinterpret_cast<uintptr_t>(DC);
+}
+
 void ScopedDecl::setLexicalDeclContext(DeclContext *DC) {
   if (DC == getLexicalDeclContext())
     return;
diff --git a/lib/AST/DeclBase.cpp b/lib/AST/DeclBase.cpp
index f1ce3f3..d9765ac 100644
--- a/lib/AST/DeclBase.cpp
+++ b/lib/AST/DeclBase.cpp
@@ -514,6 +514,7 @@
 }
 
 void DeclContext::addDecl(ASTContext &Context, ScopedDecl *D, bool AllowLookup) {
+  assert(D->getLexicalDeclContext() == this && "Decl inserted into wrong lexical context");
   Decls.push_back(D);
   if (AllowLookup)
     D->getDeclContext()->insert(Context, D);
@@ -599,7 +600,6 @@
   if (LookupPtr.getPointer())
     insertImpl(D);
 
-
   // If we are a transparent context, insert into our parent context,
   // too. This operation is recursive.
   if (isTransparentContext())
diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp
index d9436eb..ecf6de9 100644
--- a/lib/Sema/SemaDecl.cpp
+++ b/lib/Sema/SemaDecl.cpp
@@ -441,7 +441,13 @@
   
   
   // TUScope is the translation-unit scope to insert this function into.
+  // FIXME: This is hideous. We need to teach PushOnScopeChains to
+  // relate Scopes to DeclContexts, and probably eliminate CurContext
+  // entirely, but we're not there yet.
+  DeclContext *SavedContext = CurContext;
+  CurContext = Context.getTranslationUnitDecl();
   PushOnScopeChains(New, TUScope);
+  CurContext = SavedContext;
   return New;
 }
 
@@ -2705,6 +2711,8 @@
   // Introduce our parameters into the function scope
   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
     ParmVarDecl *Param = FD->getParamDecl(p);
+    Param->setOwningFunction(FD);
+
     // If this has an identifier, add it to the scope stack.
     if (Param->getIdentifier())
       PushOnScopeChains(Param, FnBodyScope);