JITMemoryManager.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. //===-- JITMemoryManager.cpp - Memory Allocator for JIT'd code ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the DefaultJITMemoryManager class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ExecutionEngine/JITMemoryManager.h"
  14. #include "llvm/ADT/SmallPtrSet.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/ADT/Twine.h"
  17. #include "llvm/Config/config.h"
  18. #include "llvm/IR/GlobalValue.h"
  19. #include "llvm/Support/Allocator.h"
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/DynamicLibrary.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/Memory.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include <cassert>
  27. #include <climits>
  28. #include <cstring>
  29. #include <vector>
  30. #if defined(__linux__)
  31. #if defined(HAVE_SYS_STAT_H)
  32. #include <sys/stat.h>
  33. #endif
  34. #include <fcntl.h>
  35. #include <unistd.h>
  36. #endif
  37. using namespace llvm;
  38. #define DEBUG_TYPE "jit"
  39. STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
  40. JITMemoryManager::~JITMemoryManager() {}
  41. //===----------------------------------------------------------------------===//
  42. // Memory Block Implementation.
  43. //===----------------------------------------------------------------------===//
  44. namespace {
  45. /// MemoryRangeHeader - For a range of memory, this is the header that we put
  46. /// on the block of memory. It is carefully crafted to be one word of memory.
  47. /// Allocated blocks have just this header, free'd blocks have FreeRangeHeader
  48. /// which starts with this.
  49. struct FreeRangeHeader;
  50. struct MemoryRangeHeader {
  51. /// ThisAllocated - This is true if this block is currently allocated. If
  52. /// not, this can be converted to a FreeRangeHeader.
  53. unsigned ThisAllocated : 1;
  54. /// PrevAllocated - Keep track of whether the block immediately before us is
  55. /// allocated. If not, the word immediately before this header is the size
  56. /// of the previous block.
  57. unsigned PrevAllocated : 1;
  58. /// BlockSize - This is the size in bytes of this memory block,
  59. /// including this header.
  60. uintptr_t BlockSize : (sizeof(intptr_t)*CHAR_BIT - 2);
  61. /// getBlockAfter - Return the memory block immediately after this one.
  62. ///
  63. MemoryRangeHeader &getBlockAfter() const {
  64. return *reinterpret_cast<MemoryRangeHeader *>(
  65. reinterpret_cast<char*>(
  66. const_cast<MemoryRangeHeader *>(this))+BlockSize);
  67. }
  68. /// getFreeBlockBefore - If the block before this one is free, return it,
  69. /// otherwise return null.
  70. FreeRangeHeader *getFreeBlockBefore() const {
  71. if (PrevAllocated) return nullptr;
  72. intptr_t PrevSize = reinterpret_cast<intptr_t *>(
  73. const_cast<MemoryRangeHeader *>(this))[-1];
  74. return reinterpret_cast<FreeRangeHeader *>(
  75. reinterpret_cast<char*>(
  76. const_cast<MemoryRangeHeader *>(this))-PrevSize);
  77. }
  78. /// FreeBlock - Turn an allocated block into a free block, adjusting
  79. /// bits in the object headers, and adding an end of region memory block.
  80. FreeRangeHeader *FreeBlock(FreeRangeHeader *FreeList);
  81. /// TrimAllocationToSize - If this allocated block is significantly larger
  82. /// than NewSize, split it into two pieces (where the former is NewSize
  83. /// bytes, including the header), and add the new block to the free list.
  84. FreeRangeHeader *TrimAllocationToSize(FreeRangeHeader *FreeList,
  85. uint64_t NewSize);
  86. };
  87. /// FreeRangeHeader - For a memory block that isn't already allocated, this
  88. /// keeps track of the current block and has a pointer to the next free block.
  89. /// Free blocks are kept on a circularly linked list.
  90. struct FreeRangeHeader : public MemoryRangeHeader {
  91. FreeRangeHeader *Prev;
  92. FreeRangeHeader *Next;
  93. /// getMinBlockSize - Get the minimum size for a memory block. Blocks
  94. /// smaller than this size cannot be created.
  95. static unsigned getMinBlockSize() {
  96. return sizeof(FreeRangeHeader)+sizeof(intptr_t);
  97. }
  98. /// SetEndOfBlockSizeMarker - The word at the end of every free block is
  99. /// known to be the size of the free block. Set it for this block.
  100. void SetEndOfBlockSizeMarker() {
  101. void *EndOfBlock = (char*)this + BlockSize;
  102. ((intptr_t *)EndOfBlock)[-1] = BlockSize;
  103. }
  104. FreeRangeHeader *RemoveFromFreeList() {
  105. assert(Next->Prev == this && Prev->Next == this && "Freelist broken!");
  106. Next->Prev = Prev;
  107. return Prev->Next = Next;
  108. }
  109. void AddToFreeList(FreeRangeHeader *FreeList) {
  110. Next = FreeList;
  111. Prev = FreeList->Prev;
  112. Prev->Next = this;
  113. Next->Prev = this;
  114. }
  115. /// GrowBlock - The block after this block just got deallocated. Merge it
  116. /// into the current block.
  117. void GrowBlock(uintptr_t NewSize);
  118. /// AllocateBlock - Mark this entire block allocated, updating freelists
  119. /// etc. This returns a pointer to the circular free-list.
  120. FreeRangeHeader *AllocateBlock();
  121. };
  122. }
  123. /// AllocateBlock - Mark this entire block allocated, updating freelists
  124. /// etc. This returns a pointer to the circular free-list.
  125. FreeRangeHeader *FreeRangeHeader::AllocateBlock() {
  126. assert(!ThisAllocated && !getBlockAfter().PrevAllocated &&
  127. "Cannot allocate an allocated block!");
  128. // Mark this block allocated.
  129. ThisAllocated = 1;
  130. getBlockAfter().PrevAllocated = 1;
  131. // Remove it from the free list.
  132. return RemoveFromFreeList();
  133. }
  134. /// FreeBlock - Turn an allocated block into a free block, adjusting
  135. /// bits in the object headers, and adding an end of region memory block.
  136. /// If possible, coalesce this block with neighboring blocks. Return the
  137. /// FreeRangeHeader to allocate from.
  138. FreeRangeHeader *MemoryRangeHeader::FreeBlock(FreeRangeHeader *FreeList) {
  139. MemoryRangeHeader *FollowingBlock = &getBlockAfter();
  140. assert(ThisAllocated && "This block is already free!");
  141. assert(FollowingBlock->PrevAllocated && "Flags out of sync!");
  142. FreeRangeHeader *FreeListToReturn = FreeList;
  143. // If the block after this one is free, merge it into this block.
  144. if (!FollowingBlock->ThisAllocated) {
  145. FreeRangeHeader &FollowingFreeBlock = *(FreeRangeHeader *)FollowingBlock;
  146. // "FreeList" always needs to be a valid free block. If we're about to
  147. // coalesce with it, update our notion of what the free list is.
  148. if (&FollowingFreeBlock == FreeList) {
  149. FreeList = FollowingFreeBlock.Next;
  150. FreeListToReturn = nullptr;
  151. assert(&FollowingFreeBlock != FreeList && "No tombstone block?");
  152. }
  153. FollowingFreeBlock.RemoveFromFreeList();
  154. // Include the following block into this one.
  155. BlockSize += FollowingFreeBlock.BlockSize;
  156. FollowingBlock = &FollowingFreeBlock.getBlockAfter();
  157. // Tell the block after the block we are coalescing that this block is
  158. // allocated.
  159. FollowingBlock->PrevAllocated = 1;
  160. }
  161. assert(FollowingBlock->ThisAllocated && "Missed coalescing?");
  162. if (FreeRangeHeader *PrevFreeBlock = getFreeBlockBefore()) {
  163. PrevFreeBlock->GrowBlock(PrevFreeBlock->BlockSize + BlockSize);
  164. return FreeListToReturn ? FreeListToReturn : PrevFreeBlock;
  165. }
  166. // Otherwise, mark this block free.
  167. FreeRangeHeader &FreeBlock = *(FreeRangeHeader*)this;
  168. FollowingBlock->PrevAllocated = 0;
  169. FreeBlock.ThisAllocated = 0;
  170. // Link this into the linked list of free blocks.
  171. FreeBlock.AddToFreeList(FreeList);
  172. // Add a marker at the end of the block, indicating the size of this free
  173. // block.
  174. FreeBlock.SetEndOfBlockSizeMarker();
  175. return FreeListToReturn ? FreeListToReturn : &FreeBlock;
  176. }
  177. /// GrowBlock - The block after this block just got deallocated. Merge it
  178. /// into the current block.
  179. void FreeRangeHeader::GrowBlock(uintptr_t NewSize) {
  180. assert(NewSize > BlockSize && "Not growing block?");
  181. BlockSize = NewSize;
  182. SetEndOfBlockSizeMarker();
  183. getBlockAfter().PrevAllocated = 0;
  184. }
  185. /// TrimAllocationToSize - If this allocated block is significantly larger
  186. /// than NewSize, split it into two pieces (where the former is NewSize
  187. /// bytes, including the header), and add the new block to the free list.
  188. FreeRangeHeader *MemoryRangeHeader::
  189. TrimAllocationToSize(FreeRangeHeader *FreeList, uint64_t NewSize) {
  190. assert(ThisAllocated && getBlockAfter().PrevAllocated &&
  191. "Cannot deallocate part of an allocated block!");
  192. // Don't allow blocks to be trimmed below minimum required size
  193. NewSize = std::max<uint64_t>(FreeRangeHeader::getMinBlockSize(), NewSize);
  194. // Round up size for alignment of header.
  195. unsigned HeaderAlign = __alignof(FreeRangeHeader);
  196. NewSize = (NewSize+ (HeaderAlign-1)) & ~(HeaderAlign-1);
  197. // Size is now the size of the block we will remove from the start of the
  198. // current block.
  199. assert(NewSize <= BlockSize &&
  200. "Allocating more space from this block than exists!");
  201. // If splitting this block will cause the remainder to be too small, do not
  202. // split the block.
  203. if (BlockSize <= NewSize+FreeRangeHeader::getMinBlockSize())
  204. return FreeList;
  205. // Otherwise, we splice the required number of bytes out of this block, form
  206. // a new block immediately after it, then mark this block allocated.
  207. MemoryRangeHeader &FormerNextBlock = getBlockAfter();
  208. // Change the size of this block.
  209. BlockSize = NewSize;
  210. // Get the new block we just sliced out and turn it into a free block.
  211. FreeRangeHeader &NewNextBlock = (FreeRangeHeader &)getBlockAfter();
  212. NewNextBlock.BlockSize = (char*)&FormerNextBlock - (char*)&NewNextBlock;
  213. NewNextBlock.ThisAllocated = 0;
  214. NewNextBlock.PrevAllocated = 1;
  215. NewNextBlock.SetEndOfBlockSizeMarker();
  216. FormerNextBlock.PrevAllocated = 0;
  217. NewNextBlock.AddToFreeList(FreeList);
  218. return &NewNextBlock;
  219. }
  220. //===----------------------------------------------------------------------===//
  221. // Memory Block Implementation.
  222. //===----------------------------------------------------------------------===//
  223. namespace {
  224. class DefaultJITMemoryManager;
  225. class JITAllocator {
  226. DefaultJITMemoryManager &JMM;
  227. public:
  228. JITAllocator(DefaultJITMemoryManager &jmm) : JMM(jmm) { }
  229. void *Allocate(size_t Size, size_t /*Alignment*/);
  230. void Deallocate(void *Slab, size_t Size);
  231. };
  232. /// DefaultJITMemoryManager - Manage memory for the JIT code generation.
  233. /// This splits a large block of MAP_NORESERVE'd memory into two
  234. /// sections, one for function stubs, one for the functions themselves. We
  235. /// have to do this because we may need to emit a function stub while in the
  236. /// middle of emitting a function, and we don't know how large the function we
  237. /// are emitting is.
  238. class DefaultJITMemoryManager : public JITMemoryManager {
  239. public:
  240. /// DefaultCodeSlabSize - When we have to go map more memory, we allocate at
  241. /// least this much unless more is requested. Currently, in 512k slabs.
  242. static const size_t DefaultCodeSlabSize = 512 * 1024;
  243. /// DefaultSlabSize - Allocate globals and stubs into slabs of 64K (probably
  244. /// 16 pages) unless we get an allocation above SizeThreshold.
  245. static const size_t DefaultSlabSize = 64 * 1024;
  246. /// DefaultSizeThreshold - For any allocation larger than 16K (probably
  247. /// 4 pages), we should allocate a separate slab to avoid wasted space at
  248. /// the end of a normal slab.
  249. static const size_t DefaultSizeThreshold = 16 * 1024;
  250. private:
  251. // Whether to poison freed memory.
  252. bool PoisonMemory;
  253. /// LastSlab - This points to the last slab allocated and is used as the
  254. /// NearBlock parameter to AllocateRWX so that we can attempt to lay out all
  255. /// stubs, data, and code contiguously in memory. In general, however, this
  256. /// is not possible because the NearBlock parameter is ignored on Windows
  257. /// platforms and even on Unix it works on a best-effort pasis.
  258. sys::MemoryBlock LastSlab;
  259. // Memory slabs allocated by the JIT. We refer to them as slabs so we don't
  260. // confuse them with the blocks of memory described above.
  261. std::vector<sys::MemoryBlock> CodeSlabs;
  262. BumpPtrAllocatorImpl<JITAllocator, DefaultSlabSize,
  263. DefaultSizeThreshold> StubAllocator;
  264. BumpPtrAllocatorImpl<JITAllocator, DefaultSlabSize,
  265. DefaultSizeThreshold> DataAllocator;
  266. // Circular list of free blocks.
  267. FreeRangeHeader *FreeMemoryList;
  268. // When emitting code into a memory block, this is the block.
  269. MemoryRangeHeader *CurBlock;
  270. uint8_t *GOTBase; // Target Specific reserved memory
  271. public:
  272. DefaultJITMemoryManager();
  273. ~DefaultJITMemoryManager();
  274. /// allocateNewSlab - Allocates a new MemoryBlock and remembers it as the
  275. /// last slab it allocated, so that subsequent allocations follow it.
  276. sys::MemoryBlock allocateNewSlab(size_t size);
  277. /// getPointerToNamedFunction - This method returns the address of the
  278. /// specified function by using the dlsym function call.
  279. void *getPointerToNamedFunction(const std::string &Name,
  280. bool AbortOnFailure = true) override;
  281. void AllocateGOT() override;
  282. // Testing methods.
  283. bool CheckInvariants(std::string &ErrorStr) override;
  284. size_t GetDefaultCodeSlabSize() override { return DefaultCodeSlabSize; }
  285. size_t GetDefaultDataSlabSize() override { return DefaultSlabSize; }
  286. size_t GetDefaultStubSlabSize() override { return DefaultSlabSize; }
  287. unsigned GetNumCodeSlabs() override { return CodeSlabs.size(); }
  288. unsigned GetNumDataSlabs() override { return DataAllocator.GetNumSlabs(); }
  289. unsigned GetNumStubSlabs() override { return StubAllocator.GetNumSlabs(); }
  290. /// startFunctionBody - When a function starts, allocate a block of free
  291. /// executable memory, returning a pointer to it and its actual size.
  292. uint8_t *startFunctionBody(const Function *F,
  293. uintptr_t &ActualSize) override {
  294. FreeRangeHeader* candidateBlock = FreeMemoryList;
  295. FreeRangeHeader* head = FreeMemoryList;
  296. FreeRangeHeader* iter = head->Next;
  297. uintptr_t largest = candidateBlock->BlockSize;
  298. // Search for the largest free block
  299. while (iter != head) {
  300. if (iter->BlockSize > largest) {
  301. largest = iter->BlockSize;
  302. candidateBlock = iter;
  303. }
  304. iter = iter->Next;
  305. }
  306. largest = largest - sizeof(MemoryRangeHeader);
  307. // If this block isn't big enough for the allocation desired, allocate
  308. // another block of memory and add it to the free list.
  309. if (largest < ActualSize ||
  310. largest <= FreeRangeHeader::getMinBlockSize()) {
  311. DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
  312. candidateBlock = allocateNewCodeSlab((size_t)ActualSize);
  313. }
  314. // Select this candidate block for allocation
  315. CurBlock = candidateBlock;
  316. // Allocate the entire memory block.
  317. FreeMemoryList = candidateBlock->AllocateBlock();
  318. ActualSize = CurBlock->BlockSize - sizeof(MemoryRangeHeader);
  319. return (uint8_t *)(CurBlock + 1);
  320. }
  321. /// allocateNewCodeSlab - Helper method to allocate a new slab of code
  322. /// memory from the OS and add it to the free list. Returns the new
  323. /// FreeRangeHeader at the base of the slab.
  324. FreeRangeHeader *allocateNewCodeSlab(size_t MinSize) {
  325. // If the user needs at least MinSize free memory, then we account for
  326. // two MemoryRangeHeaders: the one in the user's block, and the one at the
  327. // end of the slab.
  328. size_t PaddedMin = MinSize + 2 * sizeof(MemoryRangeHeader);
  329. size_t SlabSize = std::max(DefaultCodeSlabSize, PaddedMin);
  330. sys::MemoryBlock B = allocateNewSlab(SlabSize);
  331. CodeSlabs.push_back(B);
  332. char *MemBase = (char*)(B.base());
  333. // Put a tiny allocated block at the end of the memory chunk, so when
  334. // FreeBlock calls getBlockAfter it doesn't fall off the end.
  335. MemoryRangeHeader *EndBlock =
  336. (MemoryRangeHeader*)(MemBase + B.size()) - 1;
  337. EndBlock->ThisAllocated = 1;
  338. EndBlock->PrevAllocated = 0;
  339. EndBlock->BlockSize = sizeof(MemoryRangeHeader);
  340. // Start out with a vast new block of free memory.
  341. FreeRangeHeader *NewBlock = (FreeRangeHeader*)MemBase;
  342. NewBlock->ThisAllocated = 0;
  343. // Make sure getFreeBlockBefore doesn't look into unmapped memory.
  344. NewBlock->PrevAllocated = 1;
  345. NewBlock->BlockSize = (uintptr_t)EndBlock - (uintptr_t)NewBlock;
  346. NewBlock->SetEndOfBlockSizeMarker();
  347. NewBlock->AddToFreeList(FreeMemoryList);
  348. assert(NewBlock->BlockSize - sizeof(MemoryRangeHeader) >= MinSize &&
  349. "The block was too small!");
  350. return NewBlock;
  351. }
  352. /// endFunctionBody - The function F is now allocated, and takes the memory
  353. /// in the range [FunctionStart,FunctionEnd).
  354. void endFunctionBody(const Function *F, uint8_t *FunctionStart,
  355. uint8_t *FunctionEnd) override {
  356. assert(FunctionEnd > FunctionStart);
  357. assert(FunctionStart == (uint8_t *)(CurBlock+1) &&
  358. "Mismatched function start/end!");
  359. uintptr_t BlockSize = FunctionEnd - (uint8_t *)CurBlock;
  360. // Release the memory at the end of this block that isn't needed.
  361. FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
  362. }
  363. /// allocateSpace - Allocate a memory block of the given size. This method
  364. /// cannot be called between calls to startFunctionBody and endFunctionBody.
  365. uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) override {
  366. CurBlock = FreeMemoryList;
  367. FreeMemoryList = FreeMemoryList->AllocateBlock();
  368. uint8_t *result = (uint8_t *)(CurBlock + 1);
  369. if (Alignment == 0) Alignment = 1;
  370. result = (uint8_t*)(((intptr_t)result+Alignment-1) &
  371. ~(intptr_t)(Alignment-1));
  372. uintptr_t BlockSize = result + Size - (uint8_t *)CurBlock;
  373. FreeMemoryList =CurBlock->TrimAllocationToSize(FreeMemoryList, BlockSize);
  374. return result;
  375. }
  376. /// allocateStub - Allocate memory for a function stub.
  377. uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
  378. unsigned Alignment) override {
  379. return (uint8_t*)StubAllocator.Allocate(StubSize, Alignment);
  380. }
  381. /// allocateGlobal - Allocate memory for a global.
  382. uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) override {
  383. return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
  384. }
  385. /// allocateCodeSection - Allocate memory for a code section.
  386. uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
  387. unsigned SectionID,
  388. StringRef SectionName) override {
  389. // Grow the required block size to account for the block header
  390. Size += sizeof(*CurBlock);
  391. // Alignment handling.
  392. if (!Alignment)
  393. Alignment = 16;
  394. Size += Alignment - 1;
  395. FreeRangeHeader* candidateBlock = FreeMemoryList;
  396. FreeRangeHeader* head = FreeMemoryList;
  397. FreeRangeHeader* iter = head->Next;
  398. uintptr_t largest = candidateBlock->BlockSize;
  399. // Search for the largest free block.
  400. while (iter != head) {
  401. if (iter->BlockSize > largest) {
  402. largest = iter->BlockSize;
  403. candidateBlock = iter;
  404. }
  405. iter = iter->Next;
  406. }
  407. largest = largest - sizeof(MemoryRangeHeader);
  408. // If this block isn't big enough for the allocation desired, allocate
  409. // another block of memory and add it to the free list.
  410. if (largest < Size || largest <= FreeRangeHeader::getMinBlockSize()) {
  411. DEBUG(dbgs() << "JIT: Allocating another slab of memory for function.");
  412. candidateBlock = allocateNewCodeSlab((size_t)Size);
  413. }
  414. // Select this candidate block for allocation
  415. CurBlock = candidateBlock;
  416. // Allocate the entire memory block.
  417. FreeMemoryList = candidateBlock->AllocateBlock();
  418. // Release the memory at the end of this block that isn't needed.
  419. FreeMemoryList = CurBlock->TrimAllocationToSize(FreeMemoryList, Size);
  420. uintptr_t unalignedAddr = (uintptr_t)CurBlock + sizeof(*CurBlock);
  421. return (uint8_t*)RoundUpToAlignment((uint64_t)unalignedAddr, Alignment);
  422. }
  423. /// allocateDataSection - Allocate memory for a data section.
  424. uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
  425. unsigned SectionID, StringRef SectionName,
  426. bool IsReadOnly) override {
  427. return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
  428. }
  429. bool finalizeMemory(std::string *ErrMsg) override {
  430. return false;
  431. }
  432. uint8_t *getGOTBase() const override {
  433. return GOTBase;
  434. }
  435. void deallocateBlock(void *Block) {
  436. // Find the block that is allocated for this function.
  437. MemoryRangeHeader *MemRange = static_cast<MemoryRangeHeader*>(Block) - 1;
  438. assert(MemRange->ThisAllocated && "Block isn't allocated!");
  439. // Fill the buffer with garbage!
  440. if (PoisonMemory) {
  441. memset(MemRange+1, 0xCD, MemRange->BlockSize-sizeof(*MemRange));
  442. }
  443. // Free the memory.
  444. FreeMemoryList = MemRange->FreeBlock(FreeMemoryList);
  445. }
  446. /// deallocateFunctionBody - Deallocate all memory for the specified
  447. /// function body.
  448. void deallocateFunctionBody(void *Body) override {
  449. if (Body) deallocateBlock(Body);
  450. }
  451. /// setMemoryWritable - When code generation is in progress,
  452. /// the code pages may need permissions changed.
  453. void setMemoryWritable() override {
  454. for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
  455. sys::Memory::setWritable(CodeSlabs[i]);
  456. }
  457. /// setMemoryExecutable - When code generation is done and we're ready to
  458. /// start execution, the code pages may need permissions changed.
  459. void setMemoryExecutable() override {
  460. for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
  461. sys::Memory::setExecutable(CodeSlabs[i]);
  462. }
  463. /// setPoisonMemory - Controls whether we write garbage over freed memory.
  464. ///
  465. void setPoisonMemory(bool poison) override {
  466. PoisonMemory = poison;
  467. }
  468. };
  469. }
  470. void *JITAllocator::Allocate(size_t Size, size_t /*Alignment*/) {
  471. sys::MemoryBlock B = JMM.allocateNewSlab(Size);
  472. return B.base();
  473. }
  474. void JITAllocator::Deallocate(void *Slab, size_t Size) {
  475. sys::MemoryBlock B(Slab, Size);
  476. sys::Memory::ReleaseRWX(B);
  477. }
  478. DefaultJITMemoryManager::DefaultJITMemoryManager()
  479. :
  480. #ifdef NDEBUG
  481. PoisonMemory(false),
  482. #else
  483. PoisonMemory(true),
  484. #endif
  485. LastSlab(nullptr, 0), StubAllocator(*this), DataAllocator(*this) {
  486. // Allocate space for code.
  487. sys::MemoryBlock MemBlock = allocateNewSlab(DefaultCodeSlabSize);
  488. CodeSlabs.push_back(MemBlock);
  489. uint8_t *MemBase = (uint8_t*)MemBlock.base();
  490. // We set up the memory chunk with 4 mem regions, like this:
  491. // [ START
  492. // [ Free #0 ] -> Large space to allocate functions from.
  493. // [ Allocated #1 ] -> Tiny space to separate regions.
  494. // [ Free #2 ] -> Tiny space so there is always at least 1 free block.
  495. // [ Allocated #3 ] -> Tiny space to prevent looking past end of block.
  496. // END ]
  497. //
  498. // The last three blocks are never deallocated or touched.
  499. // Add MemoryRangeHeader to the end of the memory region, indicating that
  500. // the space after the block of memory is allocated. This is block #3.
  501. MemoryRangeHeader *Mem3 = (MemoryRangeHeader*)(MemBase+MemBlock.size())-1;
  502. Mem3->ThisAllocated = 1;
  503. Mem3->PrevAllocated = 0;
  504. Mem3->BlockSize = sizeof(MemoryRangeHeader);
  505. /// Add a tiny free region so that the free list always has one entry.
  506. FreeRangeHeader *Mem2 =
  507. (FreeRangeHeader *)(((char*)Mem3)-FreeRangeHeader::getMinBlockSize());
  508. Mem2->ThisAllocated = 0;
  509. Mem2->PrevAllocated = 1;
  510. Mem2->BlockSize = FreeRangeHeader::getMinBlockSize();
  511. Mem2->SetEndOfBlockSizeMarker();
  512. Mem2->Prev = Mem2; // Mem2 *is* the free list for now.
  513. Mem2->Next = Mem2;
  514. /// Add a tiny allocated region so that Mem2 is never coalesced away.
  515. MemoryRangeHeader *Mem1 = (MemoryRangeHeader*)Mem2-1;
  516. Mem1->ThisAllocated = 1;
  517. Mem1->PrevAllocated = 0;
  518. Mem1->BlockSize = sizeof(MemoryRangeHeader);
  519. // Add a FreeRangeHeader to the start of the function body region, indicating
  520. // that the space is free. Mark the previous block allocated so we never look
  521. // at it.
  522. FreeRangeHeader *Mem0 = (FreeRangeHeader*)MemBase;
  523. Mem0->ThisAllocated = 0;
  524. Mem0->PrevAllocated = 1;
  525. Mem0->BlockSize = (char*)Mem1-(char*)Mem0;
  526. Mem0->SetEndOfBlockSizeMarker();
  527. Mem0->AddToFreeList(Mem2);
  528. // Start out with the freelist pointing to Mem0.
  529. FreeMemoryList = Mem0;
  530. GOTBase = nullptr;
  531. }
  532. void DefaultJITMemoryManager::AllocateGOT() {
  533. assert(!GOTBase && "Cannot allocate the got multiple times");
  534. GOTBase = new uint8_t[sizeof(void*) * 8192];
  535. HasGOT = true;
  536. }
  537. DefaultJITMemoryManager::~DefaultJITMemoryManager() {
  538. for (unsigned i = 0, e = CodeSlabs.size(); i != e; ++i)
  539. sys::Memory::ReleaseRWX(CodeSlabs[i]);
  540. delete[] GOTBase;
  541. }
  542. sys::MemoryBlock DefaultJITMemoryManager::allocateNewSlab(size_t size) {
  543. // Allocate a new block close to the last one.
  544. std::string ErrMsg;
  545. sys::MemoryBlock *LastSlabPtr = LastSlab.base() ? &LastSlab : nullptr;
  546. sys::MemoryBlock B = sys::Memory::AllocateRWX(size, LastSlabPtr, &ErrMsg);
  547. if (!B.base()) {
  548. report_fatal_error("Allocation failed when allocating new memory in the"
  549. " JIT\n" + Twine(ErrMsg));
  550. }
  551. LastSlab = B;
  552. ++NumSlabs;
  553. // Initialize the slab to garbage when debugging.
  554. if (PoisonMemory) {
  555. memset(B.base(), 0xCD, B.size());
  556. }
  557. return B;
  558. }
  559. /// CheckInvariants - For testing only. Return "" if all internal invariants
  560. /// are preserved, and a helpful error message otherwise. For free and
  561. /// allocated blocks, make sure that adding BlockSize gives a valid block.
  562. /// For free blocks, make sure they're in the free list and that their end of
  563. /// block size marker is correct. This function should return an error before
  564. /// accessing bad memory. This function is defined here instead of in
  565. /// JITMemoryManagerTest.cpp so that we don't have to expose all of the
  566. /// implementation details of DefaultJITMemoryManager.
  567. bool DefaultJITMemoryManager::CheckInvariants(std::string &ErrorStr) {
  568. raw_string_ostream Err(ErrorStr);
  569. // Construct a the set of FreeRangeHeader pointers so we can query it
  570. // efficiently.
  571. llvm::SmallPtrSet<MemoryRangeHeader*, 16> FreeHdrSet;
  572. FreeRangeHeader* FreeHead = FreeMemoryList;
  573. FreeRangeHeader* FreeRange = FreeHead;
  574. do {
  575. // Check that the free range pointer is in the blocks we've allocated.
  576. bool Found = false;
  577. for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
  578. E = CodeSlabs.end(); I != E && !Found; ++I) {
  579. char *Start = (char*)I->base();
  580. char *End = Start + I->size();
  581. Found = (Start <= (char*)FreeRange && (char*)FreeRange < End);
  582. }
  583. if (!Found) {
  584. Err << "Corrupt free list; points to " << FreeRange;
  585. return false;
  586. }
  587. if (FreeRange->Next->Prev != FreeRange) {
  588. Err << "Next and Prev pointers do not match.";
  589. return false;
  590. }
  591. // Otherwise, add it to the set.
  592. FreeHdrSet.insert(FreeRange);
  593. FreeRange = FreeRange->Next;
  594. } while (FreeRange != FreeHead);
  595. // Go over each block, and look at each MemoryRangeHeader.
  596. for (std::vector<sys::MemoryBlock>::iterator I = CodeSlabs.begin(),
  597. E = CodeSlabs.end(); I != E; ++I) {
  598. char *Start = (char*)I->base();
  599. char *End = Start + I->size();
  600. // Check each memory range.
  601. for (MemoryRangeHeader *Hdr = (MemoryRangeHeader*)Start, *LastHdr = nullptr;
  602. Start <= (char*)Hdr && (char*)Hdr < End;
  603. Hdr = &Hdr->getBlockAfter()) {
  604. if (Hdr->ThisAllocated == 0) {
  605. // Check that this range is in the free list.
  606. if (!FreeHdrSet.count(Hdr)) {
  607. Err << "Found free header at " << Hdr << " that is not in free list.";
  608. return false;
  609. }
  610. // Now make sure the size marker at the end of the block is correct.
  611. uintptr_t *Marker = ((uintptr_t*)&Hdr->getBlockAfter()) - 1;
  612. if (!(Start <= (char*)Marker && (char*)Marker < End)) {
  613. Err << "Block size in header points out of current MemoryBlock.";
  614. return false;
  615. }
  616. if (Hdr->BlockSize != *Marker) {
  617. Err << "End of block size marker (" << *Marker << ") "
  618. << "and BlockSize (" << Hdr->BlockSize << ") don't match.";
  619. return false;
  620. }
  621. }
  622. if (LastHdr && LastHdr->ThisAllocated != Hdr->PrevAllocated) {
  623. Err << "Hdr->PrevAllocated (" << Hdr->PrevAllocated << ") != "
  624. << "LastHdr->ThisAllocated (" << LastHdr->ThisAllocated << ")";
  625. return false;
  626. } else if (!LastHdr && !Hdr->PrevAllocated) {
  627. Err << "The first header should have PrevAllocated true.";
  628. return false;
  629. }
  630. // Remember the last header.
  631. LastHdr = Hdr;
  632. }
  633. }
  634. // All invariants are preserved.
  635. return true;
  636. }
  637. //===----------------------------------------------------------------------===//
  638. // getPointerToNamedFunction() implementation.
  639. //===----------------------------------------------------------------------===//
  640. // AtExitHandlers - List of functions to call when the program exits,
  641. // registered with the atexit() library function.
  642. static std::vector<void (*)()> AtExitHandlers;
  643. /// runAtExitHandlers - Run any functions registered by the program's
  644. /// calls to atexit(3), which we intercept and store in
  645. /// AtExitHandlers.
  646. ///
  647. static void runAtExitHandlers() {
  648. while (!AtExitHandlers.empty()) {
  649. void (*Fn)() = AtExitHandlers.back();
  650. AtExitHandlers.pop_back();
  651. Fn();
  652. }
  653. }
  654. //===----------------------------------------------------------------------===//
  655. // Function stubs that are invoked instead of certain library calls
  656. //
  657. // Force the following functions to be linked in to anything that uses the
  658. // JIT. This is a hack designed to work around the all-too-clever Glibc
  659. // strategy of making these functions work differently when inlined vs. when
  660. // not inlined, and hiding their real definitions in a separate archive file
  661. // that the dynamic linker can't see. For more info, search for
  662. // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
  663. #if defined(__linux__) && defined(__GLIBC__)
  664. /* stat functions are redirecting to __xstat with a version number. On x86-64
  665. * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'stat'
  666. * available as an exported symbol, so we have to add it explicitly.
  667. */
  668. namespace {
  669. class StatSymbols {
  670. public:
  671. StatSymbols() {
  672. sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
  673. sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
  674. sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
  675. sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
  676. sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
  677. sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
  678. sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
  679. sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
  680. sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
  681. sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
  682. sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
  683. }
  684. };
  685. }
  686. static StatSymbols initStatSymbols;
  687. #endif // __linux__
  688. // jit_exit - Used to intercept the "exit" library call.
  689. static void jit_exit(int Status) {
  690. runAtExitHandlers(); // Run atexit handlers...
  691. exit(Status);
  692. }
  693. // jit_atexit - Used to intercept the "atexit" library call.
  694. static int jit_atexit(void (*Fn)()) {
  695. AtExitHandlers.push_back(Fn); // Take note of atexit handler...
  696. return 0; // Always successful
  697. }
  698. static int jit_noop() {
  699. return 0;
  700. }
  701. //===----------------------------------------------------------------------===//
  702. //
  703. /// getPointerToNamedFunction - This method returns the address of the specified
  704. /// function by using the dynamic loader interface. As such it is only useful
  705. /// for resolving library symbols, not code generated symbols.
  706. ///
  707. void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
  708. bool AbortOnFailure) {
  709. // Check to see if this is one of the functions we want to intercept. Note,
  710. // we cast to intptr_t here to silence a -pedantic warning that complains
  711. // about casting a function pointer to a normal pointer.
  712. if (Name == "exit") return (void*)(intptr_t)&jit_exit;
  713. if (Name == "atexit") return (void*)(intptr_t)&jit_atexit;
  714. // We should not invoke parent's ctors/dtors from generated main()!
  715. // On Mingw and Cygwin, the symbol __main is resolved to
  716. // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
  717. // (and register wrong callee's dtors with atexit(3)).
  718. // We expect ExecutionEngine::runStaticConstructorsDestructors()
  719. // is called before ExecutionEngine::runFunctionAsMain() is called.
  720. if (Name == "__main") return (void*)(intptr_t)&jit_noop;
  721. const char *NameStr = Name.c_str();
  722. // If this is an asm specifier, skip the sentinal.
  723. if (NameStr[0] == 1) ++NameStr;
  724. // If it's an external function, look it up in the process image...
  725. void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
  726. if (Ptr) return Ptr;
  727. // If it wasn't found and if it starts with an underscore ('_') character,
  728. // try again without the underscore.
  729. if (NameStr[0] == '_') {
  730. Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
  731. if (Ptr) return Ptr;
  732. }
  733. // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf. These
  734. // are references to hidden visibility symbols that dlsym cannot resolve.
  735. // If we have one of these, strip off $LDBLStub and try again.
  736. #if defined(__APPLE__) && defined(__ppc__)
  737. if (Name.size() > 9 && Name[Name.size()-9] == '$' &&
  738. memcmp(&Name[Name.size()-8], "LDBLStub", 8) == 0) {
  739. // First try turning $LDBLStub into $LDBL128. If that fails, strip it off.
  740. // This mirrors logic in libSystemStubs.a.
  741. std::string Prefix = std::string(Name.begin(), Name.end()-9);
  742. if (void *Ptr = getPointerToNamedFunction(Prefix+"$LDBL128", false))
  743. return Ptr;
  744. if (void *Ptr = getPointerToNamedFunction(Prefix, false))
  745. return Ptr;
  746. }
  747. #endif
  748. if (AbortOnFailure) {
  749. report_fatal_error("Program used external function '"+Name+
  750. "' which could not be resolved!");
  751. }
  752. return nullptr;
  753. }
  754. JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
  755. return new DefaultJITMemoryManager();
  756. }
  757. const size_t DefaultJITMemoryManager::DefaultCodeSlabSize;
  758. const size_t DefaultJITMemoryManager::DefaultSlabSize;
  759. const size_t DefaultJITMemoryManager::DefaultSizeThreshold;