Ejemplo n.º 1
0
def get_use_map(ctx, statements):
    maps = [[s[1][2][0][1], s[1][2][1][1]] for s in statements.values()]
    maps = sum(maps, [])
    union_map = isl.UnionMap("{}", ctx)
    for m in maps:
        union_map = union_map.union(isl.UnionMap.from_map(m))
    return union_map
Ejemplo n.º 2
0
def test_sched_constraints_set_validity():
    domain = isl.UnionSet("[n] -> { A[i] : 0 <= i < n; B[i] : 0 <= i < n }")
    validity = isl.UnionMap("[n] -> { A[i] -> B[i] : 0 <= i < n }")
    sc = isl.ScheduleConstraints.on_domain(domain)

    sc = sc.set_validity(validity)
    validity2 = sc.get_validity()

    print(validity)
    print(validity2)

    assert str(validity) == str(validity2)
Ejemplo n.º 3
0
def checkTimeDepsPreserved(Snew, Dep):
    ### src2sinktime = Snew o R
    src2sinktime = isl.UnionMap.apply_range(Dep, Snew)
    ### timesrcsink = Snew o R o Snew^{-1}
    timesrcsink = isl.UnionMap.apply_range(isl.UnionMap.reverse(Snew),
                                           src2sinktime)

    Tnew = Snew.range()
    #print(Tnew)
    Sdesc = Tnew.lex_ge_union_set(Tnew)
    src_gt_sink = timesrcsink.intersect(Sdesc)
    null_map = isl.UnionMap("[N]->{  }")
    is_empty = src_gt_sink.__eq__(null_map)
    return (timesrcsink, is_empty)
Ejemplo n.º 4
0
    def PreprocessPet(self):

        for i in range(0, len(self.Deps)):
            from_ = 'S' + str(self.Deps[i].from_)
            to = 'S' + str(self.Deps[i].to)
            rel = str(self.Deps[i].Relation)
            rel = rel.replace('{ [', '{ ' + from_ + '[')  #like aka Pet
            rel = rel.replace('> [', '> ' + to + '[')
            self.Deps[i].Relation = isl.Map(rel)
            print self.Deps[i].Relation

        self.isl_rel = isl.UnionMap(str(self.Deps[0].Relation))
        for i in range(1, len(self.Deps)):
            self.isl_rel = self.isl_rel.union(self.Deps[i].Relation)
            self.isl_rel = self.isl_rel.coalesce()
Ejemplo n.º 5
0
def Scatter(R, cl, StatementinRange):

    R = str(R)
    strR = R.split(';')
    for st in cl.statements:
        s = 'S' + str(st.petit_line)
        for i in range(0, len(strR)):
            if s in strR[i]:

                res = re.findall(r'S' + str(st.petit_line) + '\[[^\]]+',
                                 strR[i])

                a = st.scatering

                w = res[0]
                w = w.replace(s, '')
                w = w.replace('[', '')
                w = w.replace(']', '')

                b = w.split(',')

                if (len(a) < cl.maxdim + 1):
                    for k in range(len(a), cl.maxdim + 1):  # wyrownaj zerami
                        a.append(u'0')

                if (len(b) < cl.maxdim):
                    for k in range(len(b), cl.maxdim):  # wyrownaj zerami
                        b.append(u'0')

                c = a + b  # scatter

                c[::2] = a
                c[1::2] = b

                strR[i] = strR[i].replace(res[0], s + '[' + ','.join(c))

                if (StatementinRange == False):
                    res = re.findall(r'-> \[[^\]]+', strR[i])

                    a = st.scatering

                    w = res[0]
                    w = w.replace('-> ', '')
                    w = w.replace('[', '')
                    w = w.replace(']', '')

                    b = w.split(',')

                    if (len(a) < cl.maxdim + 1):
                        for k in range(len(a),
                                       cl.maxdim + 1):  # wyrownaj zerami
                            a.append(u'0')

                    if (len(b) < cl.maxdim):
                        for k in range(len(b), cl.maxdim):  # wyrownaj zerami
                            b.append(u'0')

                    c = a + b  # scatter
                    c[::2] = a
                    c[1::2] = b

                    strR[i] = strR[i].replace(res[0], '-> [' + ','.join(c))

    newR = ';'.join(strR)

    return isl.UnionMap(newR)
