Exemple #1
0
    def on_kernel(self, kernel_id):
        last_kernel = self.last_kernel
        self.last_kernel = kernel_id

        if not self.acc.is_empty():
            if last_kernel is not None:
                self.kernels[last_kernel].finish = True

            domain = self.acc
            self.acc = isl.UnionSet("{ }", self.ctx.isl_context)

            writes = assign_map.intersect_domain(domain).range()
            writes = list({ s.get_tuple_name() for s in to_sets(writes) })
            reads = use_map.intersect_domain(domain).range()
            reads = list({ s.get_tuple_name() for s in to_sets(reads) })

            for v in reads:
                self.cpu_access(v, write=False)

            for v in writes:
                self.cpu_access(v, write=True)

        kernel = self.kernels[kernel_id]

        for v in kernel.reads:
            self.gpu_acccess(v, kernel_id, write=False)

        for v in kernel.writes:
            self.gpu_acccess(v, kernel_id, write=True)
Exemple #2
0
def test_union_casts():
    # https://github.com/inducer/islpy/issues/29
    s1 = isl.UnionSet("{[0]}")
    s2 = isl.BasicSet("{[1]}")

    s2.union(s1)  # works fine
    s1.union(s2)  # does not work
Exemple #3
0
 def __init__(self, ctx, assign_map, use_map, arrays, domains, kernels):
     self.ctx = ctx
     self.assign_map = assign_map
     self.use_map = use_map
     self.arrays = arrays
     self.domains = domains
     self.kernels = kernels
     self.last_kernel = None
     self.acc = isl.UnionSet("{ }", ctx.isl_context)
