Fix for PR5967: Make const-marking for LLVM globals correct for cases requiring
run-time initialization, and emit run-time initializers aggresively to avoid
ordering issues with deferred globals.

llvm-svn: 92976
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 0dbf336..13cdc2b 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -66,10 +66,8 @@
 }
 
 void CodeGenModule::Release() {
-  // We need to call this first because it can add deferred declarations.
-  EmitCXXGlobalInitFunc();
-
   EmitDeferred();
+  EmitCXXGlobalInitFunc();
   if (Runtime)
     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
       AddGlobalCtor(ObjCInitFunction);
@@ -971,6 +969,7 @@
 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
   llvm::Constant *Init = 0;
   QualType ASTTy = D->getType();
+  bool NonConstInit = false;
 
   if (D->getInit() == 0) {
     // This is a tentative definition; tentative definitions are
@@ -990,8 +989,9 @@
     if (!Init) {
       QualType T = D->getInit()->getType();
       if (getLangOptions().CPlusPlus) {
-        CXXGlobalInits.push_back(D);
+        EmitCXXGlobalVarDeclInitFunc(D);
         Init = EmitNullConstant(T);
+        NonConstInit = true;
       } else {
         ErrorUnsupported(D, "static initializer");
         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
@@ -1052,7 +1052,7 @@
 
   // If it is safe to mark the global 'constant', do so now.
   GV->setConstant(false);
-  if (DeclIsConstantGlobal(Context, D))
+  if (!NonConstInit && DeclIsConstantGlobal(Context, D))
     GV->setConstant(true);
 
   GV->setAlignment(getContext().getDeclAlignInBytes(D));