Ejemplo n.º 6
0
def tile(plik,
         block,
         permute,
         output_file="",
         L="0",
         SIMPLIFY="False",
         perfect_mode=False,
         parallel_option=False,
         rplus_mode='',
         cpus=2):

    print ''
    print colored('/\__  _\ /\  == \   /\  __ \   /\  ___\   /\  __ \   ',
                  'green')
    print colored('\/_/\ \/ \ \  __<   \ \  __ \  \ \ \____  \ \ \/\ \  ',
                  'green')
    print colored('   \ \_\  \ \_\ \_\  \ \_\ \_\  \ \_____\  \ \_____\ ',
                  'green')
    print colored('    \/_/   \/_/ /_/   \/_/\/_/   \/_____/   \/_____/ ',
                  'green')
    print ''
    print '      An Automatic Parallelizer and Optimizer'
    print 'based on the ' + colored('TRA', 'green') + 'nsitive ' + colored(
        'C', 'green') + 'l' + colored('O',
                                      'green') + 'sure of dependence graphs'
    print '             traco.sourceforge.net               '
    print ''
    print 'TIME SPACE TILING Module'

    LPetit = "tmp/tmp_petit" + L + ".t"

    BLOCK = block.split(',')
    BLOCK2 = BLOCK

    for i in range(len(BLOCK), 10):
        BLOCK.append(BLOCK[len(BLOCK) - 1])

    linestring = open(plik, 'r').read()
    lines = linestring.split('\n')

    petit_loop = convert_loop.convert_loop(lines)

    file = open(LPetit, 'w')

    imperf = 0
    endloop = 0
    startloop = 0
    for line in petit_loop:
        #sprawdz przy okazji jaka petla idealnie czy nie
        if 'for' in line and not 'endfor' in line:
            if startloop == 2:
                imperf = 1
            startloop = 1
        else:
            if startloop == 1:
                startloop = 2
        if 'endfor' in line:
            endloop = 1
        if endloop == 1 and 'endfor' not in line and not line.isspace(
        ) and line != '':
            imperf = 1

        file.write(line + '\n')

    file.close()

    start = time.time()
    loop = Dependence.Kernel_Loop(LPetit, 1)

    loop.Load_Deps()

    loop.Load_instrukcje()
    loop.PreprocessPet()
    loop.Get_Arrays()
    end = time.time()
    elapsed = end - start

    print "Dependence analysis: time taken: ", elapsed, "seconds."

    print colored('R', 'green')
    print loop.isl_rel

    isl_symb = loop.Deps[0].Relation.get_var_names(isl.dim_type.param)

    symb_prefix = ''
    if len(isl_symb) > 0:
        symb_prefix = '[' + ','.join(isl_symb) + '] -> '

    cl = clanpy.ClanPy()
    cl.loop_path = plik
    cl.Load()

    arr = map(int, loop.dane)
    arr = sorted(list(set(arr)))
    for i in range(0, len(cl.statements)):
        cl.statements[i].petit_line = arr[i]
        cl.statements[i].bounds = tiling_v5.GetBounds(
            petit_loop, cl.statements[i].petit_line, BLOCK2, 0)
        print cl.statements[i].scatering

    for i in range(0, len(cl.statements)):
        cl.statements[i].domainpet = isl.Set(
            symb_prefix + ' { S' + str(cl.statements[i].petit_line) + '[' +
            ','.join(cl.statements[i].original_iterators) + '] : ' +
            cl.statements[i].domain + '}')
        #print cl.statements[i].domainpet

    IS = isl.UnionSet(str(cl.statements[0].domainpet))
    for i in range(1, len(cl.statements)):
        IS = IS.union(cl.statements[i].domainpet)
        IS = IS.coalesce()

    print colored('IS', 'green')
    print IS

    #isl schedule
    text = 'R:= ' + str(loop.isl_rel) + '; IS := ' + str(
        IS) + '; schedule IS respecting R minimizing R;'

    print colored('ISL output', 'green')

    sched_dump = iscc.iscc_communicate(text)

    print sched_dump

    lines = sched_dump.split('\n')
    sched_maps = sched_parser.parse(lines, cl, symb_prefix)

    print colored('ISL schedules', 'green')

    for m in sched_maps:
        print m

    SCHED = isl.UnionMap(str(sched_maps[0]))
    for i in range(1, len(sched_maps)):
        SCHED = SCHED.union(sched_maps[i])
        SCHED = SCHED.coalesce()

    #SCHED = isl.UnionMap('[N] -> { S27[i, j] -> [-i + j, 2,j] : N > 0 and 0 <= i <= -2 + N and i < j < N; S20[i, j, k] -> [-i + j, 0,0,1,k] : N > 0 and 0 <= i <= -2 + N and 2 + i <= j < N and i < k < j; S23[i, j, k] -> [-i + j, 0,k,2, j] : N > 0 and 0 <= i <= -2 + N and 2 + i <= j < N and i < k <= -2 + j; S26[i, j] -> [-i + j, 1,j] : N > 0 and 0 <= i <= -2 + N and i < j < N; S16[i, j, k, m] -> [-i + j, 0,k, 0,m] : N > 0 and 0 <= i <= -2 + N and 2 + i <= j < N and i < k <= -2 + j and k < m <= -3 - i + j + k and m < j }')

    #SCHED = isl.UnionMap('[n, loop] -> { S12[l, i, k] -> [l,i,k] : n >= 2 and loop > 0 and 0 < l <= loop and 0 < i < n and 0 <= k < i }')

    print colored('SCHED', 'green')
    print SCHED

    #print colored('deltas R', 'green')

    # SPACE

    # wykryj liczbe na razie globalnie

    islR = Scatter(loop.isl_rel, cl, True)
    D = loop.isl_rel.deltas()
    spaces_num = sys.maxint

    for i in range(0, len(cl.statements)):
        depth = len(cl.statements[i].original_iterators)
        nums = 0
        for j in range(0, depth):
            direct = ' < '
            print cl.statements[i].bounds[j]['step']  # decrementation
            if cl.statements[i].bounds[j]['step'] == '-1':
                direct = ' > '

            TEST = '{ S' + str(cl.statements[i].petit_line) + '[' + ','.join(
                cl.statements[i].original_iterators) + '] : ' + cl.statements[
                    i].original_iterators[j] + direct + ' 0 }'
            print TEST
            TEST = isl.Set(TEST)

            TEST = D.intersect(TEST)
            if (TEST.is_empty()):
                nums = nums + 1
            else:
                break  # sa ujemne
        # print nums
        if (nums < spaces_num):
            spaces_num = nums

    print colored('SPACES NUMBER', 'green')
    print spaces_num

    if spaces_num == 0 or 1 == 1:
        print 'No spaces or manually input calculated number'
        spaces_num = int(raw_input())

    # vars

    vars = []
    sym_exvars = []

    for st in cl.statements:
        if (len(st.original_iterators) == loop.maxl):
            vars = st.original_iterators
            break

    for v in vars:
        sym_exvars.append(v * 2)

    ##################################

    SPACES = {}
    space = ''

    for st in cl.statements:
        tmpspaces = []
        for i in range(0, spaces_num):
            space = st.domainpet
            space = space.insert_dims(isl.dim_type.param, 0, 1)
            space = space.set_dim_name(isl.dim_type.param, 0, sym_exvars[i])
            space = str(space)
            space = space.replace(
                '}', MakesSpaceConstr(st, vars, sym_exvars, isl_symb, BLOCK,
                                      i))
            print space
            space = isl.Set(space)

            tmpspaces.append(space)
            #print space

        SPACES["S" + str(st.petit_line)] = tmpspaces

    ##################################
    #experimental Rk

    if False:

        print "=============================================="

        spaceunion = None

        for s in SPACES:
            print s
            tmpspace = None
            for ss in SPACES[s]:
                if tmpspace is None:
                    tmpspace = isl.UnionSet(str(ss))
                else:
                    tmpspace = tmpspace.union(ss).coalesce()

            if spaceunion is None:
                spaceunion = tmpspace
            else:
                spaceunion = spaceunion.union(tmpspace).coalesce()

        if (1 == 0):
            print "Experimental Rk"
            print "SPACE"
            print spaceunion

            print "new R"
            R = loop.isl_rel.from_domain_and_range(spaceunion,
                                                   spaceunion).coalesce()
            print R

            #Rk = R.power()
            #print "Rk"
            print Rk

            print "=============================================="

    ###################################

    sched_maps_i = sched_maps  #SCHED_1 SCHED_2
    TIMES = []

    if (spaces_num < cl.maxdim):

        print colored("SCHED_1:=SCHED^-1", 'green')

        for i in range(0, len(sched_maps_i)):
            sched_maps_i[i] = sched_maps_i[i].fixed_power_val(-1).coalesce()

            print sched_maps_i[i]

            #if i == 3:
            #    sched_maps_i[i] = isl.Map('[N] -> {[i0, 0] -> S20[i, j = i0 + i]: N > 0 and 0 <= i <= -2 + N and i0=1}')

            TIMES.append(sched_maps_i[i])

            tmp = ''

            if ("i0" in str(TIMES[i])):

                TIMES[i] = TIMES[i].insert_dims(isl.dim_type.param, 0, 1)
                TIMES[i] = TIMES[i].set_dim_name(isl.dim_type.param, 0, 'c')
                TIMES[i] = TIMES[i].insert_dims(isl.dim_type.param, 0, 1)
                TIMES[i] = TIMES[i].set_dim_name(isl.dim_type.param, 0, 'i0')
                tmp = str(TIMES[i])

                if 'i1' in tmp:
                    v = 'i1'
                else:
                    v = 'i0'

                tmp = tmp.replace('}', " && " + str(BLOCK[spaces_num]) +
                                  "c<=" + v + "<=" + str(BLOCK[spaces_num]) +
                                  "*(c+1)-1 && i0=i0' }")  # podmien na bloki

            else:
                tmp = str(TIMES[i])

            TIMES[i] = isl.Map(tmp).range()

        print colored("TIMEi", 'green')

        for s in TIMES:
            print s

        print colored("TIME", 'green')
    else:
        print colored("TIME: all distance vectors elements are positive",
                      'green')
        for i in range(0, len(sched_maps_i)):
            TIMES.append(sched_maps_i[i].subtract(
                sched_maps_i[i]).complement().domain().coalesce())

    ######################################### TIMES experimental code

    TIME = isl.UnionSet(str(TIMES[i]))
    for i in range(1, len(TIMES)):
        TIME = TIME.union(TIMES[i])
        TIME = TIME.coalesce()

    print TIME

    #########################################

    TILES = []

    for i in range(0, len(TIMES)):
        TILES.append(TIMES[i])
        for j in range(0, spaces_num):
            TILES[i] = TILES[i].intersect(
                SPACES['S' + str(cl.statements[i].petit_line)][j]).coalesce()

    TILE = isl.UnionSet(str(TILES[0]))
    for i in range(1, len(TILES)):
        TILE = TILE.union(TILES[i])
        TILE = TILE.coalesce()

    print colored("TILE", 'green')
    print TILE
    print "Making MAP %%%"

    ###########################################

    # MAKE MAP

    TILE = str(TILE).split('->')[1]

    # j=i-i0 crazy thing

    ####################################################   wstawia oryginalne iteratory, dodaje rownania i scattering
    strTILE = TILE.split(';')
    for st in cl.statements:
        s = 'S' + str(st.petit_line)
        for i in range(0, len(strTILE)):
            if s in strTILE[i]:
                res = re.findall(r'S\d+\[[^\]]+', strTILE[i])

                a = st.scatering
                b = st.original_iterators[:]

                for k in range(0, st.getDim()):
                    if st.bounds[k]['step'] == '-1':
                        b[k] = '-' + b[k]

                if (len(a) < cl.maxdim + 1):
                    for k in range(len(a), cl.maxdim + 1):  #wyrownaj zerami
                        a.append(u'0')

                if (len(b) < cl.maxdim):
                    for k in range(len(b), cl.maxdim):  #wyrownaj zerami
                        b.append(u'0')

                c = a + b  #scatter
                c[::2] = a
                c[1::2] = b

                strTILE[i] = strTILE[i].replace(res[0], s + '[' + ','.join(c))
                res = res[0].split('[')[1].replace(' ', '').split(',')
                for r in res:
                    if '=' in r:
                        strTILE[i] = strTILE[i].replace(
                            ':', ': ' + r + ' and ')
                break
            else:
                continue

    TILE = ';'.join(strTILE)
    print TILE

    #####################################################

    arr = []
    arr.append('t')
    timet = []
    if spaces_num == 0:
        timet.append('0')
    for i in range(0, spaces_num):
        arr.append(sym_exvars[i])
        timet.append(sym_exvars[i])
    arr.append('i0')
    arr.append('c,')
    arr = ','.join(arr)

    TILE = TILE.replace('[', '[' + arr)

    timet = ' t = ' + '+'.join(timet)

    if (spaces_num >= cl.maxdim):  # dodatnie wektory
        timet += ' and  c = 0 and i0 = 0 '

    TILE = symb_prefix + TILE.replace(':', ':' + timet + ' and ')

    for st in cl.statements:
        s = 'S' + str(st.petit_line)
        TILE = TILE.replace(
            s, s + '[' + ','.join(st.original_iterators) + '] -> ')

    print colored("MAP", 'green')
    print TILE

    print 'MAP in ISL'
    print isl.UnionMap(TILE).coalesce()

    #loop_x = iscc.iscc_communicate("L :=" + str(TILE) + "; codegen L;")
    #print loop_x

    print colored("ISL AST", 'green')

    loop_x = iscc.isl_ast_codegen_map(isl.UnionMap(TILE))
    print loop_x

    # **************************************************************************
    lines = loop_x.split('\n')

    # *********** post processing ****************

    print colored("POSTPROCESSING", 'green')

    loop_str = []

    for line in lines:
        if line.endswith(');'):
            tab = imperf_tile.get_tab(line)
            line = line.replace(' ', '')
            line = line[:-2]
            line = line[1:]

            line = line.split('(')

            petit_st = line[0].replace('S', '')
            line = line[1]

            arr = line.split(',')

            s = ''

            for i in range(0, len(cl.statements)):

                # TODO if petit_st has 'c' get all statements make if from petit_line and insert to s, solution for loop over st
                if 'c' in petit_st:
                    combo_st = '{'
                    for j in range(0, len(cl.statements)):
                        combo_st += '\n' + tab
                        combo_st += 'if( ' + petit_st + ' == ' + str(cl.statements[j].petit_line) + ' ) ' + \
                                    cl.statements[j].body
                    s = combo_st + '\n' + tab + '}'
                elif cl.statements[i].petit_line == int(
                        petit_st):  # st.petit_line
                    s = cl.statements[i].body

            for i in range(
                    0, len(vars)
            ):  # todo oryginal iterators for loops with mixed indexes

                if (i + 1 > len(arr)):
                    continue

                subt = arr[i]
                if (('+' in subt) or ('-' in subt)):
                    subt = '(' + subt + ')'
                s = re.sub(r'\b' + vars[i] + r'\b', subt, s)

            loop_str.append(tab + s)

        else:
            line = line.replace('for (int', 'for(')
            loop_str.append(line)

    # *********** post processing end ****************

    if (1 == 1):
        for line in loop_str:
            if 'for( c1 ' in line and spaces_num < cl.maxdim:
                print imperf_tile.get_tab(line) + colored(
                    '#pragma omp parallel for', 'green')
            print line

    # VALIDITY

    # Lex_Neg2:=[N]->{ [i0, i1]: (i0=0 and i1=0 ) or i0<0  or i0=0 and i1<0 };

    # VALIDITY

    SCHED2 = Scatter(SCHED, cl, False)

    L = 2 * cl.maxdim + 1

    lexvar = ["i%d" % i for i in range(0, L)]

    lexneg = '{[' + ','.join(lexvar) + '] : ('

    for i in range(0, L):
        lexneg += lexvar[i] + '=0' + ' and '

    lexneg += '1=1) or '

    for i in range(0, L):
        lexneg += lexvar[i] + ' < 0 and '
        for j in range(0, i):
            lexneg += lexvar[j] + ' = 0 and '
        lexneg += ' 1 = 1 or '
    lexneg += ' 1 = 0 }'

    lexneg = isl.Set(lexneg)

    C = (SCHED2.fixed_power_val(-1).apply_range(islR)).apply_range(SCHED2)

    P = C.deltas().intersect(lexneg).coalesce()

    if P.is_empty():
        print colored('VALIDATION OK', 'green')
    else:
        print colored('VALIDATION FAILED !!', 'red')

    print colored('lexneg', 'yellow')
    print lexneg
    print colored('C = (SCHED^-1(R))(SCHED)', 'yellow')
    print C
    print colored('P = C.deltas()', 'yellow')
    print C.deltas()
    print colored('P*C', 'yellow')
    print P

    for d in loop.Deps:
        del d.Relation
