Fixed alignment of code sections in the JIT mode. Added a test to the JITMemoryManager.

llvm-svn: 185421
diff --git a/llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp b/llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp
index 6a1db16..94db245 100644
--- a/llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp
+++ b/llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp
@@ -468,7 +468,11 @@
       // Grow the required block size to account for the block header
       Size += sizeof(*CurBlock);
 
-      // FIXME: Alignement handling.
+      // Alignment handling.
+      if (!Alignment)
+        Alignment = 16;
+      Size += Alignment - 1;
+
       FreeRangeHeader* candidateBlock = FreeMemoryList;
       FreeRangeHeader* head = FreeMemoryList;
       FreeRangeHeader* iter = head->Next;
@@ -500,7 +504,8 @@
       FreeMemoryList = candidateBlock->AllocateBlock();
       // Release the memory at the end of this block that isn't needed.
       FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
-      return (uint8_t *)(CurBlock + 1);
+      uintptr_t unalignedAddr = (uintptr_t)CurBlock + sizeof(*CurBlock);
+      return (uint8_t*)RoundUpToAlignment((uint64_t)unalignedAddr, Alignment);
     }
 
     /// allocateDataSection - Allocate memory for a data section.
diff --git a/llvm/unittests/ExecutionEngine/JIT/JITMemoryManagerTest.cpp b/llvm/unittests/ExecutionEngine/JIT/JITMemoryManagerTest.cpp
index 21ca0d4..c06b89c 100644
--- a/llvm/unittests/ExecutionEngine/JIT/JITMemoryManagerTest.cpp
+++ b/llvm/unittests/ExecutionEngine/JIT/JITMemoryManagerTest.cpp
@@ -277,4 +277,27 @@
   EXPECT_EQ(3U, MemMgr->GetNumStubSlabs());
 }
 
+// Check section allocation and alignment
+TEST(JITMemoryManagerTest, AllocateSection) {
+  OwningPtr<JITMemoryManager> MemMgr(
+      JITMemoryManager::CreateDefaultMemManager());
+  uint8_t *code1 = MemMgr->allocateCodeSection(256, 0, 1);

+  uint8_t *data1 = MemMgr->allocateDataSection(256, 16, 2, true);

+  uint8_t *code2 = MemMgr->allocateCodeSection(257, 32, 3);

+  uint8_t *data2 = MemMgr->allocateDataSection(256, 64, 4, false);

+  uint8_t *code3 = MemMgr->allocateCodeSection(258, 64, 5);

+

+  EXPECT_NE((uint8_t*)0, code1);

+  EXPECT_NE((uint8_t*)0, code2);

+  EXPECT_NE((uint8_t*)0, data1);

+  EXPECT_NE((uint8_t*)0, data2);

+

+  // Check alignment

+  EXPECT_EQ((uint64_t)code1 & 0xf, 0);

+  EXPECT_EQ((uint64_t)code2 & 0x1f, 0);

+  EXPECT_EQ((uint64_t)code3 & 0x3f, 0);

+  EXPECT_EQ((uint64_t)data1 & 0xf, 0);

+  EXPECT_EQ((uint64_t)data2 & 0x3f, 0);

+}
+
 }