Move lowerGlobal() from target-specific code to emitGlobal() in generic code.

Emitting the global initializers is mostly the same across
each architecture (same filling, alignment, etc.). The only difference
is in assembler-directive quirks. E.g., on ARM for ".align N" N is
the exponent for a power of 2, while on x86 N is the actual number
of bytes. To avoid target-specific directives, use .p2align which
is always a power of 2. Similarly, use % instead of @. Either one
may be a comment character for *some* architecture, but for the
architectures we care about % is not a comment character while @
is sometimes (ARM).

Usually MIPS uses ".space N" for ".zero", but the assembler seems
to accept ".zero" so don't change that for now.

May need to adjust .long in the future too.
.word for AArch64 and .4byte for MIPS?

Potentially we can refactor the lowerGlobals() dispatcher
(ELF vs ASM vs IASM). The only thing target-specific about that
is *probably* just the relocation type.

BUG= https://code.google.com/p/nativeclient/issues/detail?id=4076
R=stichnot@chromium.org

Review URL: https://codereview.chromium.org/1188603002.
diff --git a/src/IceTargetLowering.cpp b/src/IceTargetLowering.cpp
index aefad00..4bb035a 100644
--- a/src/IceTargetLowering.cpp
+++ b/src/IceTargetLowering.cpp
@@ -20,6 +20,7 @@
 #include "assembler_mips32.h"
 #include "IceCfg.h" // setError()
 #include "IceCfgNode.h"
+#include "IceGlobalInits.h"
 #include "IceOperand.h"
 #include "IceRegAlloc.h"
 #include "IceTargetLowering.h"
@@ -445,6 +446,89 @@
 
 TargetDataLowering::~TargetDataLowering() {}
 
+void TargetDataLowering::emitGlobal(const VariableDeclaration &Var) {
+  if (!ALLOW_DUMP)
+    return;
+
+  // If external and not initialized, this must be a cross test.
+  // Don't generate a declaration for such cases.
+  bool IsExternal = Var.isExternal() || Ctx->getFlags().getDisableInternal();
+  if (IsExternal && !Var.hasInitializer())
+    return;
+
+  Ostream &Str = Ctx->getStrEmit();
+  const VariableDeclaration::InitializerListType &Initializers =
+      Var.getInitializers();
+  bool HasNonzeroInitializer = Var.hasNonzeroInitializer();
+  bool IsConstant = Var.getIsConstant();
+  uint32_t Align = Var.getAlignment();
+  SizeT Size = Var.getNumBytes();
+  IceString MangledName = Var.mangleName(Ctx);
+  IceString SectionSuffix = "";
+  if (Ctx->getFlags().getDataSections())
+    SectionSuffix = "." + MangledName;
+
+  Str << "\t.type\t" << MangledName << ",%object\n";
+
+  if (IsConstant)
+    Str << "\t.section\t.rodata" << SectionSuffix << ",\"a\",%progbits\n";
+  else if (HasNonzeroInitializer)
+    Str << "\t.section\t.data" << SectionSuffix << ",\"aw\",%progbits\n";
+  else
+    Str << "\t.section\t.bss" << SectionSuffix << ",\"aw\",%nobits\n";
+
+  if (IsExternal)
+    Str << "\t.globl\t" << MangledName << "\n";
+
+  if (Align > 1) {
+    assert(llvm::isPowerOf2_32(Align));
+    // Use the .p2align directive, since the .align N directive can either
+    // interpret N as bytes, or power of 2 bytes, depending on the target.
+    Str << "\t.p2align\t" << llvm::Log2_32(Align) << "\n";
+  }
+
+  Str << MangledName << ":\n";
+
+  if (HasNonzeroInitializer) {
+    for (VariableDeclaration::Initializer *Init : Initializers) {
+      switch (Init->getKind()) {
+      case VariableDeclaration::Initializer::DataInitializerKind: {
+        const auto Data = llvm::cast<VariableDeclaration::DataInitializer>(Init)
+                              ->getContents();
+        for (SizeT i = 0; i < Init->getNumBytes(); ++i) {
+          Str << "\t.byte\t" << (((unsigned)Data[i]) & 0xff) << "\n";
+        }
+        break;
+      }
+      case VariableDeclaration::Initializer::ZeroInitializerKind:
+        Str << "\t.zero\t" << Init->getNumBytes() << "\n";
+        break;
+      case VariableDeclaration::Initializer::RelocInitializerKind: {
+        const auto Reloc =
+            llvm::cast<VariableDeclaration::RelocInitializer>(Init);
+        Str << "\t" << getEmit32Directive() << "\t";
+        Str << Reloc->getDeclaration()->mangleName(Ctx);
+        if (RelocOffsetT Offset = Reloc->getOffset()) {
+          if (Offset >= 0 || (Offset == INT32_MIN))
+            Str << " + " << Offset;
+          else
+            Str << " - " << -Offset;
+        }
+        Str << "\n";
+        break;
+      }
+      }
+    }
+  } else
+    // NOTE: for non-constant zero initializers, this is BSS (no bits),
+    // so an ELF writer would not write to the file, and only track
+    // virtual offsets, but the .s writer still needs this .zero and
+    // cannot simply use the .size to advance offsets.
+    Str << "\t.zero\t" << Size << "\n";
+
+  Str << "\t.size\t" << MangledName << ", " << Size << "\n";
+}
+
 std::unique_ptr<TargetHeaderLowering>
 TargetHeaderLowering::createLowering(GlobalContext *Ctx) {
   TargetArch Target = Ctx->getFlags().getTargetArch();
diff --git a/src/IceTargetLowering.h b/src/IceTargetLowering.h
index 66e663b..4d9598a 100644
--- a/src/IceTargetLowering.h
+++ b/src/IceTargetLowering.h
@@ -384,6 +384,13 @@
   virtual void lowerConstants() = 0;
 
 protected:
+  void emitGlobal(const VariableDeclaration &Var);
+
+  // For now, we assume .long is the right directive for emitting 4 byte
+  // emit global relocations. However, LLVM MIPS usually uses .4byte instead.
+  // Perhaps there is some difference when the location is unaligned.
+  const char *getEmit32Directive() { return ".long"; }
+
   explicit TargetDataLowering(GlobalContext *Ctx) : Ctx(Ctx) {}
   GlobalContext *Ctx;
 };