Ejemplo n.º 7
0
#
#                     |
#                     v
#
#           for(j=0; j<=N; j++)
#             for(i=1; i<=N; i++)
# S1[i,j]:      Z[i,j] = f(Z[i-1,j]);
#
import islpy as isl
import common

### fill in the original iteration space (domain)---set of stmt instances
I = isl.UnionSet("[N] -> { ... }")

### fill in the original schedule---relation mapping stmts to time
Sini = isl.UnionMap("[N] -> { ... }").intersect_domain(I)
print("Initial Schedule:")
print(Sini)

### fill in the write/read access relations---mapping stmts to read/written array elements
Write = isl.UnionMap("[N] -> { ... }").intersect_domain(I)
Read = isl.UnionMap("[N] -> { ... }").intersect_domain(I)

Dep = common.mkDepGraph(Sini, Read, Write)
print("Dependency graph is:")
print(Dep)

### Most Importantly: fill in the new schedule representing the loop
###                   interchange transformation as a relation mapping
###                   original stmts to their new (rescheduled) time.
### Then verify that loop of index `j` is parallel (by writing a new
Ejemplo n.º 8
0
def test_union_map():
    d = isl.UnionSet("[start, num] -> {S[i,j] : start <= i,j < start + num}")
    s = isl.UnionMap("{S[i,j] -> [i,j]}").intersect_domain(d)
    aw = isl.UnionMap("{S[i,j] -> B[1024 i + j]}")
    aw.compute_flow(aw, aw, s)
