source: icGREP/icgrep-devel/icgrep/pablo/carrypack_manager.cpp @ 6155

Last change on this file since 6155 was 5836, checked in by nmedfort, 20 months ago

Added PabloBlock/Builder? createScope() methods + minor code changes.

File size: 60.1 KB
Line 
1/*
2 *  Copyright (c) 2015 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include "carrypack_manager.h"
8#include <pablo/carry_data.h>
9#include <pablo/codegenstate.h>
10#include <llvm/IR/BasicBlock.h>
11#include <llvm/IR/DerivedTypes.h>
12#include <pablo/branch.h>
13#include <pablo/pe_advance.h>
14#include <pablo/pe_scanthru.h>
15#include <pablo/pe_matchstar.h>
16#include <pablo/pe_var.h>
17#include <kernels/kernel_builder.h>
18#include <toolchain/toolchain.h>
19#include <array>
20
21#include <llvm/Support/CommandLine.h>
22
23#include <llvm/Support/raw_ostream.h>
24
25using namespace llvm;
26
27namespace pablo {
28
29inline static bool is_power_2(const unsigned n) {
30    return (n && ((n & (n - 1)) == 0));
31}
32
33inline static unsigned ceil_log2(const unsigned v) {
34    assert ("log2(0) is undefined!" && v != 0);
35    return (sizeof(unsigned) * CHAR_BIT) - __builtin_clz(v - 1U);
36}
37
38inline static unsigned floor_log2(const unsigned v) {
39    assert ("log2(0) is undefined!" && v != 0);
40    return ((sizeof(unsigned) * CHAR_BIT) - 1U) - __builtin_clz(v);
41}
42
43inline static unsigned nearest_pow2(const unsigned v) {
44    assert (v > 0 && v < (UINT32_MAX / 2));
45    return (v < 2) ? 1 : (1U << ceil_log2(v));
46}
47
48inline static unsigned nearest_multiple(const unsigned n, const unsigned m) {
49    assert (is_power_2(m));
50    return (n + m - 1U) & ~(m - 1U);
51}
52
53inline static bool is_multiple_of(const unsigned n, const unsigned m) {
54    return nearest_multiple(n, m) == n;
55}
56
57inline static unsigned udiv(const unsigned x, const unsigned y) {
58    assert (is_power_2(y));
59    const unsigned z = x >> floor_log2(y);
60    assert (z == (x / y));
61    return z;
62}
63
64inline static unsigned ceil_udiv(const unsigned x, const unsigned y) {
65    assert (is_power_2(x) && is_power_2(y));
66    return udiv(((x - 1U) | (y - 1U)) + 1U, y);
67}
68
69inline static unsigned getElementWidth(Type * ty) {
70    if (LLVM_LIKELY(isa<VectorType>(ty))) {
71        ty = cast<IntegerType>(ty->getVectorElementType());
72    }
73    return cast<IntegerType>(ty)->getBitWidth();
74}
75
76inline static unsigned gcd(unsigned a, unsigned b) {
77  while (a) {
78     assert (is_power_2(a));
79     const unsigned c = a;
80     a = b & (a - 1);
81     b = c;
82  }
83  return b;
84}
85
86inline static unsigned getPackingSize(const unsigned elementWidth, const unsigned depth) {
87    return std::max<unsigned>(elementWidth / nearest_pow2(depth + 1), 1);
88}
89
90using TypeId = PabloAST::ClassTypeId;
91
92#define ELEMENTS_IN_DYNAMICALLY_ALLOCATED_CARRY_STRUCT 3
93
94/** ------------------------------------------------------------------------------------------------------------- *
95 * @brief initializeCarryData
96 ** ------------------------------------------------------------------------------------------------------------- */
97void CarryManager::initializeCarryData(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, PabloKernel * const kernel) {
98
99    // Each scope constructs its own CarryData struct, which will be added to the final "carries" struct
100    // that is added to the Kernel. The scope index will indicate which struct to access.
101
102    // A CarryData struct either contains an array of CarryPackBlocks or an integer indicating the capacity of
103    // the variable length CarryData struct and pointer. A variable length CarryData struct is required whenever
104    // the streams accessed by a loop could vary between iterations. When resizing a CarryData struct for a
105    // particular loop, the current loop struct and all nested structs need to be resized. This accommodates
106    // the fact every pablo While loop must be executed at least once.
107
108    // A nested loop may also contain a variable length CarryData struct
109
110    // To determine whether we require a variable length CarryData struct, we test the escaped variables of
111    // each loop branch to see whether they are used as the index parameter of a nested Extract statement.
112    // Any scope that requires variable length CarryData, requires that all nested branches have a unique
113    // set of carries for that iteration.
114
115    assert (mKernel == nullptr);
116
117    mCurrentScope = kernel->getEntryScope();
118    mKernel = kernel;
119
120    Type * const carryTy = iBuilder->getBitBlockType();
121    mVectorWidth = carryTy->getPrimitiveSizeInBits();
122    mElementWidth = getElementWidth(carryTy);
123    assert (is_power_2(mElementWidth));
124
125    mCarryScopes = 0;
126    mCarryMetadata.resize(getScopeCount(mCurrentScope));
127    mCarryGroup.resize(assignDefaultCarryGroups(kernel->getEntryScope()));
128
129    kernel->setCarryDataTy(analyse(iBuilder, mCurrentScope));
130
131    kernel->addScalar(kernel->getCarryDataTy(), "carries");
132
133    if (mHasLoop) {
134        kernel->addScalar(iBuilder->getInt32Ty(), "selector");
135    }
136    if (mHasLongAdvance) {
137        kernel->addScalar(iBuilder->getSizeTy(), "CarryBlockIndex");
138    }
139}
140
141bool isDynamicallyAllocatedType(const Type * const ty) {
142    if (isa<StructType>(ty) && ty->getStructNumElements() == ELEMENTS_IN_DYNAMICALLY_ALLOCATED_CARRY_STRUCT) {
143        return (ty->getStructElementType(1)->isPointerTy() && ty->getStructElementType(2)->isPointerTy() && ty->getStructElementType(0)->isIntegerTy());
144    }
145    return false;
146}
147
148bool containsDynamicallyAllocatedType(const Type * const ty) {
149    if (isa<StructType>(ty)) {
150        for (unsigned i = 0; i < ty->getStructNumElements(); ++i) {
151            if (isDynamicallyAllocatedType(ty->getStructElementType(i))) {
152                return true;
153            }
154        }
155    }
156    return false;
157}
158
159void freeDynamicallyAllocatedMemory(const std::unique_ptr<kernel::KernelBuilder> & idb, Value * const frame) {
160    StructType * const ty = cast<StructType>(frame->getType()->getPointerElementType());
161    std::array<Value *, 3> indices;
162    indices[0] = idb->getInt32(0);
163    for (unsigned i = 0; i < ty->getStructNumElements(); ++i) {
164        if (isDynamicallyAllocatedType(ty->getStructElementType(i))) {
165            indices[1] = idb->getInt32(i);
166            indices[2] = idb->getInt32(1);
167            Value * const innerFrame = idb->CreateLoad(idb->CreateGEP(frame, ArrayRef<Value*>(indices.data(), 3)));
168            if (containsDynamicallyAllocatedType(innerFrame->getType())) {
169                indices[2] = indices[0];
170                Value *  const count = idb->CreateLoad(idb->CreateGEP(frame, ArrayRef<Value*>(indices.data(), 3)));
171                BasicBlock * const entry = idb->GetInsertBlock();
172                BasicBlock * const cond = idb->CreateBasicBlock("freeCarryDataCond");
173                BasicBlock * const body = idb->CreateBasicBlock("freeCarryDataLoop");
174                BasicBlock * const exit = idb->CreateBasicBlock("freeCarryDataExit");
175                idb->CreateBr(cond);
176                idb->SetInsertPoint(cond);
177                PHINode * const index = idb->CreatePHI(count->getType(), 2);
178                index->addIncoming(ConstantInt::getNullValue(count->getType()), entry);
179                Value * test = idb->CreateICmpNE(index, count);
180                idb->CreateCondBr(test, body, exit);
181                idb->SetInsertPoint(body);
182                freeDynamicallyAllocatedMemory(idb, idb->CreateGEP(innerFrame, index));
183                index->addIncoming(idb->CreateAdd(index, ConstantInt::get(count->getType(), 1)), body);
184                idb->CreateBr(cond);
185                idb->SetInsertPoint(exit);
186            }
187            idb->CreateFree(innerFrame);
188            indices[2] = idb->getInt32(2);
189            Value *  const summary = idb->CreateLoad(idb->CreateGEP(frame, ArrayRef<Value*>(indices.data(), 3)));
190            idb->CreateFree(summary);
191        }
192    }
193}
194
195/** ------------------------------------------------------------------------------------------------------------- *
196 * @brief releaseCarryData
197 ** ------------------------------------------------------------------------------------------------------------- */
198void CarryManager::releaseCarryData(const std::unique_ptr<kernel::KernelBuilder> & idb) {
199    if (mHasNonCarryCollapsingLoops) {
200        freeDynamicallyAllocatedMemory(idb, idb->getScalarFieldPtr("carries"));
201    }
202}
203
204/** ------------------------------------------------------------------------------------------------------------- *
205 * @brief initializeCodeGen
206 ** ------------------------------------------------------------------------------------------------------------- */
207void CarryManager::initializeCodeGen(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
208
209    assert(!mCarryMetadata.empty());
210    mCarryInfo = &mCarryMetadata[0];
211    assert (!mCarryInfo->hasSummary());
212
213    mCurrentFrame = iBuilder->getScalarFieldPtr("carries");
214    mCurrentFrameIndex = 0;
215    mCarryScopes = 0;
216    mCarryScopeIndex.push_back(0);
217
218    assert (mCurrentFrameOffset.empty());
219
220    mCurrentFrameOffset.push_back(iBuilder->getInt32(0));
221
222    assert (mNonCarryCollapsingLoopCarryFrameStack.empty());
223
224    assert (mCarrySummaryStack.empty());
225
226    Type * const carryTy = iBuilder->getBitBlockType();
227
228    mCarrySummaryStack.push_back(Constant::getNullValue(carryTy));
229
230    if (mHasLoop) {       
231        mLoopSelector[0] = iBuilder->getScalarField("selector");
232        mLoopSelector[1] = iBuilder->CreateXor(mLoopSelector[0], ConstantInt::get(mLoopSelector[0]->getType(), 1));
233    }
234
235}
236
237/** ------------------------------------------------------------------------------------------------------------- *
238 * @brief finalizeCodeGen
239 ** ------------------------------------------------------------------------------------------------------------- */
240void CarryManager::finalizeCodeGen(const std::unique_ptr<kernel::KernelBuilder> & iBuilder) {
241    if (mHasLoop) {
242        iBuilder->setScalarField("selector", mLoopSelector[1]);
243    }
244    if (mHasLongAdvance) {
245        Value * idx = iBuilder->getScalarField("CarryBlockIndex");
246        idx = iBuilder->CreateAdd(idx, iBuilder->getSize(1));
247        iBuilder->setScalarField("CarryBlockIndex", idx);
248    }
249    assert (mNonCarryCollapsingLoopCarryFrameStack.empty());
250    assert ("base summary value was deleted!" && mCarrySummaryStack.size() == 1);
251    assert ("base summary value was overwritten with non-zero value!" && isa<Constant>(mCarrySummaryStack[0]) && cast<Constant>(mCarrySummaryStack[0])->isNullValue());
252    mCarrySummaryStack.clear();
253    assert (mCarryScopeIndex.size() == 1);
254    mCarryScopeIndex.clear();
255}
256
257/** ------------------------------------------------------------------------------------------------------------- *
258 * @brief enterLoopScope
259 ** ------------------------------------------------------------------------------------------------------------- */
260void CarryManager::enterLoopScope(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, const PabloBlock * const scope) {
261    assert (scope);
262    assert (mHasLoop);
263    ++mLoopDepth;
264    enterScope(iBuilder, scope);
265}
266
267/** ------------------------------------------------------------------------------------------------------------- *
268 * @brief enterLoopBody
269 ** ------------------------------------------------------------------------------------------------------------- */
270void CarryManager::enterLoopBody(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, BasicBlock * const entryBlock) {
271    if (mCarryInfo->hasSummary()) {
272        Type * const carryTy = iBuilder->getBitBlockType();
273        PHINode * phiCarryOutSummary = iBuilder->CreatePHI(carryTy, 2, "summary");
274        assert (!mCarrySummaryStack.empty());
275        phiCarryOutSummary->addIncoming(mCarrySummaryStack.back(), entryBlock);
276        // Replace the incoming carry summary with the phi node and add the phi node to the stack  so that we can
277        // properly OR it into the outgoing summary value.
278        // NOTE: this may change the base summary value; when exiting to the base scope, replace this summary with
279        // a null value to prevent subsequent nested scopes from inheriting the summary of this scope.
280        mCarrySummaryStack.back() = phiCarryOutSummary;
281        mCarrySummaryStack.push_back(phiCarryOutSummary);
282    }
283    if (LLVM_UNLIKELY(mCarryInfo->nonCarryCollapsingMode())) {
284
285        assert (mCarryInfo->hasSummary());
286
287        Type * const int8PtrTy = iBuilder->getInt8PtrTy();
288        Type * const carryTy = iBuilder->getBitBlockType();
289        PointerType * const carryPtrTy = carryTy->getPointerTo();
290
291        // Check whether we need to resize the carry state
292        PHINode * index = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2);
293        mLoopIndicies.push_back(index);
294        index->addIncoming(iBuilder->getSize(0), entryBlock);
295        Value * capacityPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
296        Value * capacity = iBuilder->CreateLoad(capacityPtr, "capacity");
297        Constant * const ONE = ConstantInt::get(capacity->getType(), 1);
298        Value * arrayPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(1)});
299        Value * array = iBuilder->CreateLoad(arrayPtr, "array");
300        BasicBlock * const entry = iBuilder->GetInsertBlock();
301        BasicBlock * const resizeCarryState = iBuilder->CreateBasicBlock("ResizeCarryState");
302        BasicBlock * const reallocExisting = iBuilder->CreateBasicBlock("ReallocExisting");
303        BasicBlock * const createNew = iBuilder->CreateBasicBlock("CreateNew");
304        BasicBlock * const resumeKernel = iBuilder->CreateBasicBlock("ResumeKernel");
305        iBuilder->CreateLikelyCondBr(iBuilder->CreateICmpNE(index, capacity), resumeKernel, resizeCarryState);
306
307        // RESIZE CARRY BLOCK
308        iBuilder->SetInsertPoint(resizeCarryState);
309        const auto BlockWidth = iBuilder->getBitBlockWidth() / 8;
310        const auto Log2BlockWidth = floor_log2(BlockWidth);
311        Constant * const carryStateWidth = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(array->getType()->getPointerElementType()), iBuilder->getSizeTy(), false);
312        Value * const summaryPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(2)});
313        Value * const hasCarryState = iBuilder->CreateICmpNE(array, ConstantPointerNull::get(cast<PointerType>(array->getType())));
314        iBuilder->CreateLikelyCondBr(hasCarryState, reallocExisting, createNew);
315
316        // REALLOCATE EXISTING
317        iBuilder->SetInsertPoint(reallocExisting);
318        Value * const capacitySize = iBuilder->CreateMul(capacity, carryStateWidth);
319        Value * const newCapacitySize = iBuilder->CreateShl(capacitySize, 1); // x 2
320        Value * const newArray = iBuilder->CreateCacheAlignedMalloc(newCapacitySize);
321        iBuilder->CreateMemCpy(newArray, array, capacitySize, iBuilder->getCacheAlignment());
322        iBuilder->CreateFree(array);
323        iBuilder->CreateStore(newArray, arrayPtr);
324        Value * const startNewArrayPtr = iBuilder->CreateGEP(iBuilder->CreatePointerCast(newArray, int8PtrTy), capacitySize);
325        iBuilder->CreateMemZero(startNewArrayPtr, capacitySize, BlockWidth);
326        Value * const newCapacity = iBuilder->CreateShl(capacity, 1);
327        iBuilder->CreateStore(newCapacity, capacityPtr);
328        Value * const summary = iBuilder->CreateLoad(summaryPtr, false);
329        Value * const summarySize = iBuilder->CreateShl(iBuilder->CreateAdd(iBuilder->CreateCeilLog2(capacity), ONE), Log2BlockWidth + 1);
330        Constant * const additionalSpace = iBuilder->getSize(2 * BlockWidth);
331        Value * const newSummarySize = iBuilder->CreateAdd(summarySize, additionalSpace);
332        Value * const newSummary = iBuilder->CreateBlockAlignedMalloc(newSummarySize);
333        iBuilder->CreateMemCpy(newSummary, summary, summarySize, BlockWidth);
334        iBuilder->CreateFree(summary);
335        iBuilder->CreateStore(iBuilder->CreatePointerCast(newSummary, carryPtrTy), summaryPtr);
336        Value * const startNewSummaryPtr = iBuilder->CreateGEP(iBuilder->CreatePointerCast(newSummary, int8PtrTy), summarySize);
337        iBuilder->CreateMemZero(startNewSummaryPtr, additionalSpace, BlockWidth);
338        iBuilder->CreateBr(resumeKernel);
339
340        // CREATE NEW
341        iBuilder->SetInsertPoint(createNew);
342        Constant * const initialLog2Capacity = iBuilder->getInt64(4);
343        Constant * const initialCapacity = ConstantExpr::getShl(ONE, initialLog2Capacity);
344        iBuilder->CreateStore(initialCapacity, capacityPtr);
345        Constant * const initialCapacitySize = ConstantExpr::getMul(initialCapacity, carryStateWidth);
346        Value * initialArray = iBuilder->CreateCacheAlignedMalloc(initialCapacitySize);
347        iBuilder->CreateMemZero(initialArray, initialCapacitySize, BlockWidth);
348        initialArray = iBuilder->CreatePointerCast(initialArray, array->getType());
349        iBuilder->CreateStore(initialArray, arrayPtr);
350        Constant * initialSummarySize = ConstantExpr::getShl(ConstantExpr::getAdd(initialLog2Capacity, iBuilder->getInt64(1)), iBuilder->getInt64(Log2BlockWidth + 1));
351        Value * initialSummary = iBuilder->CreateBlockAlignedMalloc(initialSummarySize);
352        iBuilder->CreateMemZero(initialSummary, initialSummarySize, BlockWidth);
353        initialSummary = iBuilder->CreatePointerCast(initialSummary, carryPtrTy);
354        iBuilder->CreateStore(initialSummary, summaryPtr);
355        iBuilder->CreateBr(resumeKernel);
356
357        // RESUME KERNEL
358        iBuilder->SetInsertPoint(resumeKernel);
359        PHINode * phiArrayPtr = iBuilder->CreatePHI(array->getType(), 3);
360        phiArrayPtr->addIncoming(array, entry);
361        phiArrayPtr->addIncoming(initialArray, createNew);
362        phiArrayPtr->addIncoming(newArray, reallocExisting);
363        mNonCarryCollapsingLoopCarryFrameStack.emplace_back(mCurrentFrame, std::vector<Value *>{mCurrentFrameOffset.begin(), mCurrentFrameOffset.end()});
364        mCurrentFrame = iBuilder->CreateGEP(phiArrayPtr, index);
365        assert (&std::get<1>(mNonCarryCollapsingLoopCarryFrameStack.back()) != &mCurrentFrameOffset);
366        mCurrentFrameOffset.resize(1);
367    }
368}
369
370/** ------------------------------------------------------------------------------------------------------------- *
371 * @brief leaveLoopBody
372 ** ------------------------------------------------------------------------------------------------------------- */
373void CarryManager::leaveLoopBody(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, BasicBlock * /* exitBlock */) {
374
375    Type * const carryTy = iBuilder->getBitBlockType();
376
377    if (LLVM_UNLIKELY(mCarryInfo->nonCarryCollapsingMode())) {
378
379        assert (mCarryInfo->hasSummary());
380
381        ConstantInt * const summaryIndex = iBuilder->getInt32(mCarryInfo->hasExplicitSummary() ? mCurrentFrameIndex : (mCurrentFrameIndex - 1));
382
383        Value * const carryInAccumulator = readCarryInSummary(iBuilder, summaryIndex);
384        Value * const carryOutAccumulator = mCarrySummaryStack.back();
385
386        if (mCarryInfo->hasExplicitSummary()) {
387            writeCarryOutSummary(iBuilder, carryOutAccumulator, summaryIndex);
388        }
389        std::tie(mCurrentFrame, mCurrentFrameOffset) = mNonCarryCollapsingLoopCarryFrameStack.back();
390        mNonCarryCollapsingLoopCarryFrameStack.pop_back();
391
392        // In non-carry-collapsing mode, we cannot rely on the fact that performing a single iteration of this
393        // loop will consume all of the incoming carries from the prior block. We need to subtract the carries
394        // consumed by this iteration from our carry summary state. To do so in parallel, we use the the half-
395        // subtractor circuit to do it in ceil log2 steps. Similarly, we compute our carry out summary state
396        // (for the subsequent block to subtract) using a half-adder circuit.
397
398        // NOTE: this requires that, for all loop iterations, i, and all block iterations, j, the carry in
399        // summary, CI_i,j, matches the carry out summary of the prior block iteration, CO_i,j - 1.
400        // Otherwise we will end up with an incorrect result or being trapped in an infinite loop.
401
402        Value * capacityPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(0)});
403        Value * capacity = iBuilder->CreateLoad(capacityPtr, false);
404        Value * summaryPtr = iBuilder->CreateGEP(mCurrentFrame, {iBuilder->getInt32(0), iBuilder->getInt32(2)});
405        Value * summary = iBuilder->CreateLoad(summaryPtr, false);
406
407        Constant * const ONE = ConstantInt::get(capacity->getType(), 1);
408
409        Value * loopSelector = iBuilder->CreateZExt(mLoopSelector[0], capacity->getType());
410
411        BasicBlock * entry = iBuilder->GetInsertBlock();
412        BasicBlock * update = iBuilder->CreateBasicBlock("UpdateNonCarryCollapsingSummary");
413        BasicBlock * resume = iBuilder->CreateBasicBlock("ResumeAfterUpdatingNonCarryCollapsingSummary");
414
415        iBuilder->CreateBr(update);
416
417        iBuilder->SetInsertPoint(update);
418        PHINode * i = iBuilder->CreatePHI(capacity->getType(), 2);
419        i->addIncoming(ConstantInt::getNullValue(capacity->getType()), entry);
420        PHINode * const borrow = iBuilder->CreatePHI(carryInAccumulator->getType(), 2);
421        borrow->addIncoming(carryInAccumulator, entry);
422        PHINode * const carry = iBuilder->CreatePHI(carryOutAccumulator->getType(), 2);
423        carry->addIncoming(carryOutAccumulator, entry);
424        // OR the updated carry in summary later for the summaryTest
425        PHINode * const carryInSummary = iBuilder->CreatePHI(carryTy, 2);
426        carryInSummary->addIncoming(Constant::getNullValue(carryTy), entry);
427
428        // half subtractor
429        Value * const carryInOffset = iBuilder->CreateOr(iBuilder->CreateShl(i, 1), loopSelector);
430        Value * const carryInPtr = iBuilder->CreateGEP(summary, carryInOffset);
431        Value * const carryIn = iBuilder->CreateBlockAlignedLoad(carryInPtr);
432        Value * const nextCarryIn = iBuilder->CreateXor(carryIn, borrow);
433        Value * const nextSummary = iBuilder->CreateOr(carryInSummary, nextCarryIn);
434        iBuilder->CreateBlockAlignedStore(nextCarryIn, carryInPtr);
435        carryInSummary->addIncoming(nextSummary, update);
436        Value * finalBorrow = iBuilder->CreateAnd(iBuilder->CreateNot(carryIn), borrow);
437        borrow->addIncoming(finalBorrow, update);
438
439        // half adder
440        Value * const carryOutOffset = iBuilder->CreateXor(carryInOffset, ConstantInt::get(carryInOffset->getType(), 1));
441        Value * const carryOutPtr = iBuilder->CreateGEP(summary, carryOutOffset);
442        Value * const carryOut = iBuilder->CreateBlockAlignedLoad(carryOutPtr);
443        Value * const nextCarryOut = iBuilder->CreateXor(carryOut, carry);
444        iBuilder->CreateBlockAlignedStore(nextCarryOut, carryOutPtr);
445        Value * finalCarry = iBuilder->CreateAnd(carryOut, carry);
446        carry->addIncoming(finalCarry, update);
447
448        // loop condition
449        i->addIncoming(iBuilder->CreateAdd(i, ONE), update);
450        iBuilder->CreateCondBr(iBuilder->CreateICmpNE(iBuilder->CreateShl(ONE, i), capacity), update, resume);
451
452        iBuilder->SetInsertPoint(resume);
453
454        iBuilder->CreateAssertZero(iBuilder->CreateOr(finalBorrow, finalCarry),
455                                   "CarryPackManager: loop post-condition violated: final borrow and carry must be zero!");
456
457        assert (!mLoopIndicies.empty());
458        PHINode * index = mLoopIndicies.back();
459        index->addIncoming(iBuilder->CreateAdd(index, iBuilder->getSize(1)), resume);
460        mLoopIndicies.pop_back();
461
462        mNextSummaryTest = nextSummary;
463    }
464    if (mCarryInfo->hasSummary()) {
465        const auto n = mCarrySummaryStack.size(); assert (n > 1);
466        Value * carryOut = mCarrySummaryStack.back();
467        mCarrySummaryStack.pop_back();
468        PHINode * phiCarryOut = cast<PHINode>(mCarrySummaryStack.back());
469        phiCarryOut->addIncoming(carryOut, iBuilder->GetInsertBlock());
470        // If we're returning to the base scope, reset our accumulated summary value.
471        if (n == 2) {
472            carryOut = Constant::getNullValue(carryTy);
473        }
474        mCarrySummaryStack.back() = carryOut;
475    }
476}
477
478/** ------------------------------------------------------------------------------------------------------------- *
479 * @brief leaveLoopScope
480 ** ------------------------------------------------------------------------------------------------------------- */
481void CarryManager::leaveLoopScope(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, BasicBlock * const /* entryBlock */, BasicBlock * const /* exitBlock */) {
482    assert (mLoopDepth > 0);
483    --mLoopDepth;
484    leaveScope(iBuilder);
485}
486
487/** ------------------------------------------------------------------------------------------------------------- *
488 * @brief enterIfScope
489 ** ------------------------------------------------------------------------------------------------------------- */
490void CarryManager::enterIfScope(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, const PabloBlock * const scope) {
491    ++mIfDepth;
492    enterScope(iBuilder, scope);
493    // We zero-initialized the nested summary value and later OR in the current summary into the escaping summary
494    // so that upon processing the subsequent block iteration, we branch into this If scope iff a carry out was
495    // generated by a statement within this If scope and not by a dominating statement in the outer scope.
496    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
497        assert (mCurrentFrameIndex == 0);
498        mNextSummaryTest = readCarryInSummary(iBuilder, iBuilder->getInt32(0));
499        if (mCarryInfo->hasExplicitSummary()) {
500            mCurrentFrameIndex = 1;
501        }
502    }
503    Type * const carryTy = iBuilder->getBitBlockType();
504    mCarrySummaryStack.push_back(Constant::getNullValue(carryTy));
505}
506
507/** ------------------------------------------------------------------------------------------------------------- *
508 * @brief generateSummaryTest
509 ** ------------------------------------------------------------------------------------------------------------- */
510Value * CarryManager::generateSummaryTest(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, Value * condition) {
511    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
512        assert ("summary test was not generated" && mNextSummaryTest);
513        condition = iBuilder->simd_or(condition, mNextSummaryTest);
514        mNextSummaryTest = nullptr;
515    }
516    assert ("summary test was not consumed" && (mNextSummaryTest == nullptr));
517    return condition;
518}
519
520/** ------------------------------------------------------------------------------------------------------------- *
521 * @brief enterIfBody
522 ** ------------------------------------------------------------------------------------------------------------- */
523void CarryManager::enterIfBody(const std::unique_ptr<kernel::KernelBuilder> & /* iBuilder */, BasicBlock * const entryBlock) {
524    assert (entryBlock);
525}
526
527/** ------------------------------------------------------------------------------------------------------------- *
528 * @brief leaveIfBody
529 ** ------------------------------------------------------------------------------------------------------------- */
530void CarryManager::leaveIfBody(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, BasicBlock * const exitBlock) {
531    assert (exitBlock);
532    const auto n = mCarrySummaryStack.size();
533    if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
534        writeCarryOutSummary(iBuilder, mCarrySummaryStack[n - 1], iBuilder->getInt32(0));
535    }
536    if (n > 2) {
537        mCarrySummaryStack[n - 1] = iBuilder->CreateOr(mCarrySummaryStack[n - 1], mCarrySummaryStack[n - 2], "summary");
538    }
539}
540
541/** ------------------------------------------------------------------------------------------------------------- *
542 * @brief leaveIfScope
543 ** ------------------------------------------------------------------------------------------------------------- */
544void CarryManager::leaveIfScope(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, BasicBlock * const entryBlock, BasicBlock * const exitBlock) {
545    assert (mIfDepth > 0);
546    if (LLVM_LIKELY(mCarryInfo->hasSummary())) {
547        const auto n = mCarrySummaryStack.size(); assert (n > 0);
548        if (n > 2) {
549            // When leaving a nested If scope with a summary value, phi out the summary to ensure the
550            // appropriate summary is stored in the outer scope.
551            Value * nested = mCarrySummaryStack[n - 1];
552            Value * outer = mCarrySummaryStack[n - 2];
553            assert (nested->getType() == outer->getType());
554            PHINode * const phi = iBuilder->CreatePHI(nested->getType(), 2, "summary");
555            phi->addIncoming(outer, entryBlock);
556            phi->addIncoming(nested, exitBlock);
557            mCarrySummaryStack[n - 2] = phi;
558        }
559    }
560    --mIfDepth;
561    leaveScope(iBuilder);
562    mCarrySummaryStack.pop_back();
563}
564
565/** ------------------------------------------------------------------------------------------------------------ *
566 * @brief enterScope
567 ** ------------------------------------------------------------------------------------------------------------- */
568void CarryManager::enterScope(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, const PabloBlock * const scope) {
569    assert (scope);
570    // Store the state of the current frame and update the scope state
571    mCurrentFrameOffset.push_back(iBuilder->getInt32(mCurrentFrameIndex));
572    mCurrentScope = scope;
573    mCarryScopeIndex.push_back(++mCarryScopes);
574    mCarryInfo = &mCarryMetadata[mCarryScopes];
575    mCurrentFrameIndex = 0;
576}
577
578/** ------------------------------------------------------------------------------------------------------------- *
579 * @brief leaveScope
580 ** ------------------------------------------------------------------------------------------------------------- */
581void CarryManager::leaveScope(const std::unique_ptr<kernel::KernelBuilder> & /* iBuilder */) {
582
583    assert (mCurrentFrameOffset.size() > 1);
584    ConstantInt * const carryIndex = cast<ConstantInt>(mCurrentFrameOffset.back());
585    mCurrentFrameIndex = carryIndex->getLimitedValue() + 1;
586    mCurrentFrameOffset.pop_back();
587
588    mCarryScopeIndex.pop_back();
589    assert (!mCarryScopeIndex.empty());
590    mCurrentScope = mCurrentScope->getPredecessor();
591    assert (mCurrentScope);
592    mCarryInfo = &mCarryMetadata[mCarryScopeIndex.back()];
593}
594
595/** ------------------------------------------------------------------------------------------------------------- *
596 * @brief addCarryInCarryOut
597 ** ------------------------------------------------------------------------------------------------------------- */
598Value * CarryManager::addCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, const CarryProducingStatement * const op, Value * const e1, Value * const e2) {
599    assert (op && !isa<Advance>(op));
600    Value * const carryIn = getCarryIn(iBuilder, op);
601    Value * carryOut, * result;
602    std::tie(carryOut, result) = iBuilder->bitblock_add_with_carry(e1, e2, carryIn);
603    setCarryOut(iBuilder, op, carryOut);
604    assert (result->getType() == iBuilder->getBitBlockType());
605    return result;
606}
607
608/** ------------------------------------------------------------------------------------------------------------- *
609 * @brief advanceCarryInCarryOut
610 ** ------------------------------------------------------------------------------------------------------------- */
611Value * CarryManager::advanceCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, const Advance * const advance, Value * const value) {
612    const auto shiftAmount = advance->getAmount();
613    if (LLVM_LIKELY(shiftAmount < mElementWidth)) {
614        Value * const carryIn = getCarryIn(iBuilder, advance);
615        Value * carryOut, * result;
616        std::tie(carryOut, result) = iBuilder->bitblock_advance(value, carryIn, shiftAmount);
617        setCarryOut(iBuilder, advance, carryOut);
618        assert (result->getType() == iBuilder->getBitBlockType());
619        return result;
620    } else {
621        return longAdvanceCarryInCarryOut(iBuilder, value, shiftAmount);
622    }
623}
624
625
626/** ------------------------------------------------------------------------------------------------------------- *
627 * @brief indexedAdvanceCarryInCarryOut
628 ** ------------------------------------------------------------------------------------------------------------- */
629Value * CarryManager::indexedAdvanceCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & b, const IndexedAdvance * const advance, Value * const strm, Value * const index_strm) {
630    const auto shiftAmount = advance->getAmount();
631    if (LLVM_LIKELY(shiftAmount < mElementWidth)) {
632        Value * const carryIn = getNextCarryIn(b);
633        Value * carryOut, * result;
634        std::tie(carryOut, result) = b->bitblock_indexed_advance(strm, index_strm, carryIn, shiftAmount);
635        setNextCarryOut(b, carryOut);
636        return result;
637    } else if (shiftAmount <= b->getBitBlockWidth()) {
638        Value * carryPtr = b->CreateGEP(mCurrentFrame, {b->getInt32(0), b->getInt32(mCurrentFrameIndex++), b->getInt32(0)});
639        Value * carryIn = b->CreateBlockAlignedLoad(carryPtr);
640        Value * carryOut, * result;
641        std::tie(carryOut, result) = b->bitblock_indexed_advance(strm, index_strm, carryIn, shiftAmount);
642        b->CreateBlockAlignedStore(carryOut, carryPtr);
643        if ((mIfDepth > 0) && mCarryInfo->hasExplicitSummary()) {
644            addToCarryOutSummary(b, strm);
645        }
646        return result;
647    } else {
648        mIndexedLongAdvanceIndex++;
649        llvm::report_fatal_error("IndexedAdvance > BlockSize not yet supported.");
650    }
651}
652
653
654/** ------------------------------------------------------------------------------------------------------------- *
655 * @brief longAdvanceCarryInCarryOut
656 ** ------------------------------------------------------------------------------------------------------------- */
657inline Value * CarryManager::longAdvanceCarryInCarryOut(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, Value * const value, const unsigned shiftAmount) {
658
659    assert (mHasLongAdvance);
660    assert (shiftAmount >= mElementWidth);
661
662    Type * const streamTy = iBuilder->getIntNTy(iBuilder->getBitBlockWidth());
663
664    if (mIfDepth > 0) {
665        if (shiftAmount > iBuilder->getBitBlockWidth()) {
666
667            mCurrentFrameOffset.push_back(iBuilder->getInt32(mCurrentFrameIndex++));
668            mCurrentFrameOffset.push_back(nullptr);
669
670            Value * carry = iBuilder->CreateZExt(iBuilder->bitblock_any(value), streamTy);
671            const unsigned summarySize = ceil_udiv(shiftAmount, iBuilder->getBitBlockWidth() * iBuilder->getBitBlockWidth());
672            for (unsigned i = 0;;++i) {
673
674                mCurrentFrameOffset.back() = iBuilder->getInt32(i);
675
676                Value * const ptr = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
677                Value * const prior = iBuilder->CreateBitCast(iBuilder->CreateBlockAlignedLoad(ptr), streamTy);
678                Value * const stream = iBuilder->CreateBitCast(iBuilder->CreateOr(iBuilder->CreateShl(prior, 1), carry), iBuilder->getBitBlockType());
679                if (LLVM_LIKELY(i == summarySize)) {
680                    Value * const maskedStream = iBuilder->CreateAnd(stream, iBuilder->bitblock_mask_from(iBuilder->getInt32(summarySize % iBuilder->getBitBlockWidth())));
681                    addToCarryOutSummary(iBuilder, maskedStream);
682                    iBuilder->CreateBlockAlignedStore(maskedStream, ptr);
683                    break;
684                }
685                addToCarryOutSummary(iBuilder, stream);
686                iBuilder->CreateBlockAlignedStore(stream, ptr);
687                carry = iBuilder->CreateLShr(prior, iBuilder->getBitBlockWidth() - 1);
688            }
689
690            mCurrentFrameOffset.pop_back();
691            mCurrentFrameOffset.pop_back();
692
693        } else if (LLVM_LIKELY(mCarryInfo->hasExplicitSummary())) {
694            addToCarryOutSummary(iBuilder, value);
695        }
696    }
697    mCurrentFrameOffset.push_back(iBuilder->getInt32(mCurrentFrameIndex++));
698    Value * result = nullptr;
699    // special case using a single buffer entry and the carry_out value.
700    if (LLVM_LIKELY((shiftAmount < iBuilder->getBitBlockWidth()) && (mLoopDepth == 0))) {
701        mCurrentFrameOffset.push_back(iBuilder->getInt32(0));
702        Value * const buffer = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
703        assert (buffer->getType()->getPointerElementType() == iBuilder->getBitBlockType());
704        Value * carryIn = iBuilder->CreateBlockAlignedLoad(buffer);
705        iBuilder->CreateBlockAlignedStore(value, buffer);
706        /* Very special case - no combine */
707        if (LLVM_UNLIKELY(shiftAmount == iBuilder->getBitBlockWidth())) {
708            return iBuilder->CreateBitCast(carryIn, iBuilder->getBitBlockType());
709        }
710        Value * block0_shr = iBuilder->CreateLShr(iBuilder->CreateBitCast(carryIn, streamTy), iBuilder->getBitBlockWidth() - shiftAmount);
711        Value * block1_shl = iBuilder->CreateShl(iBuilder->CreateBitCast(value, streamTy), shiftAmount);
712        result = iBuilder->CreateBitCast(iBuilder->CreateOr(block1_shl, block0_shr), iBuilder->getBitBlockType());
713    } else { //
714        const unsigned blockShift = shiftAmount % iBuilder->getBitBlockWidth();
715        const unsigned blocks = ceil_udiv(shiftAmount, iBuilder->getBitBlockWidth());
716        // Create a mask to implement circular buffer indexing
717        Value * const indexMask = iBuilder->getSize(nearest_pow2(blocks + ((mLoopDepth != 0) ? 1 : 0)) - 1);
718        Value * const blockIndex = iBuilder->getScalarField("CarryBlockIndex");
719        Value * const carryIndex0 = iBuilder->CreateSub(blockIndex, iBuilder->getSize(blocks));
720        Value * const loadIndex0 = iBuilder->CreateAnd(carryIndex0, indexMask);
721        mCurrentFrameOffset.push_back(loadIndex0);
722
723        Value * const carryInPtr = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
724        Value * const carryIn = iBuilder->CreateBlockAlignedLoad(carryInPtr);
725        Value * const storeIndex = iBuilder->CreateAnd(blockIndex, indexMask);
726        mCurrentFrameOffset.back() = storeIndex;
727
728        Value * const carryOutPtr = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
729        assert (carryIn->getType() == iBuilder->getBitBlockType());
730        // If the long advance is an exact multiple of BitBlockWidth, we simply return the oldest
731        // block in the long advance carry data area.
732        if (LLVM_UNLIKELY(blockShift == 0)) {
733            iBuilder->CreateBlockAlignedStore(value, carryOutPtr);
734            result = carryIn;
735        } else { // Otherwise we need to combine data from the two oldest blocks.
736            Value * carryIndex1 = iBuilder->CreateSub(blockIndex, iBuilder->getSize(blocks - 1));
737            Value * loadIndex1 = iBuilder->CreateAnd(carryIndex1, indexMask);
738            mCurrentFrameOffset.back() = loadIndex1;
739            Value * const carryInPtr2 = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
740            Value * carry_block1 = iBuilder->CreateBlockAlignedLoad(carryInPtr2);
741            Value * block0_shr = iBuilder->CreateLShr(iBuilder->CreateBitCast(carryIn, streamTy), iBuilder->getBitBlockWidth() - blockShift);
742            Value * block1_shl = iBuilder->CreateShl(iBuilder->CreateBitCast(carry_block1, streamTy), blockShift);
743            iBuilder->CreateBlockAlignedStore(value, carryOutPtr);
744            result = iBuilder->CreateBitCast(iBuilder->CreateOr(block1_shl, block0_shr), iBuilder->getBitBlockType());
745        }
746    }
747    mCurrentFrameOffset.pop_back();
748    mCurrentFrameOffset.pop_back();
749    return result;
750}
751
752/** ------------------------------------------------------------------------------------------------------------- *
753 * @brief getNextCarryIn
754 ** ------------------------------------------------------------------------------------------------------------- */
755Value * CarryManager::getCarryIn(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, const CarryProducingStatement * const op) {
756
757    VectorType * const carryTy = iBuilder->getBitBlockType();
758
759    const auto carryGroup = op->getCarryGroup();
760    assert (carryGroup < mCarryGroup.size());
761    CarryGroup & group = mCarryGroup[carryGroup];
762
763    Value * carryIn = group.carryIn;
764    if (carryIn) {
765        // if this carry crosses a non-carry-collapsing loop frame, compute the address for this carry in the 'new' frame.
766        Value * const frame = cast<GetElementPtrInst>(cast<LoadInst>(carryIn)->getPointerOperand())->getPointerOperand();
767        carryIn = (frame == mCurrentFrame) ? carryIn : nullptr;
768    }
769
770    if (carryIn == nullptr) {
771        mCurrentFrameOffset.push_back(iBuilder->getInt32(mCurrentFrameIndex));
772        if (LLVM_UNLIKELY(mLoopDepth != 0)) {
773            assert ("Loop selector was not initialized!" && mLoopSelector[0]);
774            mCurrentFrameOffset.push_back(mLoopSelector[0]);
775        }
776        Value * ptr = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
777        carryIn = iBuilder->CreateBlockAlignedLoad(ptr);
778        carryIn = iBuilder->CreateBitCast(carryIn, carryTy);
779
780        group.carryIn = carryIn;
781        group.carryOut = nullptr;
782        group.frameIndex = mCurrentFrameIndex++;
783        group.packedSize = 0;
784
785        // If we're within a loop, we need to clear out the carry in value for the subsequent loop iteration
786        if (LLVM_UNLIKELY(mLoopDepth != 0)) {
787            iBuilder->CreateBlockAlignedStore(Constant::getNullValue(carryTy), ptr);
788            mCurrentFrameOffset.pop_back();
789        }
790        mCurrentFrameOffset.pop_back();
791        if (LLVM_UNLIKELY(group.groupSize == 1)) {
792            return carryIn;
793        }
794    }
795
796    // Initially, our carry in is densely packed. Our goal is to move the carry to the 0-th position and leave
797    // all other values zeroed out. We can do so easily using ShuffleVector by moving the appropriate element
798    // and selecting 0s for all other elements but this produces poor code by LLVM.
799
800    // Instead we divide this process into two stages:
801
802    // First use the blend instruction to select only the elements of the carry we want
803
804
805
806    const auto width = std::max<unsigned>(gcd(std::min<unsigned>(op->getCarryWidth(), mElementWidth), group.packedSize), 8);
807    const auto n = udiv(iBuilder->getBitBlockWidth(), width);
808
809    VectorType * packTy = VectorType::get(iBuilder->getIntNTy(width), n);
810
811    Constant * const zero = Constant::getNullValue(packTy);
812
813    carryIn = iBuilder->CreateBitCast(carryIn, packTy);
814
815    if (LLVM_UNLIKELY(group.groupSize > 1)) {
816        int blend_mask[n];
817        for (unsigned i = 0; i < n; ++i) {
818            const auto w = i * width;
819            if (w >= group.packedSize && w < (group.packedSize + op->getCarryWidth())) {
820                blend_mask[i] = i;
821            } else {
822                blend_mask[i] = i + n;
823            }
824        }
825        carryIn = iBuilder->CreateShuffleVector(carryIn, zero, ArrayRef<int>(blend_mask, n));
826    }
827
828    // Then use a byte shift to move them to the 0-th position
829
830    const auto offset = udiv(group.packedSize, width);
831
832    if (offset) {
833        int shift[n];
834        for (unsigned i = 0; i < n; ++i) {
835            shift[i] = offset + i;
836        }
837        carryIn = iBuilder->CreateShuffleVector(carryIn, zero, ArrayRef<int>(shift, n));
838    }
839
840    // if this element contains more than one carry, we need to mask mask off any subsequent carries
841    const unsigned nextPackedSize = group.packedSize + op->getCarryWidth();
842    const unsigned subsequentOffset = (-nextPackedSize) & (width - 1U);
843    if (LLVM_UNLIKELY(subsequentOffset != 0)) {
844        carryIn = iBuilder->CreateShl(carryIn, subsequentOffset);
845    }
846
847    // then shift out the prior carries while moving the current carry to the correct position
848    const unsigned trailingOffset = subsequentOffset + (group.packedSize & (width - 1U));
849    assert (trailingOffset < width);
850    if (LLVM_UNLIKELY(trailingOffset != 0)) {
851        carryIn = iBuilder->CreateLShr(carryIn, trailingOffset);
852    }
853
854    carryIn = iBuilder->CreateBitCast(carryIn, carryTy, "CarryIn_" + op->getName());
855
856    return carryIn;
857}
858
859/** ------------------------------------------------------------------------------------------------------------- *
860 * @brief setNextCarryOut
861 ** ------------------------------------------------------------------------------------------------------------- */
862void CarryManager::setCarryOut(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, const CarryProducingStatement * const op, Value * carryOut) {
863
864    VectorType * const carryTy = iBuilder->getBitBlockType();
865
866    assert ("Unexpected carry out value type!" && carryOut->getType()->canLosslesslyBitCastTo(carryTy));
867
868    const auto carryGroup = op->getCarryGroup();
869    assert (carryGroup < mCarryGroup.size());
870    CarryGroup & group = mCarryGroup[carryGroup];
871
872    const auto width = std::max<unsigned>(gcd(op->getCarryWidth(), group.packedSize), 8);
873    const auto count = udiv(iBuilder->getBitBlockWidth(), width);
874    VectorType * packTy = VectorType::get(iBuilder->getIntNTy(width), count);
875
876    carryOut = iBuilder->CreateBitCast(carryOut, packTy);
877
878    // shuffle the carryOut to have the 0-th slot being in the correct packed offset
879    const auto index = udiv(group.packedSize, width);
880
881    if (index) {
882        assert (index < count);
883        int position[count];
884        for (unsigned i = 0; i < count; ++i) {
885            position[i] = ((count - index) + i);
886        }
887        Constant * const zero = Constant::getNullValue(packTy);
888        carryOut = iBuilder->CreateShuffleVector(zero, carryOut, ArrayRef<int>(position, count));
889    }
890
891    const auto offset = group.packedSize & (width - 1U);
892    if (LLVM_UNLIKELY(offset != 0)) {
893        carryOut = iBuilder->CreateShl(carryOut, offset);
894    }
895    carryOut = iBuilder->CreateBitCast(carryOut, carryTy);
896
897    assert (op->getCarryWidth() > 0);
898
899    if (group.carryOut == nullptr) {
900        group.carryOut = carryOut;
901    } else {
902        #ifndef NDEBUG
903        iBuilder->CreateAssertZero(iBuilder->CreateAnd(group.carryOut, carryOut),
904                               "CarryPackManager: bit collision detected when combining partial carry outs");
905        #endif
906        group.carryOut = iBuilder->CreateOr(group.carryOut, carryOut);
907    }
908
909    group.packedSize += op->getCarryWidth();
910
911    if (LLVM_UNLIKELY(group.groupSize == 1)) {
912        Value * ptr = nullptr;
913        if (LLVM_LIKELY(mLoopDepth == 0)) {
914            ptr = cast<LoadInst>(group.carryIn)->getPointerOperand();
915        } else {
916            mCurrentFrameOffset.push_back(iBuilder->getInt32(group.frameIndex));
917            mCurrentFrameOffset.push_back(mLoopSelector[1]);
918            ptr = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
919            mCurrentFrameOffset.pop_back();
920            mCurrentFrameOffset.pop_back();
921            if (LLVM_LIKELY(!mCarryInfo->nonCarryCollapsingMode())) {
922                group.carryOut = iBuilder->CreateOr(group.carryOut, iBuilder->CreateBlockAlignedLoad(ptr));
923            }
924        }
925
926        if (mCarryInfo->hasSummary()) {
927            // TODO: if this group is all within a single scope, only add the packed carry to the summary
928            addToCarryOutSummary(iBuilder, group.carryOut);
929        }
930
931        iBuilder->CreateBlockAlignedStore(group.carryOut, ptr);
932    }
933
934    group.groupSize -= 1;
935
936}
937
938/** ------------------------------------------------------------------------------------------------------------- *
939 * @brief readCarryInSummary
940 ** ------------------------------------------------------------------------------------------------------------- */
941Value * CarryManager::readCarryInSummary(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, ConstantInt * index) {
942    assert (mCarryInfo->hasSummary());
943    const auto size = mCurrentFrameOffset.size();
944    // If we have a borrowed summary, we cannot be sure how deeply nested it is but do know that it will be the first
945    // element of a nested struct that is not a struct. Traverse inwards until we find it.
946    if (LLVM_UNLIKELY(mCarryInfo->hasBorrowedSummary())) {
947        Type * frameTy = mCurrentFrame->getType()->getPointerElementType();
948        for (unsigned i = 1; i < mCurrentFrameOffset.size(); ++i) {
949            frameTy = frameTy->getStructElementType(cast<ConstantInt>(mCurrentFrameOffset[i])->getLimitedValue());
950        }
951        assert (frameTy->isStructTy());
952        unsigned count = 1;
953        for (;;) {
954            frameTy = frameTy->getStructElementType(0);
955            if (!frameTy->isStructTy()) {
956                break;
957            }
958            ++count;
959        }
960        assert (count > 0);
961        mCurrentFrameOffset.insert(mCurrentFrameOffset.end(), count - 1, iBuilder->getInt32(0));
962    }
963    mCurrentFrameOffset.push_back(index);
964    if (mLoopDepth != 0) {
965        mCurrentFrameOffset.push_back(mLoopSelector[0]);
966    }
967    Value * const summaryPtr = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
968    mCurrentFrameOffset.resize(size);
969    Value * const summary = iBuilder->CreateBlockAlignedLoad(summaryPtr);
970    if (mLoopDepth != 0 && mCarryInfo->hasExplicitSummary()) {
971        Type * const carryTy = iBuilder->getBitBlockType();
972        iBuilder->CreateBlockAlignedStore(Constant::getNullValue(carryTy), summaryPtr);
973    }
974    return summary;
975}
976
977/** ------------------------------------------------------------------------------------------------------------- *
978 * @brief writeCarryOutSummary
979 ** ------------------------------------------------------------------------------------------------------------- */
980inline void CarryManager::writeCarryOutSummary(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, Value * const summary, ConstantInt * index) {
981    assert (mCarryInfo->hasExplicitSummary());
982    mCurrentFrameOffset.push_back(index);
983    if (mLoopDepth != 0) {
984        mCurrentFrameOffset.push_back(mLoopSelector[1]);
985    }
986    Value * const summaryPtr = iBuilder->CreateGEP(mCurrentFrame, mCurrentFrameOffset);
987    iBuilder->CreateBlockAlignedStore(summary, summaryPtr);
988    if (mLoopDepth != 0) {
989        mCurrentFrameOffset.pop_back();
990    }
991    mCurrentFrameOffset.pop_back();
992}
993
994/** ------------------------------------------------------------------------------------------------------------- *
995 * @brief addToCarryOutSummary
996 ** ------------------------------------------------------------------------------------------------------------- */
997inline void CarryManager::addToCarryOutSummary(const std::unique_ptr<kernel::KernelBuilder> & iBuilder, Value * const value) {
998    assert ("cannot add null summary value!" && value);   
999    assert ("summary stack is empty!" && !mCarrySummaryStack.empty());
1000    assert ("current scope does not have a summary!" && mCarryInfo->hasSummary());
1001    Value * const currentSummary = mCarrySummaryStack.back();
1002    mCarrySummaryStack.back() = iBuilder->CreateOr(value, currentSummary);
1003}
1004
1005/** ------------------------------------------------------------------------------------------------------------- *
1006 * @brief enumerate
1007 ** ------------------------------------------------------------------------------------------------------------- */
1008unsigned CarryManager::getScopeCount(const PabloBlock * const scope, unsigned index) {
1009    for (const Statement * stmt : *scope) {
1010        if (LLVM_UNLIKELY(isa<Branch>(stmt))) {
1011            index = getScopeCount(cast<Branch>(stmt)->getBody(), index);
1012        }
1013    }
1014    return index + 1;
1015}
1016
1017/** ------------------------------------------------------------------------------------------------------------- *
1018 * @brief hasIterationSpecificAssignment
1019 ** ------------------------------------------------------------------------------------------------------------- */
1020bool CarryManager::hasIterationSpecificAssignment(const PabloBlock * const scope) {
1021#if 0
1022    return dyn_cast_or_null<While>(scope->getBranch()) != nullptr;
1023#else
1024    if (const While * const br = dyn_cast_or_null<While>(scope->getBranch())) {
1025        for (const Var * var : br->getEscaped()) {
1026            for (const PabloAST * user : var->users()) {
1027                if (const Extract * e = dyn_cast<Extract>(user)) {
1028                    if (LLVM_UNLIKELY(e->getIndex() == var)) {
1029                        // If we assign this Var a value and read the value as the index parameter
1030                        // of a nested Extract statement, then we cannot collapse the carries.
1031                        const PabloBlock * parent = e->getParent();
1032                        for (;;) {
1033                            if (parent == scope) {
1034                                return true;
1035                            }
1036                            parent = parent->getPredecessor();
1037                            if (parent == nullptr) {
1038                                break;
1039                            }
1040                        }
1041                    }
1042                }
1043            }
1044        }
1045    }
1046    return false;
1047#endif
1048}
1049
1050/** ------------------------------------------------------------------------------------------------------------- *
1051 * @brief assignDefaultCarryGroups
1052 ** ------------------------------------------------------------------------------------------------------------- */
1053unsigned CarryManager::assignDefaultCarryGroups(PabloBlock * const scope, const unsigned ifDepth, const unsigned loopDepth, unsigned carryGroups) {
1054    const auto packingSize = getPackingSize(mVectorWidth, (ifDepth + loopDepth));
1055    unsigned packedWidth = 0;
1056    for (Statement * stmt : *scope) {
1057        if (LLVM_UNLIKELY(isa<CarryProducingStatement>(stmt))) {
1058            unsigned amount = 1;
1059            bool canPack = true;
1060            if (LLVM_LIKELY(isa<Advance>(stmt))) {
1061                amount = cast<Advance>(stmt)->getAmount();
1062                canPack = (amount < mElementWidth);
1063            }
1064            else if (isa<IndexedAdvance>(stmt)) {
1065                amount = cast<Advance>(stmt)->getAmount();
1066                canPack = (amount < mElementWidth);
1067            }
1068            if (packedWidth == 0) {
1069                ++carryGroups;
1070            }
1071            if (LLVM_LIKELY(canPack)) {
1072                amount = nearest_multiple(amount, packingSize);
1073                // if we cannot insert this carry into the current pack, start a new group
1074                if ((packedWidth + amount) > mVectorWidth) {
1075                    ++carryGroups;
1076                    packedWidth = amount;
1077                } else {
1078                    packedWidth += amount;
1079                }
1080            } else if (LLVM_LIKELY(packedWidth != 0)) {
1081                ++carryGroups;
1082                packedWidth = 0;
1083            }
1084            assert (carryGroups > 0);
1085            cast<CarryProducingStatement>(stmt)->setCarryGroup(carryGroups - 1);
1086            cast<CarryProducingStatement>(stmt)->setCarryWidth(amount);
1087        } else if (LLVM_UNLIKELY(isa<Branch>(stmt))) {
1088            const auto nestedIfDepth = ifDepth + isa<If>(stmt) ? 1 : 0;
1089            const auto nestedLoopDepth = loopDepth + isa<If>(stmt) ? 0 : 1;
1090            carryGroups = assignDefaultCarryGroups(cast<Branch>(stmt)->getBody(), nestedIfDepth, nestedLoopDepth, carryGroups);
1091            packedWidth = 0;
1092        }
1093    }
1094    return carryGroups;
1095}
1096
1097
1098/** ------------------------------------------------------------------------------------------------------------- *
1099 * @brief analyse
1100 ** ------------------------------------------------------------------------------------------------------------- */
1101StructType * CarryManager::analyse(const std::unique_ptr<kernel::KernelBuilder> & iBuilder,
1102                                   const PabloBlock * const scope,
1103                                   const unsigned ifDepth, const unsigned loopDepth,
1104                                   const bool isNestedWithinNonCarryCollapsingLoop) {
1105
1106    assert ("scope cannot be null!" && scope);
1107    assert ("the entry scope -- and only the entry scope -- must be in carry scope 0"
1108            && (mCarryScopes == 0 ? (scope == mKernel->getEntryScope()) : (scope != mKernel->getEntryScope())));
1109    assert (mCarryScopes < mCarryMetadata.size());
1110
1111    Type * const carryTy = iBuilder->getBitBlockType();
1112
1113    CarryData & cd = mCarryMetadata[mCarryScopes++];
1114    const bool nonCarryCollapsingMode = hasIterationSpecificAssignment(scope);
1115    Type * const carryPackTy = (loopDepth == 0) ? carryTy : ArrayType::get(carryTy, 2);
1116    std::vector<Type *> state;
1117
1118    for (const Statement * stmt : *scope) {
1119        if (LLVM_UNLIKELY(isa<CarryProducingStatement>(stmt))) {
1120            const auto index = cast<CarryProducingStatement>(stmt)->getCarryGroup();
1121            assert (index < mCarryGroup.size());
1122            CarryGroup & carryGroup = mCarryGroup[index];
1123            if (carryGroup.groupSize == 0) {
1124                Type * packTy = carryPackTy;
1125                if (LLVM_UNLIKELY(isa<Advance>(stmt))) {
1126                    const auto amount = cast<Advance>(stmt)->getAmount();
1127                    if (LLVM_UNLIKELY(amount >= mElementWidth)) {
1128                        if (LLVM_UNLIKELY(ifDepth > 0 && amount > iBuilder->getBitBlockWidth())) {
1129                            // 1 bit will mark the presense of any bit in each block.
1130                            state.push_back(ArrayType::get(carryTy, ceil_udiv(amount, std::pow(iBuilder->getBitBlockWidth(), 2))));
1131                        }
1132                        mHasLongAdvance = true;
1133                        const auto blocks = ceil_udiv(amount, iBuilder->getBitBlockWidth());
1134                        packTy = ArrayType::get(carryTy, nearest_pow2(blocks + ((loopDepth != 0) ? 1 : 0)));
1135                    }
1136                }
1137                if (LLVM_UNLIKELY(isa<IndexedAdvance>(stmt))) {
1138                    // The carry data for the indexed advance stores N bits of carry data,
1139                    // organized in packs that can be processed with GR instructions (such as PEXT, PDEP, popcount).
1140                    // A circular buffer is used.  Because the number of bits to be dequeued
1141                    // and enqueued is variable (based on the popcount of the index), an extra
1142                    // pack stores the offset position in the circular buffer.
1143                    const auto amount = cast<IndexedAdvance>(stmt)->getAmount();
1144                    const auto packWidth = sizeof(size_t) * 8;
1145                    const auto packs = ceil_udiv(amount, packWidth);
1146                    packTy = ArrayType::get(iBuilder->getSizeTy(), nearest_pow2(packs) + 1);
1147                }
1148                state.push_back(packTy);
1149            }
1150            carryGroup.groupSize += 1;
1151        } else if (LLVM_UNLIKELY(isa<Branch>(stmt))) {
1152            unsigned nestedIfDepth = ifDepth;
1153            unsigned nestedLoopDepth = loopDepth;
1154            if (LLVM_LIKELY(isa<If>(stmt))) {
1155                ++nestedIfDepth;
1156            } else {
1157                mHasLoop = true;
1158                ++nestedLoopDepth;
1159            }
1160            state.push_back(analyse(iBuilder, cast<Branch>(stmt)->getBody(),
1161                                    nestedIfDepth, nestedLoopDepth, nonCarryCollapsingMode | isNestedWithinNonCarryCollapsingLoop));
1162        }
1163    }
1164    // Build the carry state struct and add the summary pack if needed.
1165    StructType * carryState = nullptr;
1166    CarryData::SummaryType summaryType = CarryData::NoSummary;
1167    if (LLVM_UNLIKELY(state.empty())) {
1168        carryState = StructType::get(iBuilder->getContext());
1169    } else {
1170        if (dyn_cast_or_null<If>(scope->getBranch()) || nonCarryCollapsingMode || isNestedWithinNonCarryCollapsingLoop) {
1171            if (LLVM_LIKELY(state.size() > 1)) {
1172                summaryType = CarryData::ExplicitSummary;
1173                // NOTE: summaries are stored differently depending whether we're entering an If or While branch. With an If branch, they
1174                // preceed the carry state data and with a While loop they succeed it. This is to help cache prefectching performance.
1175                state.insert(isa<If>(scope->getBranch()) ? state.begin() : state.end(), carryPackTy);
1176            } else {
1177                summaryType = CarryData::ImplicitSummary;
1178                if (state[0]->isStructTy()) {
1179                    summaryType = CarryData::BorrowedSummary;
1180                }
1181            }           
1182        }
1183        carryState = StructType::get(iBuilder->getContext(), state);
1184        // If we're in a loop and cannot use collapsing carry mode, convert the carry state struct into a capacity,
1185        // carry state pointer, and summary pointer struct.
1186        if (LLVM_UNLIKELY(nonCarryCollapsingMode)) {
1187            mHasNonCarryCollapsingLoops = true;
1188            carryState = StructType::get(iBuilder->getContext(), {iBuilder->getSizeTy(), carryState->getPointerTo(), carryTy->getPointerTo()};
1189            assert (isDynamicallyAllocatedType(carryState));
1190        }
1191        cd.setNonCollapsingCarryMode(nonCarryCollapsingMode);
1192    }
1193    cd.setSummaryType(summaryType);
1194
1195    return carryState;
1196}
1197
1198/** ------------------------------------------------------------------------------------------------------------- *
1199 * @brief constructor
1200 ** ------------------------------------------------------------------------------------------------------------- */
1201CarryManager::CarryManager() noexcept
1202: mKernel(nullptr)
1203, mVectorWidth(0)
1204, mElementWidth(0)
1205, mCurrentFrame(nullptr)
1206, mCurrentFrameIndex(0)
1207, mCurrentScope(nullptr)
1208, mCarryInfo(nullptr)
1209, mNextSummaryTest(nullptr)
1210, mIfDepth(0)
1211, mHasLongAdvance(false)
1212, mHasNonCarryCollapsingLoops(false)
1213, mHasLoop(false)
1214, mLoopDepth(0)
1215, mLoopSelector{nullptr, nullptr}
1216, mCarryScopes(0) {
1217
1218}
1219
1220}
Note: See TracBrowser for help on using the repository browser.