diff --git a/src/IceTargetLoweringARM32.cpp b/src/IceTargetLoweringARM32.cpp
index a2091b2..a4aa517 100644
--- a/src/IceTargetLoweringARM32.cpp
+++ b/src/IceTargetLoweringARM32.cpp
@@ -2194,11 +2194,6 @@
 TargetDataARM32::TargetDataARM32(GlobalContext *Ctx)
     : TargetDataLowering(Ctx) {}
 
-void TargetDataARM32::lowerGlobal(const VariableDeclaration &Var) const {
-  (void)Var;
-  UnimplementedError(Ctx->getFlags());
-}
-
 void TargetDataARM32::lowerGlobals(
     std::unique_ptr<VariableDeclarationList> Vars) {
   switch (Ctx->getFlags().getOutFileType()) {
@@ -2212,7 +2207,7 @@
     OstreamLocker L(Ctx);
     for (const VariableDeclaration *Var : *Vars) {
       if (GlobalContext::matchSymbolName(Var->getName(), TranslateOnly)) {
-        lowerGlobal(*Var);
+        emitGlobal(*Var);
       }
     }
   } break;
diff --git a/src/IceTargetLoweringARM32.h b/src/IceTargetLoweringARM32.h
index 2477aaa..7f5fdc8 100644
--- a/src/IceTargetLoweringARM32.h
+++ b/src/IceTargetLoweringARM32.h
@@ -319,7 +319,6 @@
   explicit TargetDataARM32(GlobalContext *Ctx);
 
 private:
-  void lowerGlobal(const VariableDeclaration &Var) const;
   ~TargetDataARM32() override {}
   template <typename T> static void emitConstantPool(GlobalContext *Ctx);
 };
diff --git a/src/IceTargetLoweringMIPS32.cpp b/src/IceTargetLoweringMIPS32.cpp
index 748881e..ee2300e 100644
--- a/src/IceTargetLoweringMIPS32.cpp
+++ b/src/IceTargetLoweringMIPS32.cpp
@@ -671,11 +671,6 @@
 TargetDataMIPS32::TargetDataMIPS32(GlobalContext *Ctx)
     : TargetDataLowering(Ctx) {}
 
-void TargetDataMIPS32::lowerGlobal(const VariableDeclaration &Var) const {
-  (void)Var;
-  llvm::report_fatal_error("Not yet implemented");
-}
-
 void TargetDataMIPS32::lowerGlobals(
     std::unique_ptr<VariableDeclarationList> Vars) {
   switch (Ctx->getFlags().getOutFileType()) {
@@ -689,7 +684,7 @@
     OstreamLocker L(Ctx);
     for (const VariableDeclaration *Var : *Vars) {
       if (GlobalContext::matchSymbolName(Var->getName(), TranslateOnly)) {
-        lowerGlobal(*Var);
+        emitGlobal(*Var);
       }
     }
   } break;
diff --git a/src/IceTargetLoweringMIPS32.h b/src/IceTargetLoweringMIPS32.h
index 3aad63f..9204833 100644
--- a/src/IceTargetLoweringMIPS32.h
+++ b/src/IceTargetLoweringMIPS32.h
@@ -144,7 +144,6 @@
   explicit TargetDataMIPS32(GlobalContext *Ctx);
 
 private:
-  void lowerGlobal(const VariableDeclaration &Var) const;
   ~TargetDataMIPS32() override {}
   template <typename T> static void emitConstantPool(GlobalContext *Ctx);
 };