Ejemplo n.º 9
0
def islApiExamples():
    ctx = isl.Context()

    ## Spaces
    names = ['s\'', 'x1', 'x2']
    space1 = isl.Space.create_from_names(ctx, set = names)
    names = ['s', 'y1', 'y2']
    space2 = isl.Space.create_from_names(ctx, set = names)
    #Spaces are equal when their dimensions are equal
    print space1.is_equal(space2)
    #isl dim type can be set/in/out/param/all   
    print space1.find_dim_by_name(isl._isl.dim_type.all,'x2')
    #print space1.get_id_dict(isl._isl.dim_type.set)
    newid  = isl.Id(context = ctx, name = 'x0')
    space1 = space1.set_dim_id(isl._isl.dim_type.set, 1, newid)
    print space1.get_dim_id(isl._isl.dim_type.set, 1)
    #Looks like get_id_dict does not work as expected
    #print space1.get_id_dict(isl._isl.dim_type.set)
    print space1.get_var_dict()

    ## Sets
    space = isl.Space.create_from_names(ctx, set=["i", "j"])

    bset1 = (isl.BasicSet.universe(space)
            .add_constraint(isl.Constraint.ineq_from_names(space, {1: -1, "i": 1}))
            .add_constraint(isl.Constraint.ineq_from_names(space, {1: 5, "i": -1}))
            .add_constraint(isl.Constraint.ineq_from_names(space, {1: -1, "j": 1}))
            .add_constraint(isl.Constraint.ineq_from_names(space, {1: 5, "j": -1})))
    print bset1

    bset2 = isl.BasicSet("[N]->{[x, y] : x >= 0 and x < 5 and y >= 0 and y < N+4 and N >= 0 and N < 10}")    
    print bset2
    print bset2.polyhedral_hull()
    print bset2.lexmax()
    print bset2.lexmin()
    print bset2.lexmin().is_singleton()   

    ## Points
    points = []
    bset1.foreach_point(points.append)
    print points
    point = points[0].get_coordinate_val(isl._isl.dim_type.all, 0)
    pointx = point.get_num_si()/point.get_num_si()
    # The same thing can be achieved with to_python() provided by islpy
    print point.to_python()
    point = points[0].get_coordinate_val(isl._isl.dim_type.all, 1)
    pointy = point.get_num_si()/point.get_num_si()
    print (pointx, pointy)

    ## Dependence computation

    mapspace = isl.Space.create_from_names(ctx, in_=["i", "j"], out = ["i1", "j1"], params = ["N"])
    ## Schedule and AST
    
    # Creating an identity schedule
    bmap = (isl.BasicMap.identity(mapspace)
           .add_constraint(isl.Constraint.ineq_from_names(mapspace, {1: -1, "i": 1}))
           .add_constraint(isl.Constraint.ineq_from_names(mapspace, {"N": 1, "i": -1}))
           .add_constraint(isl.Constraint.ineq_from_names(mapspace, {1: -1, "j": 1}))
           .add_constraint(isl.Constraint.ineq_from_names(mapspace, {"N": 1, "j": -1})))
    #bmap = bmap.insert_dims(isl._isl.dim_type.out, 0, 1)
    #name = bmap.get_dim_name(isl._isl.dim_type.out, 1)
    #bmap = bmap.set_dim_name(isl._isl.dim_type.out, dim, 'S_' + name)

    print bmap
    astbld = isl.AstBuild.from_context(isl.BasicSet("[N] -> { : }"))
    astbld = astbld.set_options(isl.UnionMap("{}"))
    # Printing is strange
    printer = isl.Printer.to_str(ctx)
    printer = printer.set_output_format(isl.format.C)
    printer = (isl.AstBuild.ast_from_schedule(astbld, isl.UnionMap.from_map(bmap))).print_(printer, isl.AstPrintOptions.alloc(ctx))
    print printer.get_str()
    
    extSet = isl.BasicSet("[n] -> { [i] : exists (a = [i/10] : 0 <= i and i <= n and i - 10 a <= 6) }")
    print extSet
    print extSet.get_local_space()
    print extSet.get_local_space().get_div(0)
    extMap = isl.BasicMap.from_domain_and_range(extSet, extSet)
    
    astbld = isl.AstBuild.from_context(isl.BasicSet("[n] -> { : }"))
    astbld = astbld.set_options(isl.UnionMap("{}"))
    # Printing is strange
    printer = isl.Printer.to_str(ctx)
    printer = printer.set_output_format(isl.format.C)
    printer = (isl.AstBuild.ast_from_schedule(astbld, isl.UnionMap.from_map(extMap))).print_(printer, isl.AstPrintOptions.alloc(ctx))
    print printer.get_str()

    gen = isl.BasicMap("[C, R] -> { Ixx[x, y] -> [Dir_i0', T_i0', Dir_i1', T_i1', t, i0', i1'] : t = 0 and i0' = x and i1' = y and x >= 1 and x <= R and y >= 1 and y <= C and R >= 1 and C >= 1 and 64T_i0' <= x and 64T_i0' >= -63 + x and 64T_i0' <= -32 + x - 64Dir_i0' and 64T_i0' >= -95 + x - 64Dir_i0' and Dir_i0' >= -1 and Dir_i0' <= 0 and 64T_i1' <= y and 64T_i1' >= -63 + y and 64T_i1' <= -32 + y - 64Dir_i1' and 64T_i1' >= -95 + y - 64Dir_i1' and Dir_i1' >= -1 and Dir_i1' <= 0 }")
    #gen = isl.UnionMap("[R, C] -> { harris[x, y] -> [1, x, y] : C = 10 and R = 10 and x >= 2 and x <= 9 and y >= 2 and y <= 9; Iyy[x, y] -> [0, x, y] : C = 10 and R = 10 and x >= 1 and x <= 10 and y >= 1 and y <= 10}")
    genbld = isl.AstBuild.from_context(isl.BasicSet("[C, R]->{: R > 1 and C > 1}"))
    #genbld = astbld.set_options(isl.UnionMap("{[i,j] -> unroll[0] : i < 4 or i > 99996}"))
    id_ = isl.Id.alloc(ctx, "Test1", "FakeObj")
    gen = gen.set_tuple_id(isl._isl.dim_type.in_, id_)
    
    #id_ = isl.Id.alloc(ctx, "Test2", "FakeObj")
    #print gen.get_tuple_name(isl._isl.dim_type.out)

    genbld = genbld.set_options(isl.UnionMap("[C, R] -> { [Dir_i0', T_i0', Dir_i1', T_i1', t, i0', i1'] -> unroll[x] : x = 0 or x = 2}"))
    idl =  isl.IdList.alloc(ctx, 3)
    print idl
    idl = idl.add(isl.Id.alloc(ctx, 'Dir_i0', None))
    idl = idl.add(isl.Id.alloc(ctx, 'T_i0', None))
    idl = idl.add(isl.Id.alloc(ctx, 'Dir_i1', None))
    idl = idl.add(isl.Id.alloc(ctx, 'T_i1', None))
    idl = idl.add(isl.Id.alloc(ctx, 't', None))
    idl = idl.add(isl.Id.alloc(ctx, 'i0', None))
    idl = idl.add(isl.Id.alloc(ctx, 'i1', None))
    genbld = genbld.set_iterators(idl)
    printer = isl.Printer.to_str(ctx)
    printer = printer.set_output_format(isl.format.C)
    #astRoot = isl.AstBuild.ast_from_schedule(genbld, isl.UnionMap.from_map(gen))
    print genbld.get_schedule_space()
    astRoot = genbld.ast_from_schedule(isl.UnionMap.from_map(gen))
    print genbld.get_schedule_space()
    printer = astRoot.print_(printer, isl.AstPrintOptions.alloc(ctx))
    print printer.get_str()

    applyBase = isl.BasicMap("[rows, cols] -> { Dx_2_img2[c, x, y] -> [3, c, x, y] : c >= 0 and c <= 2 and x >= 2 and 4x <= 4 + rows and y >= 2 and 2y <= 2 + cols and rows >= 1 and cols >= 1 }")
    align = isl.BasicMap("[rows, cols]->{[a, b, c, d] -> [a, d, b, c]}")
    print applyBase.apply_range(align)

    mem = isl.BasicMap("[cols, rows] -> { Uy_2_img2[c, x, y] -> [c, T_i1', T_i2', 7, 4x, 4y] : c >= 0 and c <= 2 and x >= 2 and 4x <= 4 + rows and y >= 2 and 4y <= 4 + cols and rows >= 1 and cols >= 1 and 64T_i1' <= -2 + x and 64T_i1' >= -70 + x and 64T_i2' <= -2 + y and 64T_i2' >= -73 + y }")
    acc = isl.BasicMap("[cols, rows] -> { Uy_2_img2[c, x, y] -> [c, T_i1', T_i2', 7, x-64T_i1', y-64T_i2'] : c >= 0 and c <= 2 and x >= 2 and 4x <= 4 + rows and y >= 2 and 4y <= 4 + cols and rows >= 1 and cols >= 1 and 64T_i1' <= -2 + x and 64T_i1' >= -70 + x and 64T_i2' <= -2 + y and 64T_i2' >= -73 + y and rows >= 256 and cols >= 256}")
    print acc.range().dim_min(4), acc.range().dim_max(4)

    split = isl.BasicMap("[cols, rows] -> { Uy_0_img1[c, x, y, _Mul_x, _Mul_y] -> [_T_i1, _T_i2, 1, 5, c, x, y] : exists (e0 = floor((-1 + y)/2): rows = 768 and 64_T_i1 = x - _Mul_x and 64_T_i2 = y - _Mul_y and cols = 1024 and 2e0 = -1 + y and c >= 0 and c <= 2 and x >= 2 and x <= 769 and y >= 2 and y <= 1025) }")
    print split
