source: icGREP/icgrep-devel/icgrep/pablo/carry_manager.cpp @ 4733

Last change on this file since 4733 was 4733, checked in by cameron, 4 years ago

Mac OS X requires alignment 16

File size: 30.1 KB
RevLine 
[4644]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
8#include <include/simd-lib/bitblock.hpp>
9#include <stdexcept>
[4683]10#include <pablo/carry_data.h>
11#include <pablo/codegenstate.h>
12#include <pablo/carry_manager.h>
13#include <pablo/pabloAST.h>
[4647]14#include <iostream>
[4722]15#include <llvm/Support/CommandLine.h>
[4726]16#include <llvm/IR/BasicBlock.h>
17#include <llvm/IR/CallingConv.h>
18#include <llvm/IR/Function.h>
[4644]19
[4726]20
[4715]21static cl::opt<CarryManagerStrategy> Strategy(cl::desc("Choose carry management strategy:"),
22                                              cl::values(
23                                                         clEnumVal(BitBlockStrategy, "Unpacked, each carry in a separate bitblock."),
24                                                         clEnumVal(SequentialFullyPackedStrategy, "Sequential packing, up to 64 carries per pack."),
25                                                         clEnumValEnd));
26
27
[4644]28namespace pablo {
[4687]29 
30    unsigned doScopeCount(PabloBlock * pb) {
31        unsigned count = 1;
32       
33        for (Statement * stmt : *pb) {
34            if (If * ifStatement = dyn_cast<If>(stmt)) {
35                count += doScopeCount(&ifStatement->getBody());
36            }
37            else if (While * whileStatement = dyn_cast<While>(stmt)) {
38                count += doScopeCount(&whileStatement->getBody());
39            }
40        }
41        return count;
42       
43    }
[4644]44
[4726]45void CarryManager::initialize(Module * m, PabloBlock * pb) {
[4644]46    mPabloRoot = pb;
[4687]47    unsigned scopeCount = doScopeCount(pb);
48    mCarryInfoVector.resize(scopeCount);
[4729]49    if (Strategy == SequentialFullyPackedStrategy) {
50        mPACK_SIZE = 64;
51        mITEMS_PER_PACK = 64;
52        mCarryPackType = mBuilder->getIntNTy(mPACK_SIZE);
53        mZeroInitializer = mBuilder->getInt64(0);
54        mOneInitializer = mBuilder->getInt64(-1);
55    }
56    else {
57        mPACK_SIZE = BLOCK_SIZE;
58        mITEMS_PER_PACK = 1;
59        mCarryPackType = mBitBlockType;
60    }
[4715]61    unsigned totalCarryDataSize = enumerate(pb, 0, 0);
[4687]62   
[4715]63    unsigned totalPackCount = (totalCarryDataSize + mITEMS_PER_PACK - 1)/mITEMS_PER_PACK;
64
[4703]65    mCarryPackPtr.resize(totalPackCount);
66    mCarryInPack.resize(totalPackCount);
67    mCarryOutPack.resize(totalPackCount);
68    for (auto i = 0; i < totalPackCount; i++) mCarryInPack[i]=nullptr;
[4715]69
70    if (Strategy == SequentialFullyPackedStrategy) {
[4729]71        mTotalCarryDataBitBlocks = (totalCarryDataSize + BLOCK_SIZE - 1)/BLOCK_SIZE;       
[4715]72    }
73    else {
74        mTotalCarryDataBitBlocks = totalCarryDataSize;
75    }
[4726]76   
77    ArrayType* cdArrayTy = ArrayType::get(mBitBlockType, mTotalCarryDataBitBlocks);
78    GlobalVariable* cdArray = new GlobalVariable(*m, cdArrayTy, /*isConstant=*/false, GlobalValue::CommonLinkage, /*Initializer=*/0, "process_block_carry_data");
79    cdArray->setAlignment(BLOCK_SIZE/8);
80    ConstantAggregateZero* cdInitData = ConstantAggregateZero::get(cdArrayTy);
81    cdArray->setInitializer(cdInitData);
82   
83    mCarryPackBasePtr = mBuilder->CreateBitCast(cdArray, PointerType::get(mCarryPackType, 0));
84    mCarryBitBlockPtr = mBuilder->CreateBitCast(cdArray, PointerType::get(mBitBlockType, 0));
85   
[4720]86    // Popcount data is stored after all the carry data.
87    if (mPabloCountCount > 0) {
[4726]88        ArrayType* pcArrayTy = ArrayType::get(mBuilder->getIntNTy(64), mPabloCountCount);
89        GlobalVariable* pcArray = new GlobalVariable(*m, pcArrayTy, /*isConstant=*/false, GlobalValue::CommonLinkage, 0, "popcount_data");
90        cdArray->setAlignment(BLOCK_SIZE/8);
91        ConstantAggregateZero* pcInitData = ConstantAggregateZero::get(pcArrayTy);
92        pcArray->setInitializer(pcInitData);
93        mPopcountBasePtr = mBuilder->CreateBitCast(pcArray, Type::getInt64PtrTy(mBuilder->getContext()));
[4720]94    }
[4715]95    // Carry Data area will have one extra bit block to store the block number.
[4726]96    GlobalVariable* blkNo = new GlobalVariable(*m, mBuilder->getIntNTy(64), /*isConstant=*/false, GlobalValue::CommonLinkage, 0, "blockNo");
[4733]97    blkNo->setAlignment(16);
[4726]98    blkNo->setInitializer(mBuilder->getInt64(0));
99    mBlockNoPtr = blkNo;
[4715]100    mBlockNo = mBuilder->CreateLoad(mBlockNoPtr);
[4690]101    /*  Set the current scope to PabloRoot */
102    mCurrentScope = mPabloRoot;
[4691]103    mCurrentFrameIndex = 0;
[4690]104    mCarryInfo = mCarryInfoVector[0];
[4644]105}
[4672]106   
[4644]107void CarryManager::generateBlockNoIncrement() {
108    mBuilder->CreateStore(mBuilder->CreateAdd(mBlockNo, mBuilder->getInt64(1)), mBlockNoPtr);
109}
110
111Value * CarryManager::getBlockNoPtr() {
112    return mBlockNoPtr;
113}
114
[4694]115
[4689]116unsigned CarryManager::enumerate(PabloBlock * blk, unsigned ifDepth, unsigned whileDepth) {
[4687]117    llvm::raw_os_ostream cerr(std::cerr);
118    unsigned idx = blk->getScopeIndex();
[4715]119    PabloBlockCarryData * cd = new PabloBlockCarryData(blk, mPACK_SIZE, mITEMS_PER_PACK);
[4687]120    mCarryInfoVector[idx] = cd;
121
122    cd->setIfDepth(ifDepth);
123    cd->setWhileDepth(whileDepth);
[4704]124    unsigned nestedOffset = cd->nested.frameOffset;
[4687]125 
126    for (Statement * stmt : *blk) {
[4720]127        if (Count * c = dyn_cast<Count>(stmt)) {
128            c->setGlobalCountIndex(mPabloCountCount);
129            mPabloCountCount++;
130        }
131        else if (If * ifStatement = dyn_cast<If>(stmt)) {
[4689]132            const unsigned ifCarryDataBits = enumerate(&ifStatement->getBody(), ifDepth+1, whileDepth);
[4687]133            PabloBlockCarryData * nestedBlockData = mCarryInfoVector[ifStatement->getBody().getScopeIndex()];
[4715]134            if (mITEMS_PER_PACK == mPACK_SIZE) {  // PACKING
[4714]135                if (cd->roomInFinalPack(nestedOffset) < ifCarryDataBits) {
[4715]136                    nestedOffset = alignCeiling(nestedOffset, mPACK_SIZE);
[4714]137                }
138            }
[4689]139            nestedBlockData->setFramePosition(nestedOffset);
140
[4687]141            nestedOffset += ifCarryDataBits;
142            if (cd->maxNestingDepth <= nestedBlockData->maxNestingDepth) cd->maxNestingDepth = nestedBlockData->maxNestingDepth + 1;
143            cd->nested.entries++;
[4732]144#ifdef CARRY_DEBUG
[4696]145            nestedBlockData->dumpCarryData(cerr);
146#endif
[4687]147        }
148        else if (While * whileStatement = dyn_cast<While>(stmt)) {
[4689]149            const unsigned whileCarryDataBits = enumerate(&whileStatement->getBody(), ifDepth, whileDepth+1);
[4687]150            PabloBlockCarryData * nestedBlockData = mCarryInfoVector[whileStatement->getBody().getScopeIndex()];
151            //if (whileStatement->isMultiCarry()) whileCarryDataBits *= whileStatement->getMaxIterations();
[4715]152            if (mITEMS_PER_PACK == mPACK_SIZE) {  // PACKING
[4714]153                if (cd->roomInFinalPack(nestedOffset) < whileCarryDataBits) {
[4715]154                    nestedOffset = alignCeiling(nestedOffset, mPACK_SIZE);
[4714]155                }
156            }
[4689]157            nestedBlockData->setFramePosition(nestedOffset);
[4687]158            nestedOffset += whileCarryDataBits;
159            if (cd->maxNestingDepth <= nestedBlockData->maxNestingDepth) cd->maxNestingDepth = nestedBlockData->maxNestingDepth + 1;
160            cd->nested.entries++;
[4732]161#ifdef CARRY_DEBUG
[4696]162            nestedBlockData->dumpCarryData(cerr);
163#endif
[4687]164        }
165    }
166   
[4704]167    cd->scopeCarryDataSize = nestedOffset;
[4687]168   
169    if (cd->explicitSummaryRequired()) {
170        // Need extra space for the summary variable, always the last
171        // entry within an if block.
[4715]172        if (mITEMS_PER_PACK == mPACK_SIZE) {  // PACKING
173            cd->scopeCarryDataSize = alignCeiling(cd->scopeCarryDataSize, mPACK_SIZE);
[4714]174        }
[4704]175        cd->summary.frameOffset = cd->scopeCarryDataSize;
[4715]176        cd->scopeCarryDataSize += mITEMS_PER_PACK;  //  computed summary is a full pack.
[4687]177    }
178    else {
[4704]179        cd->summary.frameOffset = 0;
[4687]180    }
[4732]181#ifdef CARRY_DEBUG
[4713]182    if (cd->ifDepth == 0) cd->dumpCarryData(cerr);
183#endif
[4704]184    return cd->scopeCarryDataSize;
[4687]185}
186
187
[4670]188/* Entering and leaving blocks. */
[4644]189
[4670]190void CarryManager::enterScope(PabloBlock * blk) {
191   
192    mCurrentScope = blk;
[4687]193    mCarryInfo = mCarryInfoVector[blk->getScopeIndex()];
[4691]194    mCurrentFrameIndex += mCarryInfo->getFrameIndex();
[4704]195    //std::cerr << "enterScope:  blk->getScopeIndex() = " << blk->getScopeIndex() << ", mCurrentFrameIndex = " << mCurrentFrameIndex << std::endl;
[4670]196}
197
198void CarryManager::leaveScope() {
[4691]199    mCurrentFrameIndex -= mCarryInfo->getFrameIndex();
[4703]200    if (mCurrentScope != mPabloRoot) {
201        mCurrentScope = mCurrentScope->getParent();
202        mCarryInfo = mCarryInfoVector[mCurrentScope->getScopeIndex()];
203    }
[4691]204    //std::cerr << "leaveScope:  mCurrentFrameIndex = " << mCurrentFrameIndex << std::endl;
[4670]205}
206
[4694]207
208/* Helper routines */
209
[4704]210unsigned CarryManager::absPosition(unsigned frameOffset, unsigned relPos) {
211    return mCurrentFrameIndex + frameOffset + relPos;
[4697]212}
[4694]213
[4697]214
215unsigned CarryManager::carryOpPosition(unsigned localIndex) {
[4704]216    //std::cerr << "carryOpPosition: addWithCarry.frameOffset = " << mCarryInfo->addWithCarry.frameOffset << ", localIndex = " <<localIndex << std::endl;
217    return absPosition(mCarryInfo->addWithCarry.frameOffset, localIndex);
[4697]218}
219
220unsigned CarryManager::advance1Position(unsigned localIndex) {
[4704]221    //std::cerr << "unsigned CarryManager::advance1Position: advance1.frameOffset = " << mCarryInfo->advance1.frameOffset << ", localIndex = " <<localIndex << std::endl;
222    return absPosition(mCarryInfo->advance1.frameOffset, localIndex);
[4697]223}
224
225unsigned CarryManager::shortAdvancePosition(unsigned localIndex) {
[4704]226    return absPosition(mCarryInfo->shortAdvance.frameOffset, localIndex);
[4697]227}
228
[4698]229unsigned CarryManager::longAdvanceBitBlockPosition(unsigned localIndex) {
[4715]230    return (mCurrentFrameIndex + mCarryInfo->longAdvance.frameOffset) / mITEMS_PER_PACK + localIndex;
[4697]231}
[4700]232   
233unsigned CarryManager::localBasePack() {
[4715]234    return (mCurrentFrameIndex + mCarryInfo->shortAdvance.frameOffset) / mITEMS_PER_PACK;
[4700]235}
236   
237unsigned CarryManager::scopeBasePack() {
[4715]238    return mCurrentFrameIndex / mITEMS_PER_PACK;
[4700]239}
240   
[4697]241
[4700]242
[4697]243unsigned CarryManager::summaryPosition() {
[4704]244    return absPosition(mCarryInfo->summary.frameOffset, 0);
[4697]245}
246
[4710]247
248unsigned CarryManager::summaryPackIndex() {
[4715]249    return summaryPosition()/mITEMS_PER_PACK;
[4710]250}
251
[4697]252unsigned CarryManager::summaryBits() {
[4715]253    if (mCarryInfo->scopeCarryDataSize > mITEMS_PER_PACK) return mPACK_SIZE;
[4704]254    else return mCarryInfo->scopeCarryDataSize;
[4697]255}
256
257
258
[4694]259Value * CarryManager::getCarryPack(unsigned packIndex) {
260    if (mCarryInPack[packIndex] == nullptr) {
[4698]261        Value * packPtr = mBuilder->CreateGEP(mCarryPackBasePtr, mBuilder->getInt64(packIndex));
[4710]262        // Save the computed pointer - so that it can be used in storeCarryPack.
[4694]263        mCarryPackPtr[packIndex] = packPtr;
[4715]264        mCarryInPack[packIndex] = mBuilder->CreateAlignedLoad(packPtr, mPACK_SIZE/8);
[4694]265    }
266    return mCarryInPack[packIndex];
267}
268
[4696]269void CarryManager::storeCarryPack(unsigned packIndex) {
[4715]270    mBuilder->CreateAlignedStore(mCarryOutPack[packIndex], mCarryPackPtr[packIndex], mPACK_SIZE/8);
[4694]271}
272
[4708]273   
[4707]274/* maskSelectBitRange selects the bits of a pack from lo_bit through
[4708]275   lo_bit + bitCount - 1, setting all other bits to zero.  */
276   
[4707]277Value * CarryManager::maskSelectBitRange(Value * pack, unsigned lo_bit, unsigned bitCount) {
[4715]278    if (bitCount == mPACK_SIZE) {
[4707]279        assert(lo_bit == 0);
280        return pack;
[4694]281    }
[4709]282    uint64_t mask = ((((uint64_t) 1) << bitCount) - 1) << lo_bit;
283    return mBuilder->CreateAnd(pack, mBuilder->getInt64(mask));
[4694]284}
[4708]285   
[4707]286Value * CarryManager::getCarryInBits(unsigned carryBitPos, unsigned carryBitCount) {
[4715]287    unsigned packIndex = carryBitPos / mPACK_SIZE;
288    unsigned packOffset = carryBitPos % mPACK_SIZE;
[4707]289    Value * selected = maskSelectBitRange(getCarryPack(packIndex), packOffset, carryBitCount);
290    if (packOffset == 0) return selected;
291    return mBuilder->CreateLShr(selected, packOffset);
[4704]292}
293
[4707]294void CarryManager::extractAndSaveCarryOutBits(Value * bitblock, unsigned carryBit_pos, unsigned carryBitCount) {
[4715]295    unsigned packIndex = carryBit_pos / mPACK_SIZE;
296    unsigned packOffset = carryBit_pos % mPACK_SIZE;
297    unsigned rshift = mPACK_SIZE - packOffset - carryBitCount;
[4709]298    uint64_t mask = ((((uint64_t) 1) << carryBitCount) - 1)  << packOffset;
299    //std::cerr << "extractAndSaveCarryOutBits: packIndex =" << packIndex << ", packOffset = " << packOffset << ", mask = " << mask << std::endl;
[4715]300    Value * field = iBuilder->mvmd_extract(mPACK_SIZE, bitblock, BLOCK_SIZE/mPACK_SIZE - 1);
[4707]301    //Value * field = maskSelectBitRange(field, PACK_SIZE - carryBitCount, carryBitCount);
302    if (rshift != 0) {
303        field = mBuilder->CreateLShr(field, mBuilder->getInt64(rshift));
304    }
305    if (packOffset != 0) {
[4709]306        field = mBuilder->CreateAnd(field, mBuilder->getInt64(mask));
[4707]307    }
308    if (mCarryOutPack[packIndex] == nullptr) {
309        mCarryOutPack[packIndex] = field;
310    }
311    else {
312        mCarryOutPack[packIndex] = mBuilder->CreateOr(mCarryOutPack[packIndex], field);
313    }
[4694]314}
[4704]315
[4707]316Value * CarryManager::pack2bitblock(Value * pack) {
317    return mBuilder->CreateBitCast(mBuilder->CreateZExt(pack, mBuilder->getIntNTy(BLOCK_SIZE)), mBitBlockType);
318}
319   
[4696]320   
321/* Methods for getting and setting individual carry values. */
322   
[4670]323Value * CarryManager::getCarryOpCarryIn(int localIndex) {
[4697]324    unsigned posn = carryOpPosition(localIndex);
[4715]325    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
326        return pack2bitblock(getCarryInBits(posn, 1));
327    }
328    else {
329        return getCarryPack(posn);
330    }
[4644]331}
[4705]332
[4696]333   
[4703]334void CarryManager::setCarryOpCarryOut(unsigned localIndex, Value * carry_out_strm) {
[4697]335    unsigned posn = carryOpPosition(localIndex);
[4715]336    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
337        extractAndSaveCarryOutBits(carry_out_strm, posn, 1);
[4647]338    }
[4715]339    else {
340        Value * carry_bit = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_out_strm, mBuilder->getIntNTy(BLOCK_SIZE)), 127);
341        mCarryOutPack[posn] = mBuilder->CreateBitCast(carry_bit, mBitBlockType);
342        if (mCarryInfo->getWhileDepth() == 0) {
343            storeCarryPack(posn);
344        }
345    }
[4644]346}
347
[4708]348Value* CarryManager::genShiftLeft64(Value* e) {
349    Value* i128_val = mBuilder->CreateBitCast(e, mBuilder->getIntNTy(BLOCK_SIZE));
350    return mBuilder->CreateBitCast(mBuilder->CreateShl(i128_val, 64), mBitBlockType);
351}
352
353Value * CarryManager::addCarryInCarryOut(int localIndex, Value* e1, Value* e2) {
354    Value * carryq_value = getCarryOpCarryIn(localIndex);
355    #if (BLOCK_SIZE == 128)
356    //calculate carry through logical ops
357    Value* carrygen = mBuilder->CreateAnd(e1, e2, "carrygen");
358    Value* carryprop = mBuilder->CreateOr(e1, e2, "carryprop");
359    Value* digitsum = mBuilder->CreateAdd(e1, e2, "digitsum");
360    Value* partial = mBuilder->CreateAdd(digitsum, carryq_value, "partial");
361    Value* digitcarry = mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, mBuilder->CreateNot(partial)));
362    Value* mid_carry_in = genShiftLeft64(mBuilder->CreateLShr(digitcarry, 63));
363    Value* sum = mBuilder->CreateAdd(partial, mBuilder->CreateBitCast(mid_carry_in, mBitBlockType), "sum");
364    Value* carry_out_strm = mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, mBuilder->CreateNot(sum)));
365
366    #else
367    //BLOCK_SIZE == 256, there is no other implementation
368    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
369    #endif         
370    setCarryOpCarryOut(localIndex, carry_out_strm);
371    return sum;
372}
373
374
[4670]375Value * CarryManager::advanceCarryInCarryOut(int localIndex, int shift_amount, Value * strm) {
[4654]376    if (shift_amount == 1) {
[4670]377        return unitAdvanceCarryInCarryOut(localIndex, strm);
[4647]378    }
[4654]379    else if (shift_amount < LongAdvanceBase) {
[4670]380        return shortAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
[4654]381    }
382    else {
[4670]383        return longAdvanceCarryInCarryOut(localIndex, shift_amount, strm);
[4654]384    }
[4644]385}
386
[4670]387Value * CarryManager::unitAdvanceCarryInCarryOut(int localIndex, Value * strm) {
[4697]388    unsigned posn = advance1Position(localIndex);
[4715]389    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
390        extractAndSaveCarryOutBits(strm, posn, 1);
391        Value* carry_longint = mBuilder->CreateZExt(getCarryInBits(posn, 1), mBuilder->getIntNTy(BLOCK_SIZE));
392        Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
393        Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, 1), carry_longint);
394        Value* result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
395        return result_value;
396    }
397    mCarryOutPack[posn] = strm;
[4697]398    Value * carry_in = getCarryPack(posn);
[4670]399    if (mCarryInfo->getWhileDepth() == 0) {
[4697]400        storeCarryPack(posn);
[4647]401    }
[4654]402    Value* result_value;
403   
404#if (BLOCK_SIZE == 128) && !defined(USE_LONG_INTEGER_SHIFT)
[4663]405    Value * ahead64 = iBuilder->mvmd_dslli(64, carry_in, strm, 1);
406    result_value = mBuilder->CreateOr(iBuilder->simd_srli(64, ahead64, 63), iBuilder->simd_slli(64, strm, 1));
[4654]407#else
408    Value* advanceq_longint = mBuilder->CreateBitCast(carry_in, mBuilder->getIntNTy(BLOCK_SIZE));
409    Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
410    Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, 1), mBuilder->CreateLShr(advanceq_longint, BLOCK_SIZE - 1), "advance");
411    result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
412   
413#endif
414    return result_value;
[4644]415}
416
[4670]417Value * CarryManager::shortAdvanceCarryInCarryOut(int localIndex, int shift_amount, Value * strm) {
[4697]418    unsigned posn = shortAdvancePosition(localIndex);
[4715]419    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
420        extractAndSaveCarryOutBits(strm, posn, shift_amount);
421        //std::cerr << "shortAdvanceCarryInCarryOut: posn = " << posn << ", shift_amount = " << shift_amount << std::endl;
422        Value* carry_longint = mBuilder->CreateZExt(getCarryInBits(posn, shift_amount), mBuilder->getIntNTy(BLOCK_SIZE));
423        Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
424        Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, shift_amount), carry_longint);
425        Value* result_value = mBuilder->CreateBitCast(adv_longint, mBitBlockType);
426        return result_value;
427    }
428    mCarryOutPack[posn] = strm;
[4697]429    Value * carry_in = getCarryPack(posn);
[4670]430    if (mCarryInfo->getWhileDepth() == 0) {
[4697]431        storeCarryPack(posn);
[4647]432    }
[4654]433    Value* advanceq_longint = mBuilder->CreateBitCast(carry_in, mBuilder->getIntNTy(BLOCK_SIZE));
434    Value* strm_longint = mBuilder->CreateBitCast(strm, mBuilder->getIntNTy(BLOCK_SIZE));
435    Value* adv_longint = mBuilder->CreateOr(mBuilder->CreateShl(strm_longint, shift_amount), mBuilder->CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
436    return mBuilder->CreateBitCast(adv_longint, mBitBlockType);
[4644]437}
[4654]438   
[4647]439
[4654]440/*  currently defined in carry_data.h
441 
[4647]442 static unsigned power2ceil (unsigned v) {
443 unsigned ceil = 1;
444 while (ceil < v) ceil *= 2;
445 return ceil;
446 }
447 
448 unsigned longAdvanceEntries(unsigned shift_amount) const {
449 return (shift_amount + BLOCK_SIZE - 1)/BLOCK_SIZE;
450 }
451 
452 unsigned longAdvanceBufferSize(unsigned shift_amount)  const {
453 return power2ceil(longAdvanceEntries(shift_amount));
454 }
455 */
[4644]456
[4654]457   
[4670]458Value * CarryManager::longAdvanceCarryInCarryOut(int localIndex, int shift_amount, Value * carry_out) {
[4698]459    unsigned carryDataIndex = longAdvanceBitBlockPosition(localIndex);
[4670]460    Value * advBaseIndex = mBuilder->getInt64(carryDataIndex);
[4647]461    if (shift_amount <= BLOCK_SIZE) {
462        // special case using a single buffer entry and the carry_out value.
[4698]463        Value * advanceDataPtr = mBuilder->CreateGEP(mCarryBitBlockPtr, advBaseIndex);
[4647]464        Value * carry_block0 = mBuilder->CreateAlignedLoad(advanceDataPtr, BLOCK_SIZE/8);
465        mBuilder->CreateAlignedStore(carry_out, advanceDataPtr, BLOCK_SIZE/8);
466        /* Very special case - no combine */
467        if (shift_amount == BLOCK_SIZE) return carry_block0;
468        Value* block0_shr = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_block0, mBuilder->getIntNTy(BLOCK_SIZE)), BLOCK_SIZE - shift_amount);
469        Value* block1_shl = mBuilder->CreateShl(mBuilder->CreateBitCast(carry_out, mBuilder->getIntNTy(BLOCK_SIZE)), shift_amount);
470        return mBuilder->CreateBitCast(mBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
471    }
472    // We need a buffer of at least two elements for storing the advance data.
[4644]473    const unsigned block_shift = shift_amount % BLOCK_SIZE;
[4670]474    const unsigned advanceEntries = mCarryInfo->longAdvanceEntries(shift_amount);
475    const unsigned bufsize = mCarryInfo->longAdvanceBufferSize(shift_amount);
[4644]476    Value * indexMask = mBuilder->getInt64(bufsize - 1);  // A mask to implement circular buffer indexing
477    Value * loadIndex0 = mBuilder->CreateAdd(mBuilder->CreateAnd(mBuilder->CreateSub(mBlockNo, mBuilder->getInt64(advanceEntries)), indexMask), advBaseIndex);
[4647]478    Value * storeIndex = mBuilder->CreateAdd(mBuilder->CreateAnd(mBlockNo, indexMask), advBaseIndex);
[4698]479    Value * carry_block0 = mBuilder->CreateAlignedLoad(mBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex0), BLOCK_SIZE/8);
[4644]480    // If the long advance is an exact multiple of BLOCK_SIZE, we simply return the oldest
[4647]481    // block in the long advance carry data area. 
482    if (block_shift == 0) {
[4698]483        mBuilder->CreateAlignedStore(carry_out, mBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), BLOCK_SIZE/8);
[4647]484        return carry_block0;
[4644]485    }
486    // Otherwise we need to combine data from the two oldest blocks.
487    Value * loadIndex1 = mBuilder->CreateAdd(mBuilder->CreateAnd(mBuilder->CreateSub(mBlockNo, mBuilder->getInt64(advanceEntries-1)), indexMask), advBaseIndex);
[4698]488    Value * carry_block1 = mBuilder->CreateAlignedLoad(mBuilder->CreateGEP(mCarryBitBlockPtr, loadIndex1), BLOCK_SIZE/8);
[4647]489    Value* block0_shr = mBuilder->CreateLShr(mBuilder->CreateBitCast(carry_block0, mBuilder->getIntNTy(BLOCK_SIZE)), BLOCK_SIZE - block_shift);
[4644]490    Value* block1_shl = mBuilder->CreateShl(mBuilder->CreateBitCast(carry_block1, mBuilder->getIntNTy(BLOCK_SIZE)), block_shift);
[4698]491    mBuilder->CreateAlignedStore(carry_out, mBuilder->CreateGEP(mCarryBitBlockPtr, storeIndex), BLOCK_SIZE/8);
[4644]492    return mBuilder->CreateBitCast(mBuilder->CreateOr(block1_shl, block0_shr), mBitBlockType);
493}
[4647]494   
[4644]495
496/* Methods for getting and setting carry summary values */
497   
[4670]498bool CarryManager::blockHasCarries(){
499    return mCarryInfo->blockHasCarries();
[4644]500} 
501
[4670]502
503Value * CarryManager::getCarrySummaryExpr() {
[4710]504    unsigned summary_index = summaryPackIndex();
[4715]505    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
506        Value * pack = getCarryPack(summary_index);
507        Value * summary_bits = maskSelectBitRange(pack, summaryPosition() % mPACK_SIZE, summaryBits());
508        return mBuilder->CreateBitCast(mBuilder->CreateZExt(summary_bits, mBuilder->getIntNTy(BLOCK_SIZE)), mBitBlockType);
509    }
510    else {
511        return getCarryPack(summary_index);
512    }
[4644]513}
514
[4704]515void CarryManager::initializeCarryDataAtIfEntry() {
[4721]516    if (blockHasCarries()) {
517        if (mCarryOutPack[scopeBasePack()] == nullptr) {
518            mCarryInfo->ifEntryPack = mZeroInitializer;
519        }
520        else {
521            mCarryInfo->ifEntryPack = mCarryOutPack[scopeBasePack()];
522        }
[4703]523    }
[4704]524}
[4703]525   
[4704]526void CarryManager::buildCarryDataPhisAfterIfBody(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
527    unsigned const ifScopeCarrySize = mCarryInfo->scopeCarryDataSize;
528    if (ifScopeCarrySize == 0) {
529        // No carry data, therefore no phi nodes.
530        return;
[4703]531    }
[4715]532    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
533        if (ifScopeCarrySize <= mPACK_SIZE) {
534            unsigned const ifPackIndex = scopeBasePack();
535            PHINode * ifPack_phi = mBuilder->CreatePHI(mCarryPackType, 2, "ifPack");
536            ifPack_phi->addIncoming(mCarryInfo->ifEntryPack, ifEntryBlock);
537            ifPack_phi->addIncoming(mCarryOutPack[ifPackIndex], ifBodyFinalBlock);
538            mCarryOutPack[ifPackIndex] = ifPack_phi;
539            return;
540        }
[4704]541    }
[4706]542    if (mCarryInfo->getIfDepth() > 1) {
[4710]543        const unsigned summaryIndex = summaryPackIndex();
[4704]544        PHINode * summary_phi = mBuilder->CreatePHI(mCarryPackType, 2, "summary");
545        summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
[4710]546        summary_phi->addIncoming(mCarryOutPack[summaryIndex], ifBodyFinalBlock);
547        mCarryOutPack[summaryIndex] = summary_phi;
[4704]548    }
549}
[4703]550   
[4676]551void CarryManager::addSummaryPhiIfNeeded(BasicBlock * ifEntryBlock, BasicBlock * ifBodyFinalBlock) {
552    if ((mCarryInfo->getIfDepth() <= 1) || !mCarryInfo->blockHasCarries()){
553        // For ifDepth == 1, the parent does not need a summary as it is not itself within an if.
554        // Therefore, it doesn't need access to this block's summary in building its own.
555        return;
556    }
[4710]557    const unsigned carrySummaryIndex = summaryPackIndex();
[4700]558    PHINode * summary_phi = mBuilder->CreatePHI(mCarryPackType, 2, "summary");
[4644]559    summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
[4696]560    summary_phi->addIncoming(mCarryOutPack[carrySummaryIndex], ifBodyFinalBlock);
561    mCarryOutPack[carrySummaryIndex] = summary_phi;
[4644]562}
[4703]563   
[4676]564void CarryManager::generateCarryOutSummaryCodeIfNeeded() {
[4644]565   
[4676]566    if (!mCarryInfo->explicitSummaryRequired()) {
567        // An explicit summary may not be required, if there is a single carry
568        // operation within the block, or the carries are packed and all carry
569        // bits fit within a single pack.
[4644]570        return;
571    }
572   
[4710]573    const unsigned carrySummaryIndex = summaryPackIndex();
[4676]574   
[4644]575    Value * carry_summary = mZeroInitializer;
[4670]576    if (mCarryInfo->blockHasLongAdvances()) { // Force if entry
[4644]577        carry_summary = mOneInitializer;
578    }
579    else {
[4700]580        auto localCarryIndex = localBasePack();
[4696]581        auto localCarryPacks = mCarryInfo->getLocalCarryPackCount();
[4644]582        if (localCarryPacks > 0) {
[4696]583            carry_summary = mCarryOutPack[localCarryIndex];
[4644]584            for (auto i = 1; i < localCarryPacks; i++) {
[4696]585                carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[localCarryIndex+i]);
[4644]586            }
[4647]587        }
[4670]588        for (Statement * stmt : *mCurrentScope) {
[4644]589            if (If * innerIf = dyn_cast<If>(stmt)) {
[4670]590                PabloBlock * inner_blk = & innerIf->getBody();
591                enterScope(inner_blk);
592                if (blockHasCarries()) {
[4710]593                  carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
[4644]594                }
[4670]595                leaveScope();
[4644]596            }
597            else if (While * innerWhile = dyn_cast<While>(stmt)) {
[4670]598                PabloBlock * inner_blk = & innerWhile->getBody();
599                enterScope(inner_blk);
600                if (blockHasCarries()) {
[4710]601                    carry_summary = mBuilder->CreateOr(carry_summary, mCarryOutPack[summaryPackIndex()]);
[4670]602                }
603                leaveScope();
[4644]604            }
605        }
606    }
607    // Calculation of the carry out summary is complete.   Store it and make it
608    // available in case it must included by parent blocks.
[4696]609    mCarryOutPack[carrySummaryIndex] = carry_summary;
610    storeCarryPack(carrySummaryIndex);
[4644]611}
612
[4670]613void CarryManager::ensureCarriesLoadedRecursive() {
[4696]614    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
[4700]615    const unsigned currentScopeBase = scopeBasePack();
[4670]616    if (mCarryInfo->getWhileDepth() == 1) {
[4700]617        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
[4694]618            getCarryPack(i);
[4644]619        }
620    }
621}
622
623
[4670]624void CarryManager::initializeCarryDataPhisAtWhileEntry(BasicBlock * whileEntryBlock) {
[4696]625    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
626    mCarryOutAccumPhis.resize(scopeCarryPacks);
[4644]627#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
[4700]628    const unsigned currentScopeBase = scopeBasePack();
[4696]629    mCarryInPhis.resize(scopeCarryPacks);
630#endif
631    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
632#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
[4700]633        PHINode * phi_in = mBuilder->CreatePHI(mCarryPackType, 2);
634        phi_in->addIncoming(mCarryInPack[currentScopeBase+index], whileEntryBlock);
[4644]635        mCarryInPhis[index] = phi_in;
636#endif
[4700]637        PHINode * phi_out = mBuilder->CreatePHI(mCarryPackType, 2);
[4644]638        phi_out->addIncoming(mZeroInitializer, whileEntryBlock);
639        mCarryOutAccumPhis[index] = phi_out;
640    }
641}
642
643
[4670]644void CarryManager::extendCarryDataPhisAtWhileBodyFinalBlock(BasicBlock * whileBodyFinalBlock) {
[4696]645    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
[4700]646    const unsigned currentScopeBase = scopeBasePack();
[4696]647    for (unsigned index = 0; index < scopeCarryPacks; ++index) {
[4644]648#ifdef SET_WHILE_CARRY_IN_TO_ZERO_AFTER_FIRST_ITERATION
649        mCarryInPhis[index]->addIncoming(mZeroInitializer, whileBodyFinalBlock);
650#endif
651        PHINode * phi = mCarryOutAccumPhis[index];
[4700]652        Value * carryOut = mBuilder->CreateOr(phi, mCarryOutPack[currentScopeBase+index]);
[4644]653        phi->addIncoming(carryOut, whileBodyFinalBlock);
[4700]654        mCarryOutPack[currentScopeBase+index] = carryOut;
[4644]655    }
656}
657
[4670]658void CarryManager::ensureCarriesStoredRecursive() {
[4696]659    const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
[4700]660    const unsigned currentScopeBase = scopeBasePack();
[4670]661    if (mCarryInfo->getWhileDepth() == 1) {
[4700]662        for (auto i = currentScopeBase; i < currentScopeBase + scopeCarryPacks; ++i) {
[4696]663            storeCarryPack(i);
[4644]664        }
665    }
666}
667
[4713]668/* Store all the full carry packs generated locally in this scope or the
669   single full pack for this scope*/
[4710]670void CarryManager::ensureCarriesStoredLocal() {
[4715]671    if (mITEMS_PER_PACK > 1) {// #ifdef PACKING
672        const unsigned scopeCarryPacks = mCarryInfo->getScopeCarryPackCount();
673        if ((scopeCarryPacks > 0) && ((mCurrentFrameIndex % mPACK_SIZE) == 0)) {
674            // We have carry data and we are not in the middle of a pack.
675            // Write out all local packs.
676            auto localCarryIndex = localBasePack();
677            auto localCarryPacks = mCarryInfo->getLocalCarryPackCount();
678            for (auto i = localCarryIndex; i < localCarryIndex + localCarryPacks; i++) {
679                storeCarryPack(i);
680            }
681            if ((localCarryPacks == 0) && (scopeCarryPacks == 1) && (mCarryInfo->nested.entries > 1)) {
682                storeCarryPack(localCarryIndex);
683            }
[4710]684        }
685    }
[4644]686}
687
[4720]688Value * CarryManager::popCount(Value * to_count, unsigned globalIdx) {
689    Value * countPtr = mBuilder->CreateGEP(mPopcountBasePtr, mBuilder->getInt64(globalIdx));
690    Value * countSoFar = mBuilder->CreateAlignedLoad(countPtr, 8);
691    Value * fieldCounts = iBuilder->simd_popcount(64, to_count);
692    for (int i = 0; i < BLOCK_SIZE/64; i++) {
693        countSoFar = mBuilder->CreateAdd(countSoFar, iBuilder->mvmd_extract(64, fieldCounts, i));
694    }
695    mBuilder->CreateAlignedStore(countSoFar, countPtr, 8);
696    return mBuilder->CreateBitCast(mBuilder->CreateZExt(countSoFar, mBuilder->getIntNTy(BLOCK_SIZE)), mBitBlockType);
697}
[4726]698
[4712]699CarryManager::~CarryManager() {
700    for (auto * cd : mCarryInfoVector) {
701        delete cd;
702    }
[4710]703}
704
[4712]705}
706
Note: See TracBrowser for help on using the repository browser.