diff --git a/src/IceTargetLoweringX8632.cpp b/src/IceTargetLoweringX8632.cpp
index dcfdc96..dbb4e4a 100644
--- a/src/IceTargetLoweringX8632.cpp
+++ b/src/IceTargetLoweringX8632.cpp
@@ -5017,82 +5017,6 @@
 TargetDataX8632::TargetDataX8632(GlobalContext *Ctx)
     : TargetDataLowering(Ctx) {}
 
-void TargetDataX8632::lowerGlobal(const VariableDeclaration &Var) {
-  // If external and not initialized, this must be a cross test.
-  // Don't generate a declaration for such cases.
-  bool IsExternal = Var.isExternal() || Ctx->getFlags().getDisableInternal();
-  if (IsExternal && !Var.hasInitializer())
-    return;
-
-  Ostream &Str = Ctx->getStrEmit();
-  const VariableDeclaration::InitializerListType &Initializers =
-      Var.getInitializers();
-  bool HasNonzeroInitializer = Var.hasNonzeroInitializer();
-  bool IsConstant = Var.getIsConstant();
-  uint32_t Align = Var.getAlignment();
-  SizeT Size = Var.getNumBytes();
-  IceString MangledName = Var.mangleName(Ctx);
-  IceString SectionSuffix = "";
-  if (Ctx->getFlags().getDataSections())
-    SectionSuffix = "." + MangledName;
-
-  Str << "\t.type\t" << MangledName << ",@object\n";
-
-  if (IsConstant)
-    Str << "\t.section\t.rodata" << SectionSuffix << ",\"a\",@progbits\n";
-  else if (HasNonzeroInitializer)
-    Str << "\t.section\t.data" << SectionSuffix << ",\"aw\",@progbits\n";
-  else
-    Str << "\t.section\t.bss" << SectionSuffix << ",\"aw\",@nobits\n";
-
-  if (IsExternal)
-    Str << "\t.globl\t" << MangledName << "\n";
-
-  if (Align > 1)
-    Str << "\t.align\t" << Align << "\n";
-
-  Str << MangledName << ":\n";
-
-  if (HasNonzeroInitializer) {
-    for (VariableDeclaration::Initializer *Init : Initializers) {
-      switch (Init->getKind()) {
-      case VariableDeclaration::Initializer::DataInitializerKind: {
-        const auto Data = llvm::cast<VariableDeclaration::DataInitializer>(Init)
-                              ->getContents();
-        for (SizeT i = 0; i < Init->getNumBytes(); ++i) {
-          Str << "\t.byte\t" << (((unsigned)Data[i]) & 0xff) << "\n";
-        }
-        break;
-      }
-      case VariableDeclaration::Initializer::ZeroInitializerKind:
-        Str << "\t.zero\t" << Init->getNumBytes() << "\n";
-        break;
-      case VariableDeclaration::Initializer::RelocInitializerKind: {
-        const auto Reloc =
-            llvm::cast<VariableDeclaration::RelocInitializer>(Init);
-        Str << "\t.long\t";
-        Str << Reloc->getDeclaration()->mangleName(Ctx);
-        if (RelocOffsetT Offset = Reloc->getOffset()) {
-          if (Offset >= 0 || (Offset == INT32_MIN))
-            Str << " + " << Offset;
-          else
-            Str << " - " << -Offset;
-        }
-        Str << "\n";
-        break;
-      }
-      }
-    }
-  } else
-    // NOTE: for non-constant zero initializers, this is BSS (no bits),
-    // so an ELF writer would not write to the file, and only track
-    // virtual offsets, but the .s writer still needs this .zero and
-    // cannot simply use the .size to advance offsets.
-    Str << "\t.zero\t" << Size << "\n";
-
-  Str << "\t.size\t" << MangledName << ", " << Size << "\n";
-}
-
 void TargetDataX8632::lowerGlobals(
     std::unique_ptr<VariableDeclarationList> Vars) {
   switch (Ctx->getFlags().getOutFileType()) {
@@ -5106,7 +5030,7 @@
     OstreamLocker L(Ctx);
     for (const VariableDeclaration *Var : *Vars) {
       if (GlobalContext::matchSymbolName(Var->getName(), TranslateOnly)) {
-        lowerGlobal(*Var);
+        emitGlobal(*Var);
       }
     }
   } break;
diff --git a/src/IceTargetLoweringX8632.h b/src/IceTargetLoweringX8632.h
index fe3612c..a921294 100644
--- a/src/IceTargetLoweringX8632.h
+++ b/src/IceTargetLoweringX8632.h
@@ -594,7 +594,6 @@
   explicit TargetDataX8632(GlobalContext *Ctx);
 
 private:
-  void lowerGlobal(const VariableDeclaration &Var);
   ~TargetDataX8632() override {}
   template <typename T> static void emitConstantPool(GlobalContext *Ctx);
 };