Ejemplo n.º 10
0
# S2:   X[j] = g(Y[j])
#            |
#            V
#    for(p=0; p<=N; p++) {
# S1:   Y[p] = Z[N-p];
# S2:   X[p] = Y[p];
#    }
# A[i] == A[0,i]
# B[i] == A[1,i]
# C[i] == A[2,i]

import islpy as isl
import common

I = isl.UnionSet("[N] -> {S1[i]: 0<=i<=N; S2[j]: 0<=j<=N}")
Sini = isl.UnionMap(
    "[N] -> {S1[i] -> [1,i]; S2[j] -> [2,j]}").intersect_domain(I)
print("Initial Schedule:")
print(Sini)

Write = isl.UnionMap(
    "[N] -> {S1[i] -> Y[N-i]; S2[j] -> X[j]}").intersect_domain(I)
Read = isl.UnionMap(
    "[N] -> {S1[i] -> Z[i];   S2[j] -> Y[j]}").intersect_domain(I)
Dep = common.mkDepGraph(Sini, Read, Write)
print("Dependency graph is:")
print(Dep)

Snew = isl.UnionMap(
    "[N] -> {S1[p] -> [N-p,1]; S2[j] -> [j,2]}").intersect_domain(I)
print("New Schedule:")
print(Snew)
Ejemplo n.º 11
0
#    for(p=1; p<=N; p++)
# S1:   Y[p] = f(Z[p]);
# S2:   X[p] = g(Y[p+1])
#            |
#            V
#    for(i=1; i<=N; i++)
# S1:   Y[i] = f(Z[i]);
#
#    for(j=1; j<=N; j++)
# S2:   X[j] = g(Y[j+1])

