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

Last change on this file since 5500 was 5500, checked in by cameron, 22 months ago

Read source kernel restructure calculations using logical code units

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