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

Last change on this file since 5448 was 5448, checked in by cameron, 23 months ago

Hack for source/external buffers with mBufferBlocks=1; u8u16 test with segment-pipeline-parallel; simplified copying

File size: 30.7 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 * i8ptr = iBuilder->getInt8PtrTy();
141    unsigned alignment = iBuilder->getBitBlockWidth() / 8;
142    Constant * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
143    unsigned numStreams = getType()->getArrayNumElements();
144    auto elemTy = getType()->getArrayElementType();
145    unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
146    if (numStreams == 1) {
147        Value * copyBits = iBuilder->CreateMul(itemsToCopy, iBuilder->getSize(fieldWidth));
148        Value * copyBytes = iBuilder->CreateLShr(iBuilder->CreateAdd(copyBits, iBuilder->getSize(7)), iBuilder->getSize(3));
149        iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, i8ptr), iBuilder->CreateBitCast(sourceBlockPtr, i8ptr), copyBytes, alignment);
150        return;
151    }
152    Value * blocksToCopy = iBuilder->CreateUDiv(itemsToCopy, blockSize);
153    Value * partialItems = iBuilder->CreateURem(itemsToCopy, blockSize);
154    Value * partialBlockTargetPtr = iBuilder->CreateGEP(targetBlockPtr, blocksToCopy);
155    Value * partialBlockSourcePtr = iBuilder->CreateGEP(sourceBlockPtr, blocksToCopy);
156    Value * blockCopyBytes = iBuilder->CreateMul(blocksToCopy, iBuilder->getSize(iBuilder->getBitBlockWidth() * numStreams * fieldWidth/8));
157    iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, i8ptr), iBuilder->CreateBitCast(sourceBlockPtr, i8ptr), blockCopyBytes, alignment);
158    Value * partialCopyBitsPreStream = iBuilder->CreateMul(partialItems, iBuilder->getSize(fieldWidth));
159    Value * partialCopyBytesPreStream = iBuilder->CreateLShr(iBuilder->CreateAdd(partialCopyBitsPreStream, iBuilder->getSize(7)), iBuilder->getSize(3));
160    for (unsigned strm = 0; strm < numStreams; strm++) {
161        Value * strmTargetPtr = iBuilder->CreateGEP(partialBlockTargetPtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
162        Value * strmSourcePtr = iBuilder->CreateGEP(partialBlockSourcePtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
163        iBuilder->CreateMemMove(iBuilder->CreateBitCast(strmTargetPtr, i8ptr), iBuilder->CreateBitCast(strmSourcePtr, i8ptr), partialCopyBytesPreStream, alignment);
164    }
165}
166
167
168
169// Single Block Buffer
170
171// For a single block buffer, the block pointer is always the buffer base pointer.
172Value * SingleBlockBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const, Value * self, Value *) const {
173    return self;
174}
175
176// Source File Buffer
177Value * SourceBuffer::getBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
178    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
179    return iBuilder->CreateLoad(ptr);
180}
181
182void SourceBuffer::setBufferedSize(IDISA::IDISA_Builder * const iBuilder, Value * self, llvm::Value * size) const {
183    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
184    iBuilder->CreateStore(size, ptr);
185}
186
187void SourceBuffer::setBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * addr) const {
188    Value * const ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
189    iBuilder->CreateStore(iBuilder->CreatePointerCast(addr, ptr->getType()->getPointerElementType()), ptr);
190}
191
192Value * SourceBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * const self) const {
193    iBuilder->CreateAssert(self, "SourceBuffer: instance cannot be null");
194    Value * const ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
195    Value * const addr = iBuilder->CreateLoad(ptr);
196    iBuilder->CreateAssert(addr, "SourceBuffer: base address cannot be 0");
197    return addr;
198}
199
200Value * SourceBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
201    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), blockIndex);
202}
203
204Value * SourceBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
205    report_fatal_error("External buffers: getLinearlyAccessibleItems is not supported.");
206}
207
208// External File Buffer
209void ExternalBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> &) {
210    report_fatal_error("External buffers cannot be allocated.");
211}
212
213Value * ExternalBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
214    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), blockIndex);
215}
216
217Value * ExternalBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
218    report_fatal_error("External buffers: getLinearlyAccessibleItems is not supported.");
219}
220
221// Circular Buffer
222Value * CircularBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * const self, Value * const blockIndex) const {
223    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), modByBufferBlocks(iBuilder, blockIndex));
224}
225
226Value * CircularBuffer::getRawItemPointer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * absolutePosition) const {
227    Value * ptr = iBuilder->CreateGEP(getBaseAddress(iBuilder, self), {iBuilder->getInt32(0), streamIndex});
228    Value * relativePosition = iBuilder->CreateURem(absolutePosition, ConstantInt::get(absolutePosition->getType(), mBufferBlocks * iBuilder->getBitBlockWidth()));
229    const auto bw = mBaseType->getArrayElementType()->getScalarSizeInBits();
230    if (bw < 8) {
231        assert (bw  == 1 || bw == 2 || bw == 4);
232        relativePosition = iBuilder->CreateUDiv(relativePosition, ConstantInt::get(relativePosition->getType(), 8 / bw));
233        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getInt8PtrTy());
234    } else {
235        ptr = iBuilder->CreatePointerCast(ptr, iBuilder->getIntNTy(bw)->getPointerTo());
236    }
237    return iBuilder->CreateGEP(ptr, relativePosition);
238}
239
240// CircularCopybackBuffer Buffer
241void CircularCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
242    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType(), iBuilder->getSize(mBufferBlocks + mOverflowBlocks));
243}
244
245void CircularCopybackBuffer::createCopyBack(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * overFlowItems) const {
246    Value * overFlowAreaPtr = iBuilder->CreateGEP(self, iBuilder->getSize(mBufferBlocks));
247    createBlockAlignedCopy(iBuilder, self, overFlowAreaPtr, overFlowItems);
248}
249
250Value * CircularCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
251    return iBuilder->CreateAdd(getLinearlyAccessibleItems(iBuilder, fromPosition), iBuilder->getSize(mOverflowBlocks * iBuilder->getBitBlockWidth()));
252}
253
254Value * CircularCopybackBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
255    return iBuilder->CreateAdd(getLinearlyAccessibleBlocks(iBuilder, fromBlock), iBuilder->getSize(mOverflowBlocks));
256}
257
258// SwizzledCopybackBuffer Buffer
259
260void SwizzledCopybackBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
261    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType(), iBuilder->getSize(mBufferBlocks + mOverflowBlocks));
262}
263
264void SwizzledCopybackBuffer::createBlockAlignedCopy(IDISA::IDISA_Builder * const iBuilder, Value * targetBlockPtr, Value * sourceBlockPtr, Value * itemsToCopy) const {
265    Type * size_ty = iBuilder->getSizeTy();
266    Type * i8ptr = iBuilder->getInt8PtrTy();
267    Constant * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
268    Function * f = iBuilder->GetInsertBlock()->getParent();
269    BasicBlock * wholeBlockCopy = BasicBlock::Create(iBuilder->getContext(), "wholeBlockCopy", f, 0);
270    BasicBlock * partialBlockCopy = BasicBlock::Create(iBuilder->getContext(), "partialBlockCopy", f, 0);
271    BasicBlock * copyDone = BasicBlock::Create(iBuilder->getContext(), "copyDone", f, 0);
272    unsigned numStreams = getType()->getArrayNumElements();
273    unsigned swizzleFactor = iBuilder->getBitBlockWidth()/mFieldWidth;
274    auto elemTy = getType()->getArrayElementType();
275    unsigned fieldWidth = isa<ArrayType>(elemTy) ? elemTy->getArrayNumElements() : 1;
276    Value * blocksToCopy = iBuilder->CreateUDiv(itemsToCopy, blockSize);
277    Value * partialItems = iBuilder->CreateURem(itemsToCopy, blockSize);
278    Value * partialBlockTargetPtr = iBuilder->CreateGEP(targetBlockPtr, blocksToCopy);
279    Value * partialBlockSourcePtr = iBuilder->CreateGEP(sourceBlockPtr, blocksToCopy);
280    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(blocksToCopy, iBuilder->getSize(0)), wholeBlockCopy, partialBlockCopy);
281    iBuilder->SetInsertPoint(wholeBlockCopy);
282    unsigned alignment = iBuilder->getBitBlockWidth() / 8;
283    Value * copyLength = iBuilder->CreateSub(iBuilder->CreatePtrToInt(partialBlockTargetPtr, size_ty), iBuilder->CreatePtrToInt(targetBlockPtr, size_ty));
284    iBuilder->CreateMemMove(iBuilder->CreateBitCast(targetBlockPtr, i8ptr), iBuilder->CreateBitCast(sourceBlockPtr, i8ptr), copyLength, alignment);
285    iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(partialItems, iBuilder->getSize(0)), partialBlockCopy, copyDone);
286    iBuilder->SetInsertPoint(partialBlockCopy);
287    Value * copyBits = iBuilder->CreateMul(itemsToCopy, iBuilder->getSize(fieldWidth * swizzleFactor));
288    Value * copyBytes = iBuilder->CreateLShr(iBuilder->CreateAdd(copyBits, iBuilder->getSize(7)), iBuilder->getSize(3));
289    for (unsigned strm = 0; strm < numStreams; strm += swizzleFactor) {
290        Value * strmTargetPtr = iBuilder->CreateGEP(partialBlockTargetPtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
291        Value * strmSourcePtr = iBuilder->CreateGEP(partialBlockSourcePtr, {iBuilder->getInt32(0), iBuilder->getInt32(strm)});
292        iBuilder->CreateMemMove(iBuilder->CreateBitCast(strmTargetPtr, i8ptr), iBuilder->CreateBitCast(strmSourcePtr, i8ptr), copyBytes, alignment);
293    }
294    iBuilder->CreateBr(copyDone);
295    iBuilder->SetInsertPoint(copyDone);
296}
297
298void SwizzledCopybackBuffer::createCopyBack(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * overFlowItems) const {
299    Value * overFlowAreaPtr = iBuilder->CreateGEP(self, iBuilder->getSize(mBufferBlocks));
300    createBlockAlignedCopy(iBuilder, self, overFlowAreaPtr, overFlowItems);
301}
302
303Value * SwizzledCopybackBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * blockIndex) const {
304    return iBuilder->CreateGEP(getBaseAddress(iBuilder, self), modByBufferBlocks(iBuilder, blockIndex));
305}
306
307Value * SwizzledCopybackBuffer::getLinearlyWritableItems(IDISA::IDISA_Builder * const iBuilder, Value * fromPosition) const {
308    return iBuilder->CreateAdd(getLinearlyAccessibleItems(iBuilder, fromPosition), iBuilder->getSize(mOverflowBlocks * iBuilder->getBitBlockWidth()));
309}
310
311Value * SwizzledCopybackBuffer::getLinearlyWritableBlocks(IDISA::IDISA_Builder * const iBuilder, Value * fromBlock) const {
312    return iBuilder->CreateAdd(getLinearlyAccessibleBlocks(iBuilder, fromBlock), iBuilder->getSize(mOverflowBlocks));
313}
314
315// Expandable Buffer
316
317void ExpandableBuffer::allocateBuffer(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
318    mStreamSetBufferPtr = iBuilder->CreateCacheAlignedAlloca(getType());
319    Value * const capacityPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
320    iBuilder->CreateStore(iBuilder->getSize(mInitialCapacity), capacityPtr);
321    Type * const bufferType = getType()->getStructElementType(1)->getPointerElementType();
322    Constant * const bufferWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(bufferType), iBuilder->getSizeTy(), false);
323    Constant * const size = ConstantExpr::getMul(iBuilder->getSize(mBufferBlocks * mInitialCapacity), bufferWidth);
324    Value * const ptr = iBuilder->CreateAlignedMalloc(size, iBuilder->getCacheAlignment());
325    iBuilder->CreateMemZero(ptr, size, bufferType->getPrimitiveSizeInBits() / 8);
326    Value * const streamSetPtr = iBuilder->CreateGEP(mStreamSetBufferPtr, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
327    iBuilder->CreateStore(iBuilder->CreatePointerCast(ptr, bufferType->getPointerTo()), streamSetPtr);
328}
329
330std::pair<Value *, Value *> ExpandableBuffer::getInternalStreamBuffer(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
331
332    // ENTRY
333    Value * const capacityPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
334    Value * const capacity = iBuilder->CreateLoad(capacityPtr);
335    Value * const streamSetPtr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
336    Value * const streamSet = iBuilder->CreateLoad(streamSetPtr);
337    blockIndex = modByBufferBlocks(iBuilder, blockIndex);
338
339    assert (streamIndex->getType() == capacity->getType());
340    Value * const cond = iBuilder->CreateICmpULT(streamIndex, capacity);
341
342    // Are we guaranteed that we can access this stream?
343    if (readOnly || isCapacityGuaranteed(streamIndex, mInitialCapacity)) {
344        iBuilder->CreateAssert(cond, "ExpandableBuffer: out-of-bounds stream access");
345        Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, capacity), streamIndex);
346        return {streamSet, offset};
347    }
348
349    BasicBlock * const entry = iBuilder->GetInsertBlock();
350    BasicBlock * const expand = BasicBlock::Create(iBuilder->getContext(), "expand", entry->getParent());
351    BasicBlock * const resume = BasicBlock::Create(iBuilder->getContext(), "resume", entry->getParent());
352
353    iBuilder->CreateLikelyCondBr(cond, resume, expand);
354
355    // EXPAND
356    iBuilder->SetInsertPoint(expand);
357
358    Type * elementType = getType()->getStructElementType(1)->getPointerElementType();
359    Constant * const vectorWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(elementType), capacity->getType(), false);
360
361    Value * newCapacity = iBuilder->CreateAdd(streamIndex, iBuilder->getSize(1));
362    newCapacity = iBuilder->CreateCeilLog2(newCapacity);
363    newCapacity = iBuilder->CreateShl(iBuilder->getSize(1), newCapacity, "newCapacity");
364
365    std::string tmp;
366    raw_string_ostream out(tmp);
367    out << "__expand";
368    elementType->print(out);
369    std::string name = out.str();
370
371    Module * const m = iBuilder->getModule();
372    Function * expandFunction = m->getFunction(name);
373
374    if (expandFunction == nullptr) {
375
376        const auto ip = iBuilder->saveIP();
377
378        FunctionType * fty = FunctionType::get(elementType->getPointerTo(), {elementType->getPointerTo(), iBuilder->getSizeTy(), iBuilder->getSizeTy()}, false);
379        expandFunction = Function::Create(fty, GlobalValue::PrivateLinkage, name, m);
380
381        auto args = expandFunction->arg_begin();
382        Value * streamSet = &*args++;
383        Value * capacity = &*args++;
384        Value * newCapacity = &*args;
385
386        BasicBlock * entry = BasicBlock::Create(iBuilder->getContext(), "entry", expandFunction);
387        iBuilder->SetInsertPoint(entry);
388
389        Value * size = iBuilder->CreateMul(newCapacity, iBuilder->getSize(mBufferBlocks));
390        Value * newStreamSet = iBuilder->CreatePointerCast(iBuilder->CreateAlignedMalloc(iBuilder->CreateMul(size, vectorWidth), iBuilder->getCacheAlignment()), elementType->getPointerTo());
391        Value * const diffCapacity = iBuilder->CreateMul(iBuilder->CreateSub(newCapacity, capacity), vectorWidth);
392
393        const auto alignment = elementType->getPrimitiveSizeInBits() / 8;
394        for (unsigned i = 0; i < mBufferBlocks; ++i) {
395            ConstantInt * const offset = iBuilder->getSize(i);
396            Value * srcOffset = iBuilder->CreateMul(capacity, offset);
397            Value * srcPtr = iBuilder->CreateGEP(streamSet, srcOffset);
398            Value * destOffset = iBuilder->CreateMul(newCapacity, offset);
399            Value * destPtr = iBuilder->CreateGEP(newStreamSet, destOffset);
400            iBuilder->CreateMemCpy(destPtr, srcPtr, iBuilder->CreateMul(capacity, vectorWidth), alignment);
401            Value * destZeroOffset = iBuilder->CreateAdd(destOffset, capacity);
402            Value * destZeroPtr = iBuilder->CreateGEP(newStreamSet, destZeroOffset);
403            iBuilder->CreateMemZero(destZeroPtr, diffCapacity, alignment);
404        }
405
406        iBuilder->CreateAlignedFree(streamSet);
407
408        iBuilder->CreateRet(newStreamSet);
409
410        iBuilder->restoreIP(ip);
411    }
412
413    Value * newStreamSet = iBuilder->CreateCall(expandFunction, {streamSet, capacity, newCapacity});
414    iBuilder->CreateStore(newStreamSet, streamSetPtr);
415    iBuilder->CreateStore(newCapacity, capacityPtr);
416
417    iBuilder->CreateBr(resume);
418
419    // RESUME
420    iBuilder->SetInsertPoint(resume);
421
422    PHINode * phiStreamSet = iBuilder->CreatePHI(streamSet->getType(), 2);
423    phiStreamSet->addIncoming(streamSet, entry);
424    phiStreamSet->addIncoming(newStreamSet, expand);
425
426    PHINode * phiCapacity = iBuilder->CreatePHI(capacity->getType(), 2);
427    phiCapacity->addIncoming(capacity, entry);
428    phiCapacity->addIncoming(newCapacity, expand);
429
430    Value * offset = iBuilder->CreateAdd(iBuilder->CreateMul(blockIndex, phiCapacity), streamIndex);
431
432    return {phiStreamSet, offset};
433}
434
435Value * ExpandableBuffer::getStreamBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, const bool readOnly) const {
436    Value * ptr, * offset;
437    std::tie(ptr, offset) = getInternalStreamBuffer(iBuilder, self, streamIndex, blockIndex, readOnly);
438    return iBuilder->CreateGEP(ptr, offset);
439}
440
441Value * ExpandableBuffer::getStreamPackPtr(IDISA::IDISA_Builder * const iBuilder, Value * self, Value * streamIndex, Value * blockIndex, Value * packIndex, const bool readOnly) const {
442    Value * ptr, * offset;
443    std::tie(ptr, offset) = getInternalStreamBuffer(iBuilder, self, streamIndex, blockIndex, readOnly);
444    return iBuilder->CreateGEP(ptr, {offset, packIndex});
445}
446
447Value * ExpandableBuffer::getStreamSetCount(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
448    return iBuilder->CreateLoad(iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
449}
450
451Value * ExpandableBuffer::getBaseAddress(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
452    iBuilder->CreateAssert(self, "ExpandableBuffer: instance cannot be null");
453    Value * const baseAddr = iBuilder->CreateLoad(iBuilder->CreateGEP(self, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
454    iBuilder->CreateAssert(self, "ExpandableBuffer: base address cannot be 0");
455    return baseAddr;
456}
457
458void ExpandableBuffer::releaseBuffer(IDISA::IDISA_Builder * const iBuilder, Value * self) const {
459    iBuilder->CreateAlignedFree(getBaseAddress(iBuilder, self));
460}
461
462Value * ExpandableBuffer::getStreamSetBlockPtr(IDISA::IDISA_Builder * const iBuilder, Value *, Value *) const {
463    report_fatal_error("Expandable buffers: getStreamSetBlockPtr is not supported.");
464}
465
466Value * ExpandableBuffer::getLinearlyAccessibleItems(IDISA::IDISA_Builder * const iBuilder, Value *) const {
467    report_fatal_error("Expandable buffers: getLinearlyAccessibleItems is not supported.");
468}
469
470// Constructors
471SingleBlockBuffer::SingleBlockBuffer(const std::unique_ptr<kernel::KernelBuilder> &  b, Type * type)
472: StreamSetBuffer(BufferKind::BlockBuffer, type, resolveStreamSetType(b, type), 1, 0) {
473    mUniqueID = "S";
474}
475
476SourceBuffer::SourceBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, unsigned MemoryAddressSpace, unsigned StructAddressSpace)
477: StreamSetBuffer(BufferKind::SourceBuffer, type, StructType::get(resolveStreamSetType(b, type)->getPointerTo(MemoryAddressSpace), b->getSizeTy(), nullptr), 1, StructAddressSpace) {
478    mUniqueID = "B";
479    if (MemoryAddressSpace != 0 || StructAddressSpace != 0) {
480        mUniqueID += "@" + std::to_string(MemoryAddressSpace) + ":" + std::to_string(StructAddressSpace);
481    }
482}
483
484ExternalBuffer::ExternalBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, llvm::Value * addr, unsigned AddressSpace)
485: StreamSetBuffer(BufferKind::ExternalBuffer, type, resolveStreamSetType(b, type), 1, AddressSpace) {
486    mUniqueID = "E";
487    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
488    mStreamSetBufferPtr = b->CreatePointerBitCastOrAddrSpaceCast(addr, getPointerType());
489}
490
491CircularBuffer::CircularBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
492: StreamSetBuffer(BufferKind::CircularBuffer, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace) {
493    mUniqueID = "C" + std::to_string(bufferBlocks);
494    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
495}
496
497CircularBuffer::CircularBuffer(const BufferKind k, const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
498: StreamSetBuffer(k, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace) {
499
500}
501
502CircularCopybackBuffer::CircularCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned AddressSpace)
503: CircularBuffer(BufferKind::CircularCopybackBuffer, b, type, bufferBlocks, AddressSpace)
504, mOverflowBlocks(overflowBlocks) {
505    mUniqueID = "CC" + std::to_string(bufferBlocks);
506    if (mOverflowBlocks != 1) mUniqueID += "_" + std::to_string(mOverflowBlocks);
507    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
508}
509
510ExpandableBuffer::ExpandableBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, unsigned AddressSpace)
511: StreamSetBuffer(BufferKind::ExpandableBuffer, type, resolveExpandableStreamSetType(b, type), bufferBlocks, AddressSpace)
512, mInitialCapacity(type->getArrayNumElements()) {
513    mUniqueID = "XP" + std::to_string(bufferBlocks);
514    if (AddressSpace > 0) mUniqueID += "@" + std::to_string(AddressSpace);
515}
516
517SwizzledCopybackBuffer::SwizzledCopybackBuffer(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type, size_t bufferBlocks, size_t overflowBlocks, unsigned fieldwidth, unsigned AddressSpace)
518: StreamSetBuffer(BufferKind::SwizzledCopybackBuffer, type, resolveStreamSetType(b, type), bufferBlocks, AddressSpace), mOverflowBlocks(overflowBlocks), mFieldWidth(fieldwidth) {
519    mUniqueID = "SW" + std::to_string(fieldwidth) + ":" + std::to_string(bufferBlocks);
520    if (mOverflowBlocks != 1) {
521        mUniqueID += "_" + std::to_string(mOverflowBlocks);
522    }
523    if (AddressSpace > 0) {
524        mUniqueID += "@" + std::to_string(AddressSpace);
525    }
526}
527
528inline StreamSetBuffer::StreamSetBuffer(BufferKind k, Type * baseType, Type * resolvedType, unsigned BufferBlocks, unsigned AddressSpace)
529: mBufferKind(k)
530, mType(resolvedType)
531, mBufferBlocks(BufferBlocks)
532, mAddressSpace(AddressSpace)
533, mStreamSetBufferPtr(nullptr)
534, mBaseType(baseType)
535, mProducer(nullptr) {
536
537}
538
539StreamSetBuffer::~StreamSetBuffer() { }
540
541// Helper routines
542ArrayType * resolveStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
543    unsigned numElements = 1;
544    if (LLVM_LIKELY(type->isArrayTy())) {
545        numElements = type->getArrayNumElements();
546        type = type->getArrayElementType();
547    }
548    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
549        type = type->getVectorElementType();
550        if (LLVM_LIKELY(type->isIntegerTy())) {
551            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
552            type = b->getBitBlockType();
553            if (fieldWidth != 1) {
554                type = ArrayType::get(type, fieldWidth);
555            }
556            return ArrayType::get(type, numElements);
557        }
558    }
559    std::string tmp;
560    raw_string_ostream out(tmp);
561    type->print(out);
562    out << " is an unvalid stream set buffer type.";
563    report_fatal_error(out.str());
564}
565
566StructType * resolveExpandableStreamSetType(const std::unique_ptr<kernel::KernelBuilder> & b, Type * type) {
567    if (LLVM_LIKELY(type->isArrayTy())) {
568        type = type->getArrayElementType();
569    }
570    if (LLVM_LIKELY(type->isVectorTy() && type->getVectorNumElements() == 0)) {
571        type = type->getVectorElementType();
572        if (LLVM_LIKELY(type->isIntegerTy())) {
573            const auto fieldWidth = cast<IntegerType>(type)->getBitWidth();
574            type = b->getBitBlockType();
575            if (fieldWidth != 1) {
576                type = ArrayType::get(type, fieldWidth);
577            }
578            return StructType::get(b->getSizeTy(), type->getPointerTo(), nullptr);
579        }
580    }
581    std::string tmp;
582    raw_string_ostream out(tmp);
583    type->print(out);
584    out << " is an unvalid stream set buffer type.";
585    report_fatal_error(out.str());
586}
Note: See TracBrowser for help on using the repository browser.