import islpy as isl
import common

I = isl.UnionSet("[N] -> {S1[p]: 1<=p<=N; S2[p]: 1<=p<=N}")
Sini0 = isl.UnionMap("[N] -> { S1[p] -> [p,1]; S2[p] -> [p,2] }")
Sini = Sini0.intersect_domain(I)
print("Initial Schedule:")
print(Sini)

Write = isl.UnionMap("[N] -> {S1[p] -> Y[p]; S2[p] -> X[p]}").intersect_domain(
    I)
Read = isl.UnionMap(
    "[N] -> {S1[p] -> Z[p]; S2[p] -> Y[p+1]}").intersect_domain(I)
Dep = common.mkDepGraph(Sini, Read, Write)
print("Dependency graph is:")
print(Dep)

Snew = isl.UnionMap(
    "[N] -> {S1[i] -> [1,i]; S2[j] -> [2,j]}").intersect_domain(I)
print("New Schedule:")
Ejemplo n.º 12
0
cmd += 'print IND;'
#######################################################################
# RESULT TO ISLPY

output = loop_x = iscc.iscc_communicate(cmd)

output = output.split('\n')

schedule = output[1]
ld = output[3]
rel = output[11]
ind = output[13]

ld = isl.UnionSet(ld)
ind = isl.UnionSet(ind)
schedule = isl.UnionMap(schedule)
strrel = rel

rel = isl.UnionMap(rel)
print rel

print schedule

########################################################################
rels = strrel.split(';')
prefix = re.findall(r'[^{]*{', rels[0])[0]

maps = []
for q in rels:
    if prefix not in q:
        q = prefix + q
Ejemplo n.º 13
0
#                   |
# Change of variables: p <- i+j,  q <- j
#                   |
#                   V
#     for(int p=2; p < 2*N-1; p++) {
#       int up_bd = ((p+2)/2) + (p%2);
#       for(int q=max(1,p-N+1); q<min(up_bd,N); q++) {
# S1:     X[p-q][q] = X[p-q-1][q] + X[p-q][q-1];
#       }
#     }

