source: icGREP/icgrep-devel/icgrep/kernels/streamset.cpp @ 5446

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

Refactoring work + correction for getRawItemPointer

File size: 31.0 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5
6#include "streamset.h"
7#include <llvm/IR/Module.h>
8#include <llvm/Support/raw_ostream.h>
9#include <kernels/kernel.h>
10#include <kernels/kernel_builder.h>
11#include <toolchain/toolchain.h>
12
13namespace llvm { class Constant; }
14namespace llvm { class Function; }
15
16using namespace parabix;
17using namespace llvm;
18using namespace IDISA;
19
20ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
21
22StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type);
23
24void StreamSetBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
25    if (LLVM_LIKELY(mStreamSetBufferPtr == nullptr)) {
26        Type * const ty = getType();
27        mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(ty, iBuilder->getSize(mBufferBlocks));
28        iBuilder->CreateAlignedStore(Constant::getNullValue(ty), mStreamSetBufferPtr, iBuilder->getCacheAlignment());
29    } else {
30        report_fatal_error("StreamSetBuffer::allocateBuffer() was called twice on the same stream set");
31    }
32}
33
34Value * StreamSetBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool /* readOnly */) const {
35    iBuilder->CreateAssert(iBuilder->CreateICmpULT(streamIndex, getStreamSetCount(iBuilder, self)), "StreamSetBuffer: out-of-bounds stream access");
36    return iBuilder->CreateGEP(getStreamSetBlockPtr(iBuilder, self, blockIndex), {iBuilder->getInt32(0), streamIndex});
37}
38
39Value * StreamSetBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool /* readOnly */) const {
40    iBuilder->CreateAssert(iBuilder->CreateICmpULT(streamIndex, getStreamSetCount(iBuilder, self)), "StreamSetBuffer: out-of-bounds stream access");
41    return iBuilder->CreateGEP(getStreamSetBlockPtr(iBuilder, self, blockIndex), {iBuilder->getInt32(0), streamIndex, packIndex});
42}
43
44void StreamSetBuffer::setBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * /* self */, Value * /* addr */) const {
45    report_fatal_error("setBaseAddress is not supported by this buffer type");
46}
47
48Value * StreamSetBuffer::getBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * /* self */) const {
49    report_fatal_error("getBufferedSize is not supported by this buffer type");
50}
51
52void StreamSetBuffer::setBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * /* self */, llvm::Value * /* size */) const {
53    report_fatal_error("setBufferedSize is not supported by this buffer type");
54}
55
56inline bool StreamSetBuffer::isCapacityGuaranteed(const Value * const index, const size_t capacity) const {
57    if (LLVM_UNLIKELY(isa<ConstantInt>(index))) {
58        if (LLVM_LIKELY(cast<ConstantInt>(index)->getLimitedValue() < capacity)) {
59            return true;
60        }
61    }
62    return false;
63}
64
65Value * StreamSetBuffer::getStreamSetCount(IDISA::IDISA_Builder * const iBuilder, Value *) const {
66    uint64_t count = 1;
67    if (isa<ArrayType>(mBaseType)) {
68        count = mBaseType->getArrayNumElements();
69    }
70    return iBuilder->getSize(count);
71}
72
73inline Value * StreamSetBuffer::modByBufferBlocks(IDISA::IDISA_Builder * const iBuilder, Value * const offset) const {
74    assert (offset->getType()->isIntegerTy());
75    if (isCapacityGuaranteed(offset, mBufferBlocks)) {
76        return offset;
77    } else if (mBufferBlocks == 1) {
78        return ConstantInt::getNullValue(iBuilder->getSizeTy());
79    } else if ((mBufferBlocks & (mBufferBlocks - 1)) == 0) { // is power of 2
80        return iBuilder->CreateAnd(offset, ConstantInt::get(offset->getType(), mBufferBlocks - 1));
81    } else {
82        return iBuilder->CreateURem(offset, ConstantInt::get(offset->getType(), mBufferBlocks));
83    }
84}
85
86/**
87 * @brief getRawItemPointer
88 *
89 * get a raw pointer the iN field at position absoluteItemPosition of the stream number streamIndex of the stream set.
90 * In the case of a stream whose fields are less than one byte (8 bits) in size, the pointer is to the containing byte.
91 * The type of the pointer is i8* for fields of 8 bits or less, otherwise iN* for N-bit fields.
92 */
93Value * StreamSetBuffer::getRawItemPointer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * absolutePosition) const {
94    Value * ptr = iBuilder->CreateGEP(getBaseAddress(iBuilder, self), {iBuilder->getInt32(0), streamIndex});
95    Value * relativePosition = absolutePosition;
96    const auto bw = mBaseType->getArrayElementType()->getScalarSizeInBits();
97    if (bw < 8) {
98        assert (bw  == 1 || bw == 2 || bw == 4);
99        relativePosition = iBuilder->CreateUDiv(relativePosition, ConstantInt::get(relativePosition->getType(), 8 / bw));
100        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getInt8PtrTy());
101    } else {
102        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getIntNTy(bw)->getPointerTo());
103    }
104    return iBuilder->CreateGEP(ptr, relativePosition);
105}
106
107Value * StreamSetBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
108    if (isa<ArrayType>(mType) && dyn_cast<ArrayType>(mType)->getNumElements() > 1) {
109        Constant * stride = iBuilder->getSize(iBuilder->getStride());
110        return iBuilder->CreateSub(stride, iBuilder->CreateURem(fromPosition, stride));
111    } else {
112        Constant * bufSize = iBuilder->getSize(mBufferBlocks * iBuilder->getStride());
113        return iBuilder->CreateSub(bufSize, iBuilder->CreateURem(fromPosition, bufSize));
114    }
115}
116
117Value * StreamSetBuffer::getLinearlyAccessibleBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
118    Constant * bufBlocks = iBuilder->getSize(mBufferBlocks);
119    return iBuilder->CreateSub(bufBlocks, iBuilder->CreateURem(fromBlock, bufBlocks));
120}
121
122Value * StreamSetBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
123    return getLinearlyAccessibleItems(iBuilder, fromPosition);
124}
125
126Value * StreamSetBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
127    return getLinearlyAccessibleBlocks(iBuilder, fromBlock);
128}
129
130Value * StreamSetBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
131    iBuilder->CreateAssert(self, "StreamSetBuffer base address cannot be 0");
132    return self;
133}
134
135void StreamSetBuffer::releaseBuffer(IDISA::IDISA_Builder * const /* iBuilder */, Value * /* self */) const {
136    /* do nothing: memory is stack allocated */
137}
138
139void StreamSetBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const iBuilder, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy) const {
140    Type * size_ty = iBuilder->getSizeTy();
141    Type * i8ptr = iBuilder->getInt8PtrTy();
142    Constant * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
143    Function * f = iBuilder->GetInsertBlock()->getParent();
144    BasicBlock * wholeBlockCopy = BasicBlock::Create(iBuilder->getContext(), "wholeBlockCopy", f, 0);
145    BasicBlock * partialBlockCopy = BasicBlock::Create(iBuilder->getContext(), "partialBlockCopy", f, 0);
146    BasicBlock * copyDone = BasicBlock::Create(iBuilder->getContext(), "copyDone", f, 0);
147    unsigned numStreams = getType()->getArrayNumElements();
148    auto elemTy = getType()->getArrayElementType();
149    unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
150    Value * blocksToCopy = iBuilder->CreateUDiv(itemsToCopy, blockSize);
151    Value * partialItems = iBuilder->CreateURem(itemsToCopy, blockSize);
152    Value * partialBlockTargetPtr = iBuilder->CreateGEP(targetBlockPtr, blocksToCopy);
153    Value * partialBlockSourcePtr = iBuilder->CreateGEP(sourceBlockPtr, blocksToCopy);
154    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(blocksToCopy, iBuilder->getSize(0)), wholeBlockCopy, partialBlockCopy);
155    iBuilder->SetInsertPoint(wholeBlockCopy);
156    unsigned alignment = iBuilder->getBitBlockWidth() / 8;
157    Value * copyLength = iBuilder->CreateSub(iBuilder->CreatePtrToInt(partialBlockTargetPtr, size_ty), iBuilder->CreatePtrToInt(targetBlockPtr, size_ty));
158    iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, i8ptr), iBuilder->CreateBitCast(sourceBlockPtr, i8ptr), copyLength, alignment);
159    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(partialItems, iBuilder->getSize(0)), partialBlockCopy, copyDone);
160    iBuilder->SetInsertPoint(partialBlockCopy);
161    Value * copyBits = iBuilder->CreateMul(itemsToCopy, iBuilder->getSize(fieldWidth));
162    Value * copyBytes = iBuilder->CreateLShr(iBuilder->CreateAdd(copyBits, iBuilder->getSize(7)), iBuilder->getSize(3));
163    for (unsigned strm = 0; strm < numStreams; strm++) {
164        Value * strmTargetPtr = iBuilder->CreateGEP(partialBlockTargetPtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
165        Value * strmSourcePtr = iBuilder->CreateGEP(partialBlockSourcePtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
166        iBuilder->CreateMemMove(iBuilder->CreateBitCast(strmTargetPtr, i8ptr), iBuilder->CreateBitCast(strmSourcePtr, i8ptr), copyBytes, alignment);
167    }
168    iBuilder->CreateBr(copyDone);
169    iBuilder->SetInsertPoint(copyDone);
170}
171
172
173
174// Single Block Buffer
175
176// For a single block buffer, the block pointer is always the buffer base pointer.
177Value * SingleBlockBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const, Value * self, Value *) const {
178    return self;
179}
180
181// Source File Buffer
182Value * SourceBuffer::getBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
183    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
184    return iBuilder->CreateLoad(ptr);
185}
186
187void SourceBuffer::setBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * self, llvm::Value * size) const {
188    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
189    iBuilder->CreateStore(size, ptr);
190}
191
192void SourceBuffer::setBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * addr) const {
193    Value * const ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
194    iBuilder->CreateStore(iBuilder->CreatePointerCast(addr, ptr->getType()->getPointerElementType()), ptr);
195}
196
197Value * SourceBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * const self) const {
198    iBuilder->CreateAssert(self, "SourceBuffer: instance cannot be null");
199    Value * const ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
200    Value * const addr = iBuilder->CreateLoad(ptr);
201    iBuilder->CreateAssert(addr, "SourceBuffer: base address cannot be 0");
202    return addr;
203}
204
205Value * SourceBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
206    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), blockIndex);
207}
208
209Value * SourceBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
210    report_fatal_error("External buffers: getLinearlyAccessibleItems is not supported.");
211}
212
213// External File Buffer
214void ExternalBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> &) {
215    report_fatal_error("External buffers cannot be allocated.");
216}
217
218Value * ExternalBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
219    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), blockIndex);
220}
221
222Value * ExternalBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
223    report_fatal_error("External buffers: getLinearlyAccessibleItems is not supported.");
224}
225
226// Circular Buffer
227Value * CircularBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * const self, Value * const blockIndex) const {
228    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), modByBufferBlocks(iBuilder, blockIndex));
229}
230
231Value * CircularBuffer::getRawItemPointer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * absolutePosition) const {
232    Value * ptr = iBuilder->CreateGEP(getBaseAddress(iBuilder, self), {iBuilder->getInt32(0), streamIndex});
233    Value * relativePosition = iBuilder->CreateURem(absolutePosition, ConstantInt::get(absolutePosition->getType(), mBufferBlocks * iBuilder->getBitBlockWidth()));
234    const auto bw = mBaseType->getArrayElementType()->getScalarSizeInBits();
235    if (bw < 8) {
236        assert (bw  == 1 || bw == 2 || bw == 4);
237        relativePosition = iBuilder->CreateUDiv(relativePosition, ConstantInt::get(relativePosition->getType(), 8 / bw));
238        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getInt8PtrTy());
239    } else {
240        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getIntNTy(bw)->getPointerTo());
241    }
242    return iBuilder->CreateGEP(ptr, relativePosition);
243}
244
245// CircularCopybackBuffer Buffer
246void CircularCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
247    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType(), iBuilder->getSize(mBufferBlocks + mOverflowBlocks));
248}
249
250void CircularCopybackBuffer::createCopyBack(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * overFlowItems) const {
251    Value * overFlowAreaPtr = iBuilder->CreateGEP(self, iBuilder->getSize(mBufferBlocks));
252    createBlockAlignedCopy(iBuilder, self, overFlowAreaPtr, overFlowItems);
253}
254
255Value * CircularCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
256    return iBuilder->CreateAdd(getLinearlyAccessibleItems(iBuilder, fromPosition), iBuilder->getSize(mOverflowBlocks * iBuilder->getBitBlockWidth()));
257}
258
259Value * CircularCopybackBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
260    return iBuilder->CreateAdd(getLinearlyAccessibleBlocks(iBuilder, fromBlock), iBuilder->getSize(mOverflowBlocks));
261}
262
263// SwizzledCopybackBuffer Buffer
264
265void SwizzledCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
266    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType(), iBuilder->getSize(mBufferBlocks + mOverflowBlocks));
267}
268
269void SwizzledCopybackBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const iBuilder, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy) const {
270    Type * size_ty = iBuilder->getSizeTy();
271    Type * i8ptr = iBuilder->getInt8PtrTy();
272    Constant * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
273    Function * f = iBuilder->GetInsertBlock()->getParent();
274    BasicBlock * wholeBlockCopy = BasicBlock::Create(iBuilder->getContext(), "wholeBlockCopy", f, 0);
275    BasicBlock * partialBlockCopy = BasicBlock::Create(iBuilder->getContext(), "partialBlockCopy", f, 0);
276    BasicBlock * copyDone = BasicBlock::Create(iBuilder->getContext(), "copyDone", f, 0);
277    unsigned numStreams = getType()->getArrayNumElements();
278    unsigned swizzleFactor = iBuilder->getBitBlockWidth()/mFieldWidth;
279    auto elemTy = getType()->getArrayElementType();
280    unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
281    Value * blocksToCopy = iBuilder->CreateUDiv(itemsToCopy, blockSize);
282    Value * partialItems = iBuilder->CreateURem(itemsToCopy, blockSize);
283    Value * partialBlockTargetPtr = iBuilder->CreateGEP(targetBlockPtr, blocksToCopy);
284    Value * partialBlockSourcePtr = iBuilder->CreateGEP(sourceBlockPtr, blocksToCopy);
285    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(blocksToCopy, iBuilder->getSize(0)), wholeBlockCopy, partialBlockCopy);
286    iBuilder->SetInsertPoint(wholeBlockCopy);
287    unsigned alignment = iBuilder->getBitBlockWidth() / 8;
288    Value * copyLength = iBuilder->CreateSub(iBuilder->CreatePtrToInt(partialBlockTargetPtr, size_ty), iBuilder->CreatePtrToInt(targetBlockPtr, size_ty));
289    iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, i8ptr), iBuilder->CreateBitCast(sourceBlockPtr, i8ptr), copyLength, alignment);
290    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(partialItems, iBuilder->getSize(0)), partialBlockCopy, copyDone);
291    iBuilder->SetInsertPoint(partialBlockCopy);
292    Value * copyBits = iBuilder->CreateMul(itemsToCopy, iBuilder->getSize(fieldWidth * swizzleFactor));
293    Value * copyBytes = iBuilder->CreateLShr(iBuilder->CreateAdd(copyBits, iBuilder->getSize(7)), iBuilder->getSize(3));
294    for (unsigned strm = 0; strm < numStreams; strm += swizzleFactor) {
295        Value * strmTargetPtr = iBuilder->CreateGEP(partialBlockTargetPtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
296        Value * strmSourcePtr = iBuilder->CreateGEP(partialBlockSourcePtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
297        iBuilder->CreateMemMove(iBuilder->CreateBitCast(strmTargetPtr, i8ptr), iBuilder->CreateBitCast(strmSourcePtr, i8ptr), copyBytes, alignment);
298    }
299    iBuilder->CreateBr(copyDone);
300    iBuilder->SetInsertPoint(copyDone);
301}
302
303void SwizzledCopybackBuffer::createCopyBack(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * overFlowItems) const {
304    Value * overFlowAreaPtr = iBuilder->CreateGEP(self, iBuilder->getSize(mBufferBlocks));
305    createBlockAlignedCopy(iBuilder, self, overFlowAreaPtr, overFlowItems);
306}
307
308Value * SwizzledCopybackBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
309    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), modByBufferBlocks(iBuilder, blockIndex));
310}
311
312Value * SwizzledCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
313    return iBuilder->CreateAdd(getLinearlyAccessibleItems(iBuilder, fromPosition), iBuilder->getSize(mOverflowBlocks * iBuilder->getBitBlockWidth()));
314}
315
316Value * SwizzledCopybackBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
317    return iBuilder->CreateAdd(getLinearlyAccessibleBlocks(iBuilder, fromBlock), iBuilder->getSize(mOverflowBlocks));
318}
319
320// Expandable Buffer
321
322void ExpandableBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
323    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType());
324    Value * const capacityPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
325    iBuilder->CreateStore(iBuilder->getSize(mInitialCapacity), capacityPtr);
326    Type * const bufferType = getType()->getStructElementType(1)->getPointerElementType();
327    Constant * const bufferWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(bufferType), iBuilder->getSizeTy(), false);
328    Constant * const size = ConstantExpr::getMul(iBuilder->getSize(mBufferBlocks * mInitialCapacity), bufferWidth);
329    Value * const ptr = iBuilder->CreateAlignedMalloc(size, iBuilder->getCacheAlignment());
330    iBuilder->CreateMemZero(ptr, size, bufferType->getPrimitiveSizeInBits() / 8);
331    Value * const streamSetPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
332    iBuilder->CreateStore(iBuilder->CreatePointerCast(ptr, bufferType->getPointerTo()), streamSetPtr);
333}
334
335std::pair<Value *, Value *> ExpandableBuffer::getInternalStreamBuffer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
336
337    // ENTRY
338    Value * const capacityPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
339    Value * const capacity = iBuilder->CreateLoad(capacityPtr);
340    Value * const streamSetPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
341    Value * const streamSet = iBuilder->CreateLoad(streamSetPtr);
342    blockIndex = modByBufferBlocks(iBuilder, blockIndex);
343
344    assert (streamIndex->getType() == capacity->getType());
345    Value * const cond = iBuilder->CreateICmpULT(streamIndex, capacity);
346
347    // Are we guaranteed that we can access this stream?
348    if (readOnly || isCapacityGuaranteed(streamIndex, mInitialCapacity)) {
349        iBuilder->CreateAssert(cond, "ExpandableBuffer: out-of-bounds stream access");
350        Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, capacity), streamIndex);
351        return {streamSet, offset};
352    }
353
354    BasicBlock * const entry = iBuilder->GetInsertBlock();
355    BasicBlock * const expand = BasicBlock::Create(iBuilder->getContext(), "expand", entry->getParent());
356    BasicBlock * const resume = BasicBlock::Create(iBuilder->getContext(), "resume", entry->getParent());
357
358    iBuilder->CreateLikelyCondBr(cond, resume, expand);
359
360    // EXPAND
361    iBuilder->SetInsertPoint(expand);
362
363    Type * elementType = getType()->getStructElementType(1)->getPointerElementType();
364    Constant * const vectorWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(elementType), capacity->getType(), false);
365
366    Value * newCapacity = iBuilder->CreateAdd(streamIndex, iBuilder->getSize(1));
367    newCapacity = iBuilder->CreateCeilLog2(newCapacity);
368    newCapacity = iBuilder->CreateShl(iBuilder->getSize(1), newCapacity, "newCapacity");
369
370    std::string tmp;
371    raw_string_ostream out(tmp);
372    out << "__expand";
373    elementType->print(out);
374    std::string name = out.str();
375
376    Module * const m = iBuilder->getModule();
377    Function * expandFunction = m->getFunction(name);
378
379    if (expandFunction == nullptr) {
380
381        const auto ip = iBuilder->saveIP();
382
383        FunctionType * fty = FunctionType::get(elementType->getPointerTo(), {elementType->getPointerTo(), iBuilder->getSizeTy(), iBuilder->getSizeTy()}, false);
384        expandFunction = Function::Create(fty, GlobalValue::PrivateLinkage, name, m);
385
386        auto args = expandFunction->arg_begin();
387        Value * streamSet = &*args++;
388        Value * capacity = &*args++;
389        Value * newCapacity = &*args;
390
391        BasicBlock * entry = BasicBlock::Create(iBuilder->getContext(), "entry", expandFunction);
392        iBuilder->SetInsertPoint(entry);
393
394        Value * size = iBuilder->CreateMul(newCapacity, iBuilder->getSize(mBufferBlocks));
395        Value * newStreamSet = iBuilder->CreatePointerCast(iBuilder->CreateAlignedMalloc(iBuilder->CreateMul(size, vectorWidth), iBuilder->getCacheAlignment()), elementType->getPointerTo());
396        Value * const diffCapacity = iBuilder->CreateMul(iBuilder->CreateSub(newCapacity, capacity), vectorWidth);
397
398        const auto alignment = elementType->getPrimitiveSizeInBits() / 8;
399        for (unsigned i = 0; i < mBufferBlocks; ++i) {
400            ConstantInt * const offset = iBuilder->getSize(i);
401            Value * srcOffset = iBuilder->CreateMul(capacity, offset);
402            Value * srcPtr = iBuilder->CreateGEP(streamSet, srcOffset);
403            Value * destOffset = iBuilder->CreateMul(newCapacity, offset);
404            Value * destPtr = iBuilder->CreateGEP(newStreamSet, destOffset);
405            iBuilder->CreateMemCpy(destPtr, srcPtr, iBuilder->CreateMul(capacity, vectorWidth), alignment);
406            Value * destZeroOffset = iBuilder->CreateAdd(destOffset, capacity);
407            Value * destZeroPtr = iBuilder->CreateGEP(newStreamSet, destZeroOffset);
408            iBuilder->CreateMemZero(destZeroPtr, diffCapacity, alignment);
409        }
410
411        iBuilder->CreateAlignedFree(streamSet);
412
413        iBuilder->CreateRet(newStreamSet);
414
415        iBuilder->restoreIP(ip);
416    }
417
418    Value * newStreamSet = iBuilder->CreateCall(expandFunction, {streamSet, capacity, newCapacity});
419    iBuilder->CreateStore(newStreamSet, streamSetPtr);
420    iBuilder->CreateStore(newCapacity, capacityPtr);
421
422    iBuilder->CreateBr(resume);
423
424    // RESUME
425    iBuilder->SetInsertPoint(resume);
426
427    PHINode * phiStreamSet = iBuilder->CreatePHI(streamSet->getType(), 2);
428    phiStreamSet->addIncoming(streamSet, entry);
429    phiStreamSet->addIncoming(newStreamSet, expand);
430
431    PHINode * phiCapacity = iBuilder->CreatePHI(capacity->getType(), 2);
432    phiCapacity->addIncoming(capacity, entry);
433    phiCapacity->addIncoming(newCapacity, expand);
434
435    Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, phiCapacity), streamIndex);
436
437    return {phiStreamSet, offset};
438}
439
440Value * ExpandableBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
441    Value * ptr, * offset;
442    std::tie(ptr, offset) = getInternalStreamBuffer(iBuilder, self, streamIndex, blockIndex, readOnly);
443    return iBuilder->CreateGEP(ptr, offset);
444}
445
446Value * ExpandableBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool readOnly) const {
447    Value * ptr, * offset;
448    std::tie(ptr, offset) = getInternalStreamBuffer(iBuilder, self, streamIndex, blockIndex, readOnly);
449    return iBuilder->CreateGEP(ptr, {offset, packIndex});
450}
451
452Value * ExpandableBuffer::getStreamSetCount(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
453    return iBuilder->CreateLoad(iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
454}
455
456Value * ExpandableBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
457    iBuilder->CreateAssert(self, "ExpandableBuffer: instance cannot be null");
458    Value * const baseAddr = iBuilder->CreateLoad(iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
459    iBuilder->CreateAssert(self, "ExpandableBuffer: base address cannot be 0");
460    return baseAddr;
461}
462
463void ExpandableBuffer::releaseBuffer(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
464    iBuilder->CreateAlignedFree(getBaseAddress(iBuilder, self));
465}
466
467Value * ExpandableBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value *, Value *) const {
468    report_fatal_error("Expandable buffers: getStreamSetBlockPtr is not supported.");
469}
470
471Value * ExpandableBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
472    report_fatal_error("Expandable buffers: getLinearlyAccessibleItems is not supported.");
473}
474
475// Constructors
476SingleBlockBuffer::SingleBlockBuffer(const std::unique_ptr<kernel::KernelBuilder> &  b, Type * type)
477: StreamSetBuffer(BufferKind::BlockBuffer, type, resolveStreamSetType(b, type), 1, 0) {
478    mUniqueID = "S";
479}
480
481SourceBuffer::SourceBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, unsigned MemoryAddressSpace, unsigned StructAddressSpace)
482: StreamSetBuffer(BufferKind::SourceBuffer, type, StructType::get(resolveStreamSetType(b, type)->getPointerTo(MemoryAddressSpace), b->getSizeTy(), nullptr), 1, StructAddressSpace) {
483    mUniqueID = "B";
484    if (MemoryAddressSpace != 0 || StructAddressSpace != 0) {
485        mUniqueID += "@" + std::to_string(MemoryAddressSpace) + ":" + std::to_string(StructAddressSpace);
486    }
487}
488
489ExternalBuffer::ExternalBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, llvm::Value * addr, unsigned AddressSpace)
490: StreamSetBuffer(BufferKind::ExternalBuffer, type, resolveStreamSetType(b, type), 1, AddressSpace) {
491    mUniqueID = "E";
492    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
493    mStreamSetBufferPtr = b->CreatePointerBitCastOrAddrSpaceCast(addr, getPointerType());
494}
495
496CircularBuffer::CircularBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
497: StreamSetBuffer(BufferKind::CircularBuffer, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace) {
498    mUniqueID = "C" + std::to_string(bufferBlocks);
499    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
500}
501
502CircularBuffer::CircularBuffer(const BufferKind k, const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
503: StreamSetBuffer(k, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace) {
504
505}
506
507CircularCopybackBuffer::CircularCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
508: CircularBuffer(BufferKind::CircularCopybackBuffer, b, type, bufferBlocks, AddressSpace)
509, mOverflowBlocks(overflowBlocks) {
510    mUniqueID = "CC" + std::to_string(bufferBlocks);
511    if (mOverflowBlocks != 1) mUniqueID += "_" + std::to_string(mOverflowBlocks);
512    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
513}
514
515ExpandableBuffer::ExpandableBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
516: StreamSetBuffer(BufferKind::ExpandableBuffer, type, resolveExpandableStreamSetType(b, type), bufferBlocks, AddressSpace)
517, mInitialCapacity(type->getArrayNumElements()) {
518    mUniqueID = "XP" + std::to_string(bufferBlocks);
519    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
520}
521
522SwizzledCopybackBuffer::SwizzledCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned fieldwidth, unsigned AddressSpace)
523: StreamSetBuffer(BufferKind::SwizzledCopybackBuffer, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace), mOverflowBlocks(overflowBlocks), mFieldWidth(fieldwidth) {
524    mUniqueID = "SW" + std::to_string(fieldwidth) + ":" + std::to_string(bufferBlocks);
525    if (mOverflowBlocks != 1) {
526        mUniqueID += "_" + std::to_string(mOverflowBlocks);
527    }
528    if (AddressSpace > 0) {
529        mUniqueID += "@" + std::to_string(AddressSpace);
530    }
531}
532
533inline StreamSetBuffer::StreamSetBuffer(BufferKind k, Type * baseType, Type * resolvedType, unsigned BufferBlocks, unsigned AddressSpace)
534: mBufferKind(k)
535, mType(resolvedType)
536, mBufferBlocks(BufferBlocks)
537, mAddressSpace(AddressSpace)
538, mStreamSetBufferPtr(nullptr)
539, mBaseType(baseType)
540, mProducer(nullptr) {
541
542}
543
544StreamSetBuffer::~StreamSetBuffer() { }
545
546// Helper routines
547ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
548    unsigned numElements = 1;
549    if (LLVM_LIKELY(type->isArrayTy())) {
550        numElements = type->getArrayNumElements();
551        type = type->getArrayElementType();
552    }
553    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
554        type = type->getVectorElementType();
555        if (LLVM_LIKELY(type->isIntegerTy())) {
556            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
557            type = b->getBitBlockType();
558            if (fieldWidth != 1) {
559                type = ArrayType::get(type, fieldWidth);
560            }
561            return ArrayType::get(type, numElements);
562        }
563    }
564    std::string tmp;
565    raw_string_ostream out(tmp);
566    type->print(out);
567    out << " is an unvalid stream set buffer type.";
568    report_fatal_error(out.str());
569}
570
571StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
572    if (LLVM_LIKELY(type->isArrayTy())) {
573        type = type->getArrayElementType();
574    }
575    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
576        type = type->getVectorElementType();
577        if (LLVM_LIKELY(type->isIntegerTy())) {
578            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
579            type = b->getBitBlockType();
580            if (fieldWidth != 1) {
581                type = ArrayType::get(type, fieldWidth);
582            }
583            return StructType::get(b->getSizeTy(), type->getPointerTo(), nullptr);
584        }
585    }
586    std::string tmp;
587    raw_string_ostream out(tmp);
588    type->print(out);
589    out << " is an unvalid stream set buffer type.";
590    report_fatal_error(out.str());
591}
Note: See TracBrowser for help on using the repository browser.