source: icGREP/icgrep-devel/icgrep/kernels/source_kernel.cpp @ 5474

Last change on this file since 5474 was 5474, checked in by nmedfort, 2 years ago

Eliminated ExecutionEngine? memory leak. Intentionally broke compatibility with prior versions to ensure unchecked in projects are restructured.

File size: 17.9 KB
Line 
1/*
2 *  Copyright (c) 2017 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5#include "source_kernel.h"
6#include <kernels/kernel_builder.h>
7#include <kernels/streamset.h>
8#include <sys/stat.h>
9#include <fcntl.h>
10
11using namespace llvm;
12
13inline static size_t round_up_to_nearest(const size_t x, const size_t y) {
14    return (((x - 1) | (y - 1)) + 1);
15}
16
17uint64_t file_size(const uint32_t fd) {
18    struct stat st;
19    if (LLVM_UNLIKELY(fstat(fd, &st) != 0)) {
20        st.st_size = 0;
21    }
22    return st.st_size;
23}
24
25namespace kernel {
26
27/// MMAP SOURCE KERNEL
28
29void MMapSourceKernel::linkExternalMethods(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
30    mFileSizeFunction = iBuilder->LinkFunction("file_size", &file_size);
31}
32
33void MMapSourceKernel::generateInitializeMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
34    BasicBlock * const emptyFile = iBuilder->CreateBasicBlock("EmptyFile");
35    BasicBlock * const nonEmptyFile = iBuilder->CreateBasicBlock("NonEmptyFile");
36    BasicBlock * const exit = iBuilder->CreateBasicBlock("Exit");
37    IntegerType * const sizeTy = iBuilder->getSizeTy();
38    assert (iBuilder->getKernel() == this);
39    Value * const fd = iBuilder->getScalarField("fileDescriptor");
40    assert (mFileSizeFunction);
41    Value * fileSize = iBuilder->CreateCall(mFileSizeFunction, fd);
42    fileSize = iBuilder->CreateZExtOrTrunc(fileSize, sizeTy);
43    if (mCodeUnitWidth > 8) {
44        fileSize = iBuilder->CreateUDiv(fileSize, iBuilder->getSize(mCodeUnitWidth / 8));
45    }
46    Value * const isEmpty = iBuilder->CreateICmpEQ(fileSize, ConstantInt::getNullValue(fileSize->getType()));
47    iBuilder->CreateUnlikelyCondBr(isEmpty, emptyFile, nonEmptyFile);
48    // we cannot mmap a 0 length file; just create a 1-page sized fake file buffer for simplicity
49    iBuilder->SetInsertPoint(emptyFile);
50    Constant * pageSize = iBuilder->getSize(getpagesize());
51    Value * fakeFileBuffer = iBuilder->CreateAnonymousMMap(pageSize);
52    iBuilder->CreateBr(exit);
53
54    iBuilder->SetInsertPoint(nonEmptyFile);
55    Value * fileBackedBuffer = iBuilder->CreateFileSourceMMap(fd, fileSize);
56    iBuilder->CreateBr(exit);
57
58    iBuilder->SetInsertPoint(exit);
59    PHINode * buffer = iBuilder->CreatePHI(fileBackedBuffer->getType(), 2);
60    buffer->addIncoming(fakeFileBuffer, emptyFile);
61    buffer->addIncoming(fileBackedBuffer, nonEmptyFile);
62    PHINode * size = iBuilder->CreatePHI(sizeTy, 2);
63    size->addIncoming(pageSize, emptyFile);
64    size->addIncoming(fileSize, nonEmptyFile);
65
66    iBuilder->setBaseAddress("sourceBuffer", buffer);
67    iBuilder->setBufferedSize("sourceBuffer", size);
68    iBuilder->setScalarField("readableBuffer", buffer);
69    iBuilder->setScalarField("fileSize", fileSize);
70    iBuilder->CreateMAdvise(buffer, fileSize, CBuilder::ADVICE_WILLNEED);
71
72}
73
74void MMapSourceKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
75
76    BasicBlock * dropPages = iBuilder->CreateBasicBlock("dropPages");
77    BasicBlock * processSegment = iBuilder->CreateBasicBlock("produceData");
78    BasicBlock * setTermination = iBuilder->CreateBasicBlock("setTermination");
79    BasicBlock * mmapSourceExit = iBuilder->CreateBasicBlock("mmapSourceExit");
80
81    // instruct the OS that it can safely drop any fully consumed pages
82    Value * consumed = iBuilder->getConsumedItemCount("sourceBuffer");
83    IntegerType * const consumedTy = cast<IntegerType>(consumed->getType());
84    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
85
86    DataLayout DL(iBuilder->getModule());
87    IntegerType * const intAddrTy = iBuilder->getIntPtrTy(DL);
88
89    // multiply the consumed count by the code unit size then mask off any partial pages
90    if (mCodeUnitWidth > 8) {
91        consumed = iBuilder->CreateMul(consumed, ConstantInt::get(consumedTy, mCodeUnitWidth / 8));
92    }
93    const auto pageSize = getpagesize();
94    if (LLVM_LIKELY((pageSize & (pageSize - 1)) == 0)) {
95        consumed = iBuilder->CreateAnd(consumed, ConstantExpr::getNeg(ConstantInt::get(consumedTy, pageSize)));
96    } else {
97        consumed = iBuilder->CreateSub(consumed, iBuilder->CreateURem(consumed, ConstantInt::get(consumedTy, pageSize)));
98    }
99
100    Value * sourceBuffer = iBuilder->getBaseAddress("sourceBuffer");
101    sourceBuffer = iBuilder->CreatePtrToInt(sourceBuffer, intAddrTy);
102    if (LLVM_UNLIKELY(intAddrTy->getBitWidth() > consumedTy->getBitWidth())) {
103        consumed = iBuilder->CreateZExt(consumed, intAddrTy);
104    } else if (LLVM_UNLIKELY(intAddrTy->getBitWidth() < consumedTy->getBitWidth())) {
105        sourceBuffer = iBuilder->CreateZExt(sourceBuffer, consumedTy);
106    }
107    Value * consumedBuffer = iBuilder->CreateAdd(sourceBuffer, consumed);
108    Value * readableBuffer = iBuilder->getScalarField("readableBuffer");
109    readableBuffer = iBuilder->CreatePtrToInt(readableBuffer, consumedBuffer->getType());
110    Value * unnecessaryBytes = iBuilder->CreateSub(consumedBuffer, readableBuffer);
111
112    // avoid calling madvise unless an actual page table change could occur
113    Value * hasPagesToDrop = iBuilder->CreateICmpEQ(unnecessaryBytes, ConstantInt::getNullValue(intAddrTy));
114    iBuilder->CreateLikelyCondBr(hasPagesToDrop, processSegment, dropPages);
115
116    iBuilder->SetInsertPoint(dropPages);
117    iBuilder->CreateMAdvise(iBuilder->CreateIntToPtr(readableBuffer, voidPtrTy), unnecessaryBytes, CBuilder::ADVICE_DONTNEED);
118    readableBuffer = iBuilder->CreateIntToPtr(iBuilder->CreateAdd(readableBuffer, unnecessaryBytes), voidPtrTy);
119    iBuilder->setScalarField("readableBuffer", readableBuffer);
120    iBuilder->CreateBr(processSegment);
121
122    // determine whether or not we've exhausted the file buffer
123    iBuilder->SetInsertPoint(processSegment);
124    ConstantInt * segmentItems = iBuilder->getSize(mSegmentBlocks * iBuilder->getBitBlockWidth());
125    Value * const fileSize = iBuilder->getScalarField("fileSize");
126    Value * const produced = iBuilder->CreateAdd(iBuilder->getProducedItemCount("sourceBuffer"), segmentItems);
127    Value * const lessThanFullSegment = iBuilder->CreateICmpULT(fileSize, produced);
128    iBuilder->CreateUnlikelyCondBr(lessThanFullSegment, setTermination, mmapSourceExit);
129    iBuilder->SetInsertPoint(setTermination);
130
131    iBuilder->setTerminationSignal();
132    iBuilder->CreateBr(mmapSourceExit);
133
134    // finally, set the "produced" count to reflect current position in the file
135    iBuilder->SetInsertPoint(mmapSourceExit);
136    PHINode * itemsRead = iBuilder->CreatePHI(produced->getType(), 2);
137    itemsRead->addIncoming(produced, processSegment);
138    itemsRead->addIncoming(fileSize, setTermination);
139    iBuilder->setProducedItemCount("sourceBuffer", itemsRead);
140}
141
142void MMapSourceKernel::generateFinalizeMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
143    iBuilder->CreateMUnmap(iBuilder->getBaseAddress("sourceBuffer"), iBuilder->getBufferedSize("sourceBuffer"));
144}
145
146MMapSourceKernel::MMapSourceKernel(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, unsigned blocksPerSegment, unsigned codeUnitWidth)
147: SegmentOrientedKernel("mmap_source" + std::to_string(blocksPerSegment) + "@" + std::to_string(codeUnitWidth),
148{},
149{Binding{iBuilder->getStreamSetTy(1, codeUnitWidth), "sourceBuffer"}},
150{Binding{iBuilder->getInt32Ty(), "fileDescriptor"}},
151{Binding{iBuilder->getSizeTy(), "fileSize"}}, {Binding{iBuilder->getVoidPtrTy(), "readableBuffer"}})
152, mSegmentBlocks(blocksPerSegment)
153, mCodeUnitWidth(codeUnitWidth)
154, mFileSizeFunction(nullptr) {
155
156}
157
158/// READ SOURCE KERNEL
159
160void ReadSourceKernel::generateInitializeMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
161    ConstantInt * const bufferSize = iBuilder->getSize(64 * getpagesize());
162    Value * const buffer = iBuilder->CreateCacheAlignedMalloc(bufferSize);
163    iBuilder->setScalarField("buffer", buffer);
164    iBuilder->setScalarField("capacity", bufferSize);
165    iBuilder->setBaseAddress("sourceBuffer", buffer);
166    iBuilder->setBufferedSize("sourceBuffer", iBuilder->getSize(0));
167}
168
169void ReadSourceKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
170
171    ConstantInt * const pageSize = iBuilder->getSize(getpagesize());
172    PointerType * const codeUnitPtrTy = IntegerType::get(iBuilder->getContext(), mCodeUnitWidth)->getPointerTo();
173    BasicBlock * const entryBlock = iBuilder->GetInsertBlock();
174    BasicBlock * const exhaustedBuffer = iBuilder->CreateBasicBlock("ExhaustedBuffer");
175    BasicBlock * const waitOnConsumers = iBuilder->CreateBasicBlock("WaitOnConsumers");
176    BasicBlock * const readData = iBuilder->CreateBasicBlock("ReadData");
177    BasicBlock * const stdInExit = iBuilder->CreateBasicBlock("StdInExit");
178
179    assert(iBuilder->getKernel() == this);
180
181    // Check whether we need to read another page of data
182    ConstantInt * const segmentSize = iBuilder->getSize(mSegmentBlocks * iBuilder->getBitBlockWidth());
183    Value * bufferedSize = iBuilder->getBufferedSize("sourceBuffer");
184    Value * const produced = iBuilder->getProducedItemCount("sourceBuffer");
185    Value * unreadSize = iBuilder->CreateSub(bufferedSize, produced);
186    iBuilder->CreateUnlikelyCondBr(iBuilder->CreateICmpULT(unreadSize, segmentSize), exhaustedBuffer, stdInExit);
187
188    // If so, it checks whether it can simply append another page to the existing buffer or whether
189    // we need to perform a copyback.
190
191    iBuilder->SetInsertPoint(exhaustedBuffer);
192
193    // Otherwise, we're going to have to perform a copy back...
194
195    // Let L be the logical buffer address (i.e., the position of the "first byte" of the input stream)
196    // and B be the address pointing to the beginning of our actual buffer. Check whether:
197
198    //     L + produced + pagesize < B + capacity
199
200    // If so, we can append to our existing buffer without impacting any subsequent kernel.
201
202    Value * inputStream = iBuilder->getRawOutputPointer("sourceBuffer", iBuilder->getInt32(0), iBuilder->getInt32(0));
203    inputStream = iBuilder->CreatePointerCast(inputStream, codeUnitPtrTy);
204    Value * const originalPtr = iBuilder->CreateGEP(inputStream, produced);
205
206    Value * const buffer = iBuilder->CreatePointerCast(iBuilder->getScalarField("buffer"), codeUnitPtrTy);
207    Value * const capacity = iBuilder->getScalarField("capacity");
208
209    Value * L = iBuilder->CreateGEP(originalPtr, pageSize);
210
211//    iBuilder->CallPrintInt("L", L);
212
213    Value * B = iBuilder->CreateGEP(buffer, capacity);
214
215//    iBuilder->CallPrintInt("B", B);
216
217    Value * const canAppend = iBuilder->CreateICmpULT(L, B);
218    iBuilder->CreateLikelyCondBr(canAppend, readData, waitOnConsumers);
219
220    // First wait on any consumers to finish processing then check how much data has been consumed.
221    iBuilder->SetInsertPoint(waitOnConsumers);
222    iBuilder->CreateConsumerWait();
223
224    // Then determine how much data has been consumed and how much needs to be copied back, noting
225    // that our "unproduced" data must be block aligned.
226    const auto blockAlignment = iBuilder->getBitBlockWidth() / 8;
227    Constant * const alignmentMask = ConstantExpr::getNot(iBuilder->getSize(blockAlignment - 1));
228    Value * const consumed = iBuilder->CreateAnd(iBuilder->getConsumedItemCount("sourceBuffer"), alignmentMask);
229    Value * const remaining = iBuilder->CreateSub(bufferedSize, consumed);
230    Value * const unconsumedPtr = iBuilder->CreateGEP(inputStream, consumed);
231    Value * const consumedMajority = iBuilder->CreateICmpULT(iBuilder->CreateGEP(buffer, remaining), unconsumedPtr);
232
233//    iBuilder->CallPrintInt("consumedMajority", consumedMajority);
234
235    BasicBlock * const copyBack = iBuilder->CreateBasicBlock("CopyBack");
236    BasicBlock * const expandAndCopyBack = iBuilder->CreateBasicBlock("ExpandAndCopyBack");
237    BasicBlock * const calculateLogicalAddress = iBuilder->CreateBasicBlock("CalculateLogicalAddress");
238    // Have we consumed enough data that we can safely copy back the unconsumed data without needing
239    // a temporary buffer? (i.e., B + remaining < L + consumed)
240    iBuilder->CreateLikelyCondBr(consumedMajority, copyBack, expandAndCopyBack);
241    iBuilder->SetInsertPoint(copyBack);
242    // If so, just copy the data ...
243    iBuilder->CreateMemCpy(buffer, unconsumedPtr, remaining, blockAlignment);
244    iBuilder->CreateBr(calculateLogicalAddress);
245    // Otherwise, allocate a buffer with twice the capacity and copy the unconsumed data back into it
246    iBuilder->SetInsertPoint(expandAndCopyBack);
247    Value * const expandedCapacity = iBuilder->CreateShl(capacity, 1);
248    Value * const expandedBuffer = iBuilder->CreateCacheAlignedMalloc(expandedCapacity);
249    Value * const expandedPtr = iBuilder->CreatePointerCast(expandedBuffer, codeUnitPtrTy);
250    iBuilder->CreateMemCpy(expandedPtr, unconsumedPtr, remaining, blockAlignment);
251    iBuilder->CreateFree(buffer);
252    iBuilder->setScalarField("buffer", expandedBuffer);
253    iBuilder->setScalarField("capacity", expandedCapacity);
254    iBuilder->CreateBr(calculateLogicalAddress);
255    // Update the logical address for this buffer....
256    iBuilder->SetInsertPoint(calculateLogicalAddress);
257    PHINode * const baseAddress = iBuilder->CreatePHI(codeUnitPtrTy, 2);
258    baseAddress->addIncoming(buffer, copyBack);
259    baseAddress->addIncoming(expandedPtr, expandAndCopyBack);
260    Value * const modifiedPtr = iBuilder->CreateGEP(baseAddress, remaining);
261    Value * const logicalAddress = iBuilder->CreateGEP(modifiedPtr, iBuilder->CreateNeg(produced));
262    iBuilder->setBaseAddress("sourceBuffer", logicalAddress);
263    iBuilder->CreateBr(readData);
264    // Regardless of whether we're simply appending data or had to allocate a new buffer, read a new page
265    // of data into the input source buffer. If we fail to read a full segment ...
266    readData->moveAfter(calculateLogicalAddress);
267    iBuilder->SetInsertPoint(readData);
268    calculateLogicalAddress->moveAfter(calculateLogicalAddress);
269    PHINode * const addr = iBuilder->CreatePHI(codeUnitPtrTy, 2);
270    addr->addIncoming(originalPtr, exhaustedBuffer);
271    addr->addIncoming(modifiedPtr, calculateLogicalAddress);
272    assert(iBuilder->getKernel() == this);
273    Value * const fd = iBuilder->getScalarField("fileDescriptor");
274    Value * bytesRead = iBuilder->CreateReadCall(fd, addr, pageSize);
275    unreadSize = iBuilder->CreateAdd(unreadSize, bytesRead);
276    bufferedSize = iBuilder->CreateAdd(bufferedSize, bytesRead);
277    iBuilder->setBufferedSize("sourceBuffer", bufferedSize);
278    Value * const exhaustedInputSource = iBuilder->CreateICmpULT(unreadSize, segmentSize);
279    BasicBlock * const setTermination = iBuilder->CreateBasicBlock("SetTermination");
280    iBuilder->CreateUnlikelyCondBr(exhaustedInputSource, setTermination, stdInExit);
281
282    // ... zero out the remaining bytes and set the termination signal.
283    iBuilder->SetInsertPoint(setTermination);
284    Value * const bytesToZero = iBuilder->CreateSub(segmentSize, unreadSize);
285    iBuilder->CreateMemZero(iBuilder->CreateGEP(addr, unreadSize), bytesToZero);
286    iBuilder->setTerminationSignal();
287    iBuilder->CreateBr(stdInExit);
288
289    // finally add the segment item count to the produced item count to inform the subsequent kernels how
290    // much data is available for processing
291    iBuilder->SetInsertPoint(stdInExit);
292    stdInExit->moveAfter(setTermination);
293    PHINode * const items = iBuilder->CreatePHI(produced->getType(), 3);
294    items->addIncoming(segmentSize, entryBlock);
295    items->addIncoming(segmentSize, readData);
296    items->addIncoming(unreadSize, setTermination);
297    iBuilder->setProducedItemCount("sourceBuffer", iBuilder->CreateAdd(produced, items));
298}
299
300void ReadSourceKernel::generateFinalizeMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
301    iBuilder->CreateFree(iBuilder->getScalarField("buffer"));
302}
303
304ReadSourceKernel::ReadSourceKernel(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, unsigned blocksPerSegment, unsigned codeUnitWidth)
305: SegmentOrientedKernel("read_source"
306, {}
307, {Binding{iBuilder->getStreamSetTy(1, codeUnitWidth), "sourceBuffer"}}
308, {Binding{iBuilder->getInt32Ty(), "fileDescriptor"}}
309, {}
310, {Binding{iBuilder->getVoidPtrTy(), "buffer"}, Binding{iBuilder->getSizeTy(), "capacity"}})
311, mSegmentBlocks(blocksPerSegment)
312, mCodeUnitWidth(codeUnitWidth) {
313
314}
315
316/// MEMORY SOURCE KERNEL
317
318void MemorySourceKernel::generateInitializeMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
319    iBuilder->setBaseAddress("sourceBuffer", iBuilder->CreatePointerCast(iBuilder->getScalarField("fileSource"), iBuilder->getVoidPtrTy()));
320    iBuilder->setBufferedSize("sourceBuffer", iBuilder->getScalarField("fileSize"));
321}
322
323void MemorySourceKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> & iBuilder) {
324
325    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
326    BasicBlock * setTermination = iBuilder->CreateBasicBlock("setTermination");
327    BasicBlock * mmapSourceExit = iBuilder->CreateBasicBlock("sourceExit");
328    ConstantInt * segmentItems = iBuilder->getSize(mSegmentBlocks * iBuilder->getBitBlockWidth());
329    Value * fileItems = iBuilder->getScalarField("fileSize");
330    if (mCodeUnitWidth > 8) {
331        fileItems = iBuilder->CreateUDiv(fileItems, iBuilder->getSize(mCodeUnitWidth / 8));
332    }
333    Value * produced = iBuilder->getProducedItemCount("sourceBuffer");
334    produced = iBuilder->CreateAdd(produced, segmentItems);
335    Value * lessThanFullSegment = iBuilder->CreateICmpULT(fileItems, produced);
336    iBuilder->CreateCondBr(lessThanFullSegment, setTermination, mmapSourceExit);
337    iBuilder->SetInsertPoint(setTermination);
338    iBuilder->setTerminationSignal();
339    iBuilder->CreateBr(mmapSourceExit);
340
341    iBuilder->SetInsertPoint(mmapSourceExit);
342
343    PHINode * itemsRead = iBuilder->CreatePHI(produced->getType(), 2);
344    itemsRead->addIncoming(produced, entryBlock);
345    itemsRead->addIncoming(fileItems, setTermination);
346    iBuilder->setProducedItemCount("sourceBuffer", itemsRead);
347}
348
349MemorySourceKernel::MemorySourceKernel(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, Type * type, unsigned blocksPerSegment, unsigned codeUnitWidth)
350: SegmentOrientedKernel("memory_source",
351    {},
352    {Binding{iBuilder->getStreamSetTy(1, codeUnitWidth), "sourceBuffer"}},
353    {Binding{cast<PointerType>(type), "fileSource"}, Binding{iBuilder->getSizeTy(), "fileSize"}}, {}, {})
354, mSegmentBlocks(blocksPerSegment)
355, mCodeUnitWidth(codeUnitWidth) {
356
357}
358
359}
Note: See TracBrowser for help on using the repository browser.