import islpy as isl
import common

I = isl.UnionSet("[N] -> {S1[i,j]: 1<=i<N and 1<=j<min(i+2, N)}")
Sini0 = isl.UnionMap("[N] -> { S1[i,j] -> [i,j] }")
Sini = Sini0.intersect_domain(I)
print("Initial Schedule:")
print(Sini)
print(I)

Write = isl.UnionMap("[N] -> {S1[i,j] -> X[i,j]}").intersect_domain(I)
Read = isl.UnionMap(
    "[N] -> {S1[i,j] -> X[i-1,j]; S1[i,j] -> X[i,j-1]}").intersect_domain(I)
Dep = common.mkDepGraph(Sini, Read, Write)
print("Dependency graph is:")
print(Dep)

#Inew = isl.UnionSet("[N] -> {S1[p,q]: 2<=p<2*N-1 and max(1,p-N+1)<=q<min((p+2)/2 + (p mod 2), N)}")
Snew = isl.UnionMap("[N] -> {S1[x,q] -> [x+q,q]}").intersect_domain(I)
#Snew = isl.UnionMap("[N] -> {S1[x,q] -> [x+q,1]}").intersect_domain(Inew)
Ejemplo n.º 14
0
def compute_communication(S0_dom, Access_A, Access_B, Access_C, str_schedule,
                          A, B, C, r_partitioner_A, rp_partitioner_A,
                          r_partitioner_B, rp_partitioner_B, r_partitioner_C,
                          rp_partitioner_C, context):
    # 0 - Print all inputs
    ##########################################@
    print "S0_dom = ", S0_dom
    print "Access_A = ", Access_A
    print "Access_B = ", Access_B
    print "Access_C = ", Access_C
    print "Schedule = ", str_schedule
    print "A = ", A
    print "B = ", B
    print "C = ", C
    print "\n\n"
    print "r_partitioner_A = ", r_partitioner_A
    print "rp_partitioner_A = ", rp_partitioner_A
    print "r_partitioner_B = ", r_partitioner_B
    print "rp_partitioner_B = ", rp_partitioner_B
    print "r_partitioner_C = ", r_partitioner_C
    print "rp_partitioner_C = ", rp_partitioner_C
    print "\n\n"

    # I - Compute the "Have" sets for r and rp.
    ############################################
    r_have_A = A.apply(r_partitioner_A)
    rp_have_A = A.apply(rp_partitioner_A)
    r_have_B = B.apply(r_partitioner_B)
    rp_have_B = B.apply(rp_partitioner_B)
    r_have_C = C.apply(r_partitioner_C)
    rp_have_C = C.apply(rp_partitioner_C)
    print "r_have_A = ", r_have_A
    print "r_have_B = ", r_have_B
    print "r_have_C = ", r_have_C
    print "rp_have_A = ", rp_have_A
    print "rp_have_B = ", rp_have_B
    print "rp_have_C = ", rp_have_C

    # II - Compute the "Need" parts of A, B, and C
    #	II.1- Reverse access to C
    #	II.2- Apply the have_C to the reverse of C to get the corresponding domain of S0
    #	II.2- Apply the domain of S0 to Access_A and Access_B to derive the needed parts
    # 	      of A and B
    ################################################
    reverse_Access_C = Access_C.reverse()
    S0_corresponding_to_p_owned_C = r_have_C.apply(reverse_Access_C)
    S0_corresponding_to_pp_owned_C = rp_have_C.apply(reverse_Access_C)
    r_need_A = S0_corresponding_to_p_owned_C.apply(Access_A)
    r_need_B = S0_corresponding_to_p_owned_C.apply(Access_B)
    rp_need_A = S0_corresponding_to_pp_owned_C.apply(Access_A)
    rp_need_B = S0_corresponding_to_pp_owned_C.apply(Access_B)
    print "r_need_A = ", r_need_A
    print "r_need_B = ", r_need_B
    print "rp_need_A = ", rp_need_A
    print "rp_need_B = ", rp_need_B
    print "\n"

    # III- Compute the missing part for r. We interpret r as the receiver in this section
    # (i.e., the part that r has to receive)
    #################################################
    # what needs to be received for A = r_missing_A
    r_missing_A = r_need_A - r_have_A
    r_missing_B = r_need_B - r_have_B
    r_receive_A = r_missing_A.intersect(rp_have_A)
    r_receive_B = r_missing_B.intersect(rp_have_B)
    print "r_missing_A = r_need_A - r_have_A = ", r_missing_A
    print "r_missing_B = r_need_B - r_have_B = ", r_missing_B
    print "r_receive_A = r_missing_A.intersect(rp_have_A) = ", r_receive_A
    print "r_receive_B = r_missing_B.intersect(rp_have_B) = ", r_receive_B
    print "\n\n"

    # IV- Compute the missing part for the senders.
    #################################################
    rp_missing_A = rp_need_A - rp_have_A
    rp_missing_B = rp_need_B - rp_have_B
    r_send_A = rp_missing_A.intersect(r_have_A)
    r_send_B = rp_missing_B.intersect(r_have_B)
    print "rp_missing_A = rp_need_A - rp_have_A = ", rp_missing_A
    print "rp_missing_B = rp_need_B - rp_have_B = ", rp_missing_B
    print "r_send_A = rp_missing_A.intersect(r_have_A) = ", r_send_A
    print "r_send_B = rp_missing_B.intersect(r_have_B) = ", r_send_B
    print "\n\n"

    # V- Code generation
    ##################################################
    if (r_send_A.is_empty() == False):
        r_send_A = augment_set_with_processor(
            r_send_A, r_partitioner_A.dim(isl.dim_type.param))
    if (r_send_B.is_empty() == False):
        r_send_B = augment_set_with_processor(
            r_send_B, r_partitioner_B.dim(isl.dim_type.param))
    if (r_receive_A.is_empty() == False):
        r_receive_A = augment_set_with_processor(
            r_receive_A, r_partitioner_A.dim(isl.dim_type.param))
    if (r_receive_B.is_empty() == False):
        r_receive_B = augment_set_with_processor(
            r_receive_B, r_partitioner_B.dim(isl.dim_type.param))
    print "\n\n"
    r_send_A = r_send_A.set_tuple_name("Send_A")
    r_send_B = r_send_B.set_tuple_name("Send_B")
    r_receive_A = r_receive_A.set_tuple_name("Receive_A")
    r_receive_B = r_receive_B.set_tuple_name("Receive_B")
    print_set("Send_A   ", r_send_A)
    print "\n"
    print_set("Send_B   ", r_send_B)
    print "\n"
    print_set("Receive_A", r_receive_A)
    print "\n"
    print_set("Receive_B", r_receive_B)
    print "\n"

    uA_to_send_p = isl.UnionSet.from_set(r_send_A)
    uB_to_send_p = isl.UnionSet.from_set(r_send_B)
    ur_receive_A = isl.UnionSet.from_set(r_receive_A)
    ur_receive_B = isl.UnionSet.from_set(r_receive_B)
    uS0_dom = isl.UnionSet.from_set(S0_dom)
    domain = uA_to_send_p.union(uB_to_send_p)
    domain = domain.union(ur_receive_A)
    domain = domain.union(ur_receive_B)
    domain = domain.union(uS0_dom)
    schedule = isl.UnionMap(str_schedule)
    schedule = schedule.intersect_domain(domain)
    print "Schedule intersect domain = ", schedule
    build = isl.AstBuild.alloc(schedule.get_ctx())
    build = build.restrict(context)
    node = build.node_from_schedule_map(schedule)
    print node.to_C_str()
