Index: llvm/tools/clang/test/CodeGenCXX/debug-info-static-member.cpp
===================================================================
--- llvm/tools/clang/test/CodeGenCXX/debug-info-static-member.cpp	(revision 0)
+++ llvm/tools/clang/test/CodeGenCXX/debug-info-static-member.cpp	(revision 0)
@@ -0,0 +1,41 @@
+// RUN: %clangxx -g -O0 %s -emit-llvm -S -o - | FileCheck %s
+// PR14471
+
+// The definition of C::a drives the emission of class C, which is
+// why the definition of "a" comes before the declarations while
+// "b" and "c" come after.
+
+// CHECK: metadata !"a", {{.*}} @_ZN1C1aE, metadata ![[DECL_A:[0-9]+]]} ; [ DW_TAG_variable ] [a] {{.*}} [def]
+// CHECK: ![[DECL_A]] = metadata {{.*}} [ DW_TAG_CXX_static_member ] [a] {{.*}} [private]
+// CHECK: [ DW_TAG_CXX_static_member ] [const_a] {{.*}} [private]
+// CHECK: ![[DECL_B:[0-9]+]] {{.*}} [ DW_TAG_CXX_static_member ] [b] {{.*}} [protected]
+// CHECK: [ DW_TAG_CXX_static_member ] [const_b] {{.*}} [protected]
+// CHECK: ![[DECL_C:[0-9]+]] {{.*}} [ DW_TAG_CXX_static_member ] [c] {{.*}}
+// CHECK: [ DW_TAG_CXX_static_member ] [const_c] {{.*}}
+// CHECK: metadata !"b", {{.*}} @_ZN1C1bE, metadata ![[DECL_B]]} ; [ DW_TAG_variable ] [b] {{.*}} [def]
+// CHECK: metadata !"c", {{.*}} @_ZN1C1cE, metadata ![[DECL_C]]} ; [ DW_TAG_variable ] [c] {{.*}} [def]
+
+
+class C
+{
+  static int a;
+  const static int const_a = 16;
+protected:
+  static int b;
+  const static int const_b = 17;
+public:
+  static int c;
+  const static int const_c = 18;
+  int d;
+};
+
+int C::a = 4;
+int C::b = 2;
+int C::c = 1;
+
+int main()
+{
+        C instance_C;
+        instance_C.d = 8;
+        return C::c;
+}
Index: llvm/tools/clang/test/CodeGenCXX/debug-lambda-expressions.cpp
===================================================================
--- llvm/tools/clang/test/CodeGenCXX/debug-lambda-expressions.cpp	(revision 170394)
+++ llvm/tools/clang/test/CodeGenCXX/debug-lambda-expressions.cpp	(working copy)
@@ -61,11 +61,11 @@
 // CHECK: [[DES_LAM_A]] = metadata {{.*}}[[LAM_A]], metadata !"~", metadata !"~"{{.*}}[ DW_TAG_subprogram ]
 
 // CVAR:
-// CHECK: metadata !{i32 {{.*}}, i32 0, null, metadata !"cvar", metadata !"cvar", metadata !"", metadata [[FILE]], i32 [[CVAR_LINE:.*]], metadata ![[CVAR_T:.*]], i32 0, i32 1, %class.anon.0* @cvar} ; [ DW_TAG_variable ]
+// CHECK: metadata !{i32 {{.*}}, i32 0, null, metadata !"cvar", metadata !"cvar", metadata !"", metadata [[FILE]], i32 [[CVAR_LINE:.*]], metadata ![[CVAR_T:.*]], i32 0, i32 1, %class.anon.0* @cvar, null} ; [ DW_TAG_variable ]
 // CHECK: [[CVAR_T]] = metadata !{i32 {{.*}}, null, metadata !"", metadata [[FILE]], i32 [[CVAR_LINE]], i64 8, i64 8, i32 0, i32 0, null, metadata ![[CVAR_ARGS:.*]], i32 0, null, null} ; [ DW_TAG_class_type ]
 // CHECK: [[CVAR_ARGS]] = metadata !{metadata !{{.*}}, metadata !{{.*}}, metadata !{{.*}}}
 
 // VAR:
-// CHECK: metadata !{i32 {{.*}}, i32 0, null, metadata !"var", metadata !"var", metadata !"", metadata [[FILE]], i32 [[VAR_LINE:.*]], metadata ![[VAR_T:.*]], i32 1, i32 1, %class.anon* @var} ; [ DW_TAG_variable ]
+// CHECK: metadata !{i32 {{.*}}, i32 0, null, metadata !"var", metadata !"var", metadata !"", metadata [[FILE]], i32 [[VAR_LINE:.*]], metadata ![[VAR_T:.*]], i32 1, i32 1, %class.anon* @var, null} ; [ DW_TAG_variable ]
 // CHECK: [[VAR_T]] = metadata !{i32 {{.*}}, null, metadata !"", metadata [[FILE]], i32 [[VAR_LINE]], i64 8, i64 8, i32 0, i32 0, null, metadata ![[VAR_ARGS:.*]], i32 0, null, null} ; [ DW_TAG_class_type ]
 // CHECK: [[VAR_ARGS]] = metadata !{metadata !{{.*}}, metadata !{{.*}}, metadata !{{.*}}}