Exemple #4
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)
Exemple #5
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
Exemple #6
0
#           for(i=1; i<=N; i++)
#             for(j=0; j<=N; j++)
# S1[i,j]:      Z[i,j] = f(Z[i-1,j]);
#
#                     |
#                     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
Exemple #7
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)
Exemple #8
0
#    for(j=0; j<=N; j++)
# 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)
Exemple #9
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)
Exemple #10
0
cmd += 'IND := Domain - LDR;'
cmd += 'print "IND";'
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:
Exemple #11
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)
Exemple #12
0
def NewTileGen(block_set, sym_exvars, vars, _SYM, symb, p_symb, par_tiling,
               rel, schedule, instrukcje):

    block_set = "BL := " + block_set[0] + ";"
    #print block_set
    R = "R := ["
    R = R + _SYM

    # dodaj zmienne symb ilorazow
    if (par_tiling):
        for i in range(0, len(sym_exvars)):
            R = R + " fff" + str(i) + ","

    R = R[:-1] + "] -> {["
    for s in vars:
        R = R + s + ","
    R = R + "v] -> ["
    for s in sym_exvars:
        R = R + s + ","
    for s in vars:
        R = R + s + ","
    R = R + "v] : "

    if (par_tiling):
        for i in range(0, len(sym_exvars)):
            R = R + " " + sym_exvars[i] + "<= fff" + str(i) + " and "

    R = R + " true };"

    isl_BL = isl.Set(str(block_set).replace("BL := ", ""))
    isl_R = isl.Map(str(R).replace("R := ", ""))
    isl_BL = isl_BL.apply(isl_R).coalesce()
    isl_BL1 = isl_BL.project_out(isl._isl.dim_type.param, 0,
                                 len(sym_exvars)).coalesce()

    BL = iscc_communicate(block_set + R + "BL := R(BL);BL;")
    with open("tmp/barv_tiling.txt", "a") as myfile:
        myfile.write(block_set + R + "BL := R(BL);BL;")

    # usun symexvars z symb
    BL = BL.split("->")
    z = "["
    for s in symb:
        z = z + s + ","
    for s in p_symb:
        z = z + s + ","
    if (par_tiling):
        for i in range(0, len(sym_exvars)):
            z = z + " fff" + str(i) + ","

    if (z != "["):
        z = z[:-1]
    z = z + "] -> "

    # poprawka gdyby za ii jj wejdzie stala

    pat = "\[" + "\w+,\s*" * len(vars)
    regex = re.compile(pat)
    tmp = "["
    for s in sym_exvars:
        tmp = tmp + s + ", "
    BB = re.sub(pat, tmp, BL[1])

    BL = "BL1 := " + z + BB + ";"

    if 0 == 1:
        Setii = iscc_communicate(BL + "BL1;")
        print Setii

    start = time.time()
    loop = iscc_communicate(BL + "codegen BL1;")
    islSet = isl.UnionSet(str(z + BB))
    codegen_ultra.codegen(islSet, instrukcje, len(sym_exvars), vars,
                          sym_exvars)
    #sys.exit()

    with open("tmp/barv_tiling.txt", "a") as myfile:
        myfile.write(BL + "codegen BL1;")
    end = time.time()
    elapsed = end - start
    print "Time taken: ", elapsed, "seconds."

    loops = []
    loops.append(loop)
    if (schedule == 0):
        return loops
    else:
        ##### OBLICZANIE REPR TILE

        nloop = ""
        srepr = ""
        with open('sources_of_slices.txt') as f:
            content = f.readlines()
            srepr = content[0]

        tmp = ""
        for s in sym_exvars:
            tmp = tmp + s + ","

        srepr = srepr.replace("{ [", "{ [" + tmp)
        srepr = srepr.replace("{[", "{ [" + tmp)

        Rel_Z = "R := {["

        for i in range(0, 2 * len(sym_exvars)):
            Rel_Z = Rel_Z + "i" + str(i) + ","
        Rel_Z = Rel_Z + "m] -> ["
        for i in range(0, len(sym_exvars)):
            Rel_Z = Rel_Z + "i" + str(i) + ","
        Rel_Z = Rel_Z[:-1] + "] };"

        output = iscc_communicate(
            BL + "Srepr := " + srepr + ";" + Rel_Z +
            "B := BL1 * Srepr;card B;print \"###\";codegen R(B);").split(
                '"###"')
        srepr_loop = output[1]

        ile = output[0]
        fs = 0
        if ("{ 1 :" in ile):
            fs = 1

        # ---------
        tmp = BL[:-1].replace("BL1 := ", "")

        rs = tmp + "->" + tmp + ";"
        #rs = iscc_communicate(tmp + "->" + tmp + ";")

        I = "I :={["
        for i in range(0, len(sym_exvars)):
            I = I + "i" + str(i) + ","
        I = I[:-1] + "] -> ["
        for i in range(0, len(sym_exvars)):
            I = I + "i" + str(i) + ","
        I = I[:-1] + "]};"

        start = time.time()
        rpaczka = iscc_communicate('R:=' + rel + ';Rst := R^+;Rst;' + I +
                                   'Rst+I;')
        rpaczka = rpaczka.split('\n')
        rplus = rpaczka[0]
        rstar = rpaczka[1]
        #rstar = iscc_communicate('R:=' + rel + ';'+I+'R^+ + I;')
        end = time.time()
        elapsed = end - start
        print "Time taken: ", elapsed, "seconds."

        tmp = ""
        tmp2 = ""
        for s in sym_exvars:
            tmp = tmp + s + ","
            tmp2 = tmp2 + s + "',"

        rplus = rplus.replace("{ [", "{ [" + tmp)
        rplus = rplus.replace("-> [", "-> [" + tmp2)
        rplus = rplus.replace("; [", "; [" + tmp)

        rstar = rstar.replace("{ [", "{ [" + tmp)
        rstar = rstar.replace("-> [", "-> [" + tmp2)
        rstar = rstar.replace("; [", "; [" + tmp)

        rt_red = rel
        rt_red = rt_red.replace("{ [", "{ [" + tmp)
        rt_red = rt_red.replace("-> [", "-> [" + tmp2)
        rt_red = rt_red.replace("; [", "; [" + tmp)

        sym_tmp = []
        rlex = "RLEX := {["
        for s in sym_exvars:
            rlex = rlex + s + ","
            sym_tmp.append(s + "'")
        rlex = rlex[:-1] + '] -> ['
        for s in sym_exvars:
            rlex = rlex + s + "',"
        rlex = rlex[:-1] + '] : '
        rlex = rlex + CreateLex(sym_tmp, sym_exvars, len(sym_exvars)) + "};"

        rs = iscc_communicate(
            "RS := " + rs + "Rplus := " + rstar + ";RS*Rplus;", 0)
        #rp = iscc_communicate("RS := " + rs + ";Rplus := " + rplus + ";RS*Rplus;", 0)

        rt_red = iscc_communicate(
            "RS:= " + rs + ";RTRED := " + rt_red + ";RS*RTRED;", 0)

        rs = iscc_communicate(rs + ";", 1).split('\n')[0]

        rs = RelationExists(rs, len(sym_exvars), symb)

        srepr_loop = srepr_loop.split('\n')

        for i in range(0, len(srepr_loop)):
            if "for" in srepr_loop[i]:
                srepr_loop.insert(i, "#pragma omp parallel for")
                break

        st_reg = re.compile('\s*\(.*\);')
        vecs = []
        taby = []
        for line in srepr_loop:
            if (st_reg.match(line)):
                vecs.append(s1_to_vec(line, len(vecs)))
                taby.append(correct.whites(line))

        #R_T = iscc_communicate("RS := " + rs + ";RS;")
        cmd = "RT :=" + rs + ";"
        for i in range(0, len(vecs)):
            cmd = cmd + vecs[i] + "codegen RT(S" + str(i) + ');print "###";'

        cmd = iscc_communicate(cmd)

        cmd = cmd.split('"###"')
        new_loop = []
        i = 0
        for line in srepr_loop:
            if (st_reg.match(line)):
                petla = cmd[i].split('\n')
                for s in petla:
                    new_loop.append(taby[i] + s)
                i = i + 1
            else:
                new_loop.append(line)

        #print new_loop
        nloop = ""
        for line in new_loop:
            if line != '':
                nloop = nloop + line + "\n"
        nloop = nloop[:-1]
        loops.append(nloop)

        #fs = 1
        if (fs == 1):
            UDS = iscc_communicate('R := ' + rel + ";dom R - ran R;")
            tmp = "{ ["
            for s in sym_exvars:
                tmp = tmp + s + ","

            UDS = UDS.replace("{ [", tmp)
            UDS = UDS.replace("; [", tmp)

            tuds = iscc_communicate(BL + 'UDS := ' + UDS + ';' + Rel_Z +
                                    'R(BL1*UDS);')

            rt_red = iscc_communicate(rt_red + ";", 1).split('\n')[0]
            rt_red = RelationExists(rt_red, len(sym_exvars), symb)

            rk = iscc_communicate(rlex + 'RT_RED := ' + rt_red +
                                  "*RLEX;pow RT_RED;")
            #rk = iscc_communicate('RT_RED := ' + rt_red + ";"+I+"Z := RT_RED-I;pow Z;")

            rk = RepairRk(rk, 1)
            #S(k) = Rk  (TILE_UDS) -  R_T+  compose  Rk (TILE_UDS)

            cmd_sk = rlex + I + "Rk := " + rk + ";TUDS :=" + tuds + ";" + 'RT_RED := ' + rt_red + "*RLEX;RP :=RT_RED^+;Sk := Rk(TUDS) - RP(Rk(TUDS));Sk;"
            #cmd_sk = I + "Rk := " + rk +";TUDS :=" + tuds + ";" + "RP :=" + rp +"-I;Sk := Rk(TUDS) - RP(Rk(TUDS));Sk;"

            sk = iscc_communicate(cmd_sk)

            reg = re.compile("^[^{]+")
            tmp = "["
            for s in symb:
                tmp = tmp + s + ","
            tmp = tmp[:-1] + "] -> "

            sk = reg.sub(tmp, sk)
            sk = sk.replace("{ [", "{ [k,")
            sk = sk.replace("; [", "; [k,")
            #print sk

            tudsk = tuds.replace("{ [", "{ [0,")
            tudsk = tudsk.replace("; [", "; [0,")

            fsloop = iscc_communicate("Sk := " + sk + ";TUDS := " + tudsk +
                                      ";Sk := Sk + TUDS; codegen Sk;")

            #usun k z symb i dodaj na poczatek krotek

            loops.append(fsloop)

        return loops