Ejemplo n.º 15
0
#
# 1 : 0
# {[i,j] -> [i,j',j-i] : 0 <= i < j < j' < N} union
#  {[i,j] -> [i',j,i-i'-1] : 0 <= i' < i < j < N}
#
# 1 : 1
# {[i,j] -> [i-1,j+1] : 1 <= i < j <= N-2}

N = 2500
val = str(N)

_par = "[N] -> {[i,j]->[i',j'] : N = " + val + "; [i,j]->[i',j',k'] : N = " + val + "; [i,j,k]->[i',j'] : N = " + val + "; [i,j,k]->[i',j',k'] : N = " + val + " } "

r00 = "[N] -> {[i,j,k] -> [i,j',j-i] : j < j' < N && 0 <= k && i+k < j && 0 <= i; [i,j,k] -> [i',j,i-i'-1] : 0 <= i' < i && j < N && 0 <= k && i+k < j; [i,j,k] -> [i,j,k'] : 0 <= k < k' && j < N && 0 <= i && i+k' < j}"

R00 = isl.UnionMap(str(r00))

r01 = "[N] -> {[i,j,k] -> [i-1,j+1] : j <= N-2 && 0 <= k && i+k < j && 1 <= i; [i,j,k] -> [i,j] : j < N && 0 <= k && i+k < j && 0 <= i}"

R01 = isl.UnionMap(str(r01))

r10 = "[N] -> {[i,j] -> [i,j',j-i] : 0 <= i < j < j' < N; [i,j] -> [i',j,i-i'-1] : 0 <= i' < i < j < N}"

R10 = isl.UnionMap(str(r10))

r11 = "[N] -> {[i,j] -> [i-1,j+1] : 1 <= i < j <= N-2}"

R11 = isl.UnionMap(str(r11))

PAR = isl.UnionMap(_par)
#print PAR
Ejemplo n.º 16
0
               default='schedule',
               choices=('schedule', 'c', 'opencl'),
               help='type of output')
p.add_argument('--sizes',
               required=True,
               help='per-kernel tile/grid/block sizes')
p.add_argument('--schedule', metavar='FILE', help='use schedule from FILE')
p.add_argument('--dump-schedule', action='store_true', help='dump schedule')
p.add_argument('output', help='name of output')
p.add_argument('filename', nargs='+', help='filename of source file')
args = p.parse_args()

isl_context = isl.Context.alloc()

name = args.output
sizes = isl.UnionMap(args.sizes, isl_context)

stmts = ()

for filename in args.filename:
    p = Parser(filename=filename)

    with open(filename, "r") as f:
        source = f.read()

    stmts += p.parse(source)

table = check_stmts(stmts)
context = compile(table, isl_context)
contract_arrays(context)
Ejemplo n.º 17
0
def get_assign_map(ctx, statements):
    maps = [s[0] for s in statements.values()]
    union_map = isl.UnionMap("{}", ctx)
    for m in maps:
        union_map = union_map.union(isl.UnionMap.from_map(m))
    return union_map
Ejemplo n.º 18
0
 def union_maps(self, maps):
     umap = isl.UnionMap("{}", self.ctx.isl_context)
     for m in maps:
         umap = umap.union(isl.UnionMap.from_map(m))
     return umap
Ejemplo n.º 19
0
###
#    for(i=0; i<N; i++)
# S[1]:   B[i] = f(A[i]);
#
#    for(j=0; j<N; j++)
# S[2]:   C[N-1-j] = g(B[j])

# A[i] == A[0,i]
# B[i] == A[1,i]
# C[i] == A[2,i]

import islpy as isl
import common

Sini = isl.UnionMap("[N] -> {S1[i] -> [1,i]: 0<=i<N; S2[j] -> [2,j]: 0<=j<N}")
print("Initial Schedule:")
print(Sini)

Write = isl.UnionMap(
    "[N] -> {S1[i] -> B[i]: 0<=i<N; S2[j] -> C[N-1-j]: 0<=j<N}")
Read = isl.UnionMap(
    "[N] -> {S1[i] -> A[i]: 0<=i<N; S2[j] -> B[j]    : 0<=j<N}")
Dep = common.mkDepGraph(Sini, Read, Write)
print("Dependency graph is:")
print(Dep)

Snew = isl.UnionMap("[N] -> {S1[i] -> [i,1]: 0<=i<N; S2[j] -> [j,2]: 0<=j<N}")
print("New Schedule:")
print(Snew)

(timesrcsink, is_empty) = common.checkTimeDepsPreserved(Snew, Dep)