Index: llvm/tools/clang/test/CodeGenObjC/debug-info-static-var.m
===================================================================
--- llvm/tools/clang/test/CodeGenObjC/debug-info-static-var.m	(revision 170394)
+++ llvm/tools/clang/test/CodeGenObjC/debug-info-static-var.m	(working copy)
@@ -3,12 +3,14 @@
 // Radar 8801045
 // Do not emit AT_MIPS_linkage_name for static variable i
 
-// CHECK: Lset6 = Lstring3-Lsection_str           ## DW_AT_name
-// CHECK-NEXT: .long   Lset6
+// CHECK: Lset5 = Lstring4-Lsection_str           ## DW_AT_name
+// CHECK-NEXT: .long   Lset5
 // CHECK-NEXT:        DW_AT_type
 // CHECK-NEXT:        DW_AT_decl_file
 // CHECK-NEXT:        DW_AT_decl_line
 // CHECK-NEXT:        DW_AT_location
+// CHECK: Lstring4:
+// CHECK-NEXT: .asciz "i"
 
 @interface A {
 }
Index: llvm/tools/clang/test/CodeGen/2009-10-20-GlobalDebug.c
===================================================================
--- llvm/tools/clang/test/CodeGen/2009-10-20-GlobalDebug.c	(revision 170394)
+++ llvm/tools/clang/test/CodeGen/2009-10-20-GlobalDebug.c	(working copy)
@@ -6,5 +6,5 @@
   return 0;
 }
 
-// CHECK: metadata !{i32 {{.*}}, i32 0, metadata !5, metadata !"localstatic", metadata !"localstatic", metadata !"", metadata !6, i32 5, metadata !9, i32 1, i32 1, i32* @main.localstatic} ; [ DW_TAG_variable ]
-// CHECK: metadata !{i32 {{.*}}, i32 0, null, metadata !"global", metadata !"global", metadata !"", metadata !6, i32 3, metadata !9, i32 0, i32 1, i32* @global} ; [ DW_TAG_variable ]
+// CHECK: metadata !{i32 {{.*}}, i32 0, metadata !5, metadata !"localstatic", metadata !"localstatic", metadata !"", metadata !6, i32 5, metadata !9, i32 1, i32 1, i32* @main.localstatic, null} ; [ DW_TAG_variable ]
+// CHECK: metadata !{i32 {{.*}}, i32 0, null, metadata !"global", metadata !"global", metadata !"", metadata !6, i32 3, metadata !9, i32 0, i32 1, i32* @global, null} ; [ DW_TAG_variable ]
Index: llvm/tools/clang/test/CodeGen/debug-info-static.c
===================================================================
--- llvm/tools/clang/test/CodeGen/debug-info-static.c	(revision 170394)
+++ llvm/tools/clang/test/CodeGen/debug-info-static.c	(working copy)
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1  -g -emit-llvm -o - %s | FileCheck %s
 
-// CHECK:  xyzzy} ; [ DW_TAG_variable ]
+// CHECK:  xyzzy, null} ; [ DW_TAG_variable ]
 void f(void)
 {
    static int xyzzy;
Index: llvm/tools/clang/lib/CodeGen/CGDebugInfo.h
===================================================================
--- llvm/tools/clang/lib/CodeGen/CGDebugInfo.h	(revision 170394)
+++ llvm/tools/clang/lib/CodeGen/CGDebugInfo.h	(working copy)
@@ -82,6 +82,7 @@
   llvm::DenseMap<const char *, llvm::WeakVH> DIFileCache;
   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH> SPCache;
   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH> NameSpaceCache;
+  llvm::DenseMap<const Decl *, llvm::WeakVH> StaticDataMemberCache;
 
   /// Helper functions for getOrCreateType.
   llvm::DIType CreateType(const BuiltinType *Ty);
@@ -151,7 +152,6 @@
                                AccessSpecifier AS, uint64_t offsetInBits,
                                llvm::DIFile tunit,
                                llvm::DIDescriptor scope);
-  void CollectRecordStaticVars(const RecordDecl *, llvm::DIType);
   void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile F,
                            SmallVectorImpl<llvm::Value *> &E,
                            llvm::DIType RecordTy);
@@ -291,6 +291,11 @@
   /// declaration for the given method definition.
   llvm::DISubprogram getFunctionDeclaration(const Decl *D);
 
+  /// getStaticDataMemberDeclaration - Return debug info descriptor to
+  /// describe in-class static data member declaration for the given
+  /// out-of-class definition.
+  llvm::DIDescriptor getStaticDataMemberDeclaration(const Decl *D);
+
   /// getFunctionName - Get function name for the given FunctionDecl. If the
   /// name is constructred on demand (e.g. C++ destructor) then the name
   /// is stored on the side.
Index: llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp
===================================================================
--- llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp	(revision 170394)
+++ llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp	(working copy)
@@ -715,33 +715,6 @@
 }
 
 
-void CGDebugInfo::
-CollectRecordStaticVars(const RecordDecl *RD, llvm::DIType FwdDecl) {
-  
-  for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
-       I != E; ++I)
-    if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
-      if (V->getInit()) {
-        const APValue *Value = V->evaluateValue();
-        if (Value && Value->isInt()) {
-          llvm::ConstantInt *CI
-            = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
-          
-          // Create the descriptor for static variable.
-          llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
-          StringRef VName = V->getName();
-          llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
-          // Do not use DIGlobalVariable for enums.
-          if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
-            DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
-                                          getLineNumber(V->getLocation()),
-                                          VTy, true, CI);
-          }
-        }
-      }
-    }
-}
-
 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
                                           QualType type,
                                           uint64_t sizeInBitsOverride,
@@ -827,11 +800,44 @@
   } else {
     bool IsMsStruct = record->isMsStruct(CGM.getContext());
     const FieldDecl *LastFD = 0;
-    for (RecordDecl::field_iterator I = record->field_begin(),
-           E = record->field_end();
-         I != E; ++I, ++fieldNo) {
-      FieldDecl *field = *I;
 
+    // Static and non-static members should appear in the same order as
+    // the corresponding declarations in the source program.
+    for (RecordDecl::decl_iterator I = record->decls_begin(),
+           E = record->decls_end(); I != E; ++I)
+      if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
+        // Create the descriptor for the static variable, with or without
+        // constant initializers.
+        llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
+        unsigned LineNumber = getLineNumber(V->getLocation());
+        StringRef VName = V->getName();
+        llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
+
+        // Do not use DIStaticDataMember for enums.
+        if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
+          continue;
+
+        llvm::ConstantInt *CI = NULL;
+        if (V->getInit()) {
+          const APValue *Value = V->evaluateValue();
+          if (Value && Value->isInt())
+            CI = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
+        }
+
+        unsigned Flags = 0;
+        AccessSpecifier Access = V->getAccess();
+        if (Access == clang::AS_private)
+          Flags |= llvm::DIDescriptor::FlagPrivate;
+        else if (Access == clang::AS_protected)
+          Flags |= llvm::DIDescriptor::FlagProtected;
+
+        llvm::DIStaticDataMember GV = DBuilder.createStaticDataMember(
+          RecordTy, VName, VUnit, LineNumber, VTy, Flags, CI);
+        elements.push_back(GV);
+        StaticDataMemberCache[V->getCanonicalDecl()] = llvm::WeakVH(GV);
+      } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
+         ++fieldNo;
+
       if (IsMsStruct) {
         // Zero-length bitfields following non-bitfield members are ignored
         if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
@@ -859,7 +865,7 @@
       llvm::DIType fieldType
         = createFieldType(name, type, SizeInBitsOverride,
                           field->getLocation(), field->getAccess(),
-                          layout.getFieldOffset(fieldNo), tunit, RecordTy);
+                          layout.getFieldOffset(fieldNo - 1), tunit, RecordTy);
 
       elements.push_back(fieldType);
     }
@@ -1264,7 +1270,6 @@
   }
 
   // Collect static variables with initializers and other fields.
-  CollectRecordStaticVars(RD, FwdDecl);
   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
   llvm::DIArray TParamsArray;
   if (CXXDecl) {
@@ -2678,6 +2683,20 @@
   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
 }
 
+/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
+/// a static data member of a class, find its corresponding in-class
+/// declaration.
+llvm::DIDescriptor CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
+  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
+    MI = StaticDataMemberCache.find(D->getCanonicalDecl());
+  if (MI != StaticDataMemberCache.end()) {
+    llvm::DIStaticDataMember SDM(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
+    if (SDM.isStaticDataMember())
+      return SDM;
+  }
+  return llvm::DIDescriptor();
+}
+
 /// EmitGlobalVariable - Emit information about a global variable.
 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
                                      const VarDecl *D) {
@@ -2709,7 +2728,8 @@
     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
                                 Unit, LineNo, getOrCreateType(T, Unit),
-                                Var->hasInternalLinkage(), Var);
+                                Var->hasInternalLinkage(), Var,
+                                getStaticDataMemberDeclaration(D));
 }
 
 /// EmitGlobalVariable - Emit information about an objective-c interface.
@@ -2756,7 +2776,8 @@
     return;
   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
                                 getLineNumber(VD->getLocation()),
-                                Ty, true, Init);
+                                Ty, true, Init,
+                                getStaticDataMemberDeclaration(VD));
 }
 
 /// getOrCreateNamesSpace - Return namespace descriptor for the given
