6 Commits

Author SHA1 Message Date
37ebeee97a Remove unused code and comments 2025-07-01 00:58:42 +03:00
2d47b8533b Merge branch 'master' into analyze_loops_with_IR 2025-06-29 22:10:03 +03:00
ALEXks
b8f429256f added removedUnreachableBlocks call for buildCFG 2025-06-29 16:02:37 +03:00
2fd08e79f1 Merge branch 'master' into analyze_loops_with_IR 2025-06-22 20:09:16 +03:00
ALEXks
2f53d6ae2e fixed 2025-06-22 09:22:10 +03:00
ALEXks
65237e4d63 added inductive variables and loop type to LoopGraph 2025-06-22 09:19:37 +03:00
19 changed files with 316 additions and 645 deletions

View File

@@ -1180,6 +1180,9 @@ map<FuncInfo*, vector<BBlock*>> buildCFG(const map<string, CommonBlock*>& common
if (SgFile::switchToFile(oldFile) == -1) if (SgFile::switchToFile(oldFile) == -1)
printInternalError(convertFileName(__FILE__).c_str(), __LINE__); printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
for (auto& [func, blocks] : result)
removedUnreachableBlocks(blocks);
return result; return result;
} }

View File

@@ -14,62 +14,9 @@
using namespace std; using namespace std;
using namespace SAPFOR; using namespace SAPFOR;
typedef SAPFOR::BasicBlock BBlock; static const SAPFOR::Argument CONST_UNDEFINED_ARG(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::COMMON_, "-1");
typedef SAPFOR::Argument BArgument;
static void printBlock(BBlock* block) template <typename T> static bool compareVectors(const vector<T>* vec1, const vector<T>* vec2)
{
cout << "block - " << block->getNumber() << endl;
cout << "next -";
for (auto i : block->getNext())
cout << " " << i->getNumber();
cout << endl << "prev -";
for (auto i : block->getPrev())
cout << " " << i->getNumber();
cout << endl;
for (auto i : block->getInstructions())
{
string resValue = "";
string arg1Value = "";
string arg2Value = "";
if (i->getInstruction()->getResult() != NULL && i->getInstruction()->getResult()->getType() == CFG_ARG_TYPE::VAR)
{
resValue = i->getInstruction()->getResult()->getValue();
i->getInstruction()->getResult()->setValue(i->getInstruction()->getResult()->getValue() + to_string(i->getInstruction()->getResult()->getNumber()));
}
if (i->getInstruction()->getArg1() != NULL && i->getInstruction()->getArg1()->getType() == CFG_ARG_TYPE::VAR)
{
arg1Value = i->getInstruction()->getArg1()->getValue();
i->getInstruction()->getArg1()->setValue(i->getInstruction()->getArg1()->getValue() + to_string(i->getInstruction()->getArg1()->getNumber()));
}
if (i->getInstruction()->getArg2() != NULL && i->getInstruction()->getArg2()->getType() == CFG_ARG_TYPE::VAR)
{
arg2Value = i->getInstruction()->getArg2()->getValue();
i->getInstruction()->getArg2()->setValue(i->getInstruction()->getArg2()->getValue() + to_string(i->getInstruction()->getArg2()->getNumber()));
}
cout << i->getNumber() << " " << i->getInstruction()->dump() << endl;
if (i->getInstruction()->getResult() != NULL && i->getInstruction()->getResult()->getType() == CFG_ARG_TYPE::VAR)
i->getInstruction()->getResult()->setValue(resValue);
if (i->getInstruction()->getArg1() != NULL && i->getInstruction()->getArg1()->getType() == CFG_ARG_TYPE::VAR)
i->getInstruction()->getArg1()->setValue(arg1Value);
if (i->getInstruction()->getArg2() != NULL && i->getInstruction()->getArg2()->getType() == CFG_ARG_TYPE::VAR)
i->getInstruction()->getArg2()->setValue(arg2Value);
}
cout << endl;
}
template <typename T>
static bool compareVectors(const vector<T>* vec1, const vector<T>* vec2)
{ {
if (vec1 == vec2) if (vec1 == vec2)
return true; return true;
@@ -86,35 +33,29 @@ static bool compareVectors(const vector<T>* vec1, const vector<T>* vec2)
return sortedVec1 == sortedVec2; return sortedVec1 == sortedVec2;
} }
template <typename T> template <typename T> static vector<T>* getCommonElements(const vector<vector<T>>* vectors)
static vector<T>* getCommonElements(const vector<vector<T>>* vectors)
{ {
if (!vectors || vectors->empty()) if (!vectors || vectors->empty())
return new vector<T>(); // Return an empty vector if input is null or empty return new vector<T>();
// Start with the first vector
vector<T>* commonElements = new vector<T>((*vectors)[0]); vector<T>* commonElements = new vector<T>((*vectors)[0]);
for (size_t i = 1; i < vectors->size(); ++i) for (size_t i = 1; i < vectors->size(); ++i)
{ {
vector<T> tempCommon; vector<T> tempCommon;
// Sort the current vector and common result for intersection
vector<T> sortedVec = (*vectors)[i]; vector<T> sortedVec = (*vectors)[i];
sort(commonElements->begin(), commonElements->end()); sort(commonElements->begin(), commonElements->end());
sort(sortedVec.begin(), sortedVec.end()); sort(sortedVec.begin(), sortedVec.end());
// Find the intersection
set_intersection( set_intersection(
commonElements->begin(), commonElements->end(), commonElements->begin(), commonElements->end(),
sortedVec.begin(), sortedVec.end(), sortedVec.begin(), sortedVec.end(),
back_inserter(tempCommon) back_inserter(tempCommon)
); );
// Update common result
*commonElements = tempCommon; *commonElements = tempCommon;
// If no common elements left, break early
if (commonElements->empty()) if (commonElements->empty())
break; break;
} }
@@ -123,19 +64,19 @@ static vector<T>* getCommonElements(const vector<vector<T>>* vectors)
} }
static map<BBlock*, vector<BBlock*>> findDominators(const vector<BBlock*>& blocks) static map<SAPFOR::BasicBlock*, vector<SAPFOR::BasicBlock*>> findDominators(const vector<SAPFOR::BasicBlock*>& blocks)
{ {
map<BBlock*, vector<BBlock*>> result; map<SAPFOR::BasicBlock*, vector<SAPFOR::BasicBlock*>> result;
bool changed = true; bool changed = true;
while (changed) while (changed)
{ {
changed = false; changed = false;
for (auto& currentBlock : blocks) for (auto& currentBlock : blocks)
{ {
auto pred = currentBlock->getPrev(); auto pred = currentBlock->getPrev();
auto prevDominators = new vector<vector<BBlock*>>(); auto prevDominators = new vector<vector<SAPFOR::BasicBlock*>>();
for (auto predBlock : pred) for (auto predBlock : pred)
prevDominators->push_back(result.find(predBlock) != result.end() ? result[predBlock] : blocks); prevDominators->push_back(result.find(predBlock) != result.end() ? result[predBlock] : blocks);
@@ -154,29 +95,12 @@ static map<BBlock*, vector<BBlock*>> findDominators(const vector<BBlock*>& block
return result; return result;
} }
static void renumberBlocks(BBlock* current, int* n, map<int, int>* res, set<BBlock*>* visited) { static map<SAPFOR::BasicBlock*, vector<SAPFOR::BasicBlock*>> findDominatorBorders(const vector<SAPFOR::BasicBlock*>& blocks)
if (visited->find(current) != visited->end()) {
return; map<SAPFOR::BasicBlock*, vector<SAPFOR::BasicBlock*>> result;
visited->insert(current);
vector<BBlock*> nextBlocks = current->getNext();
sort(nextBlocks.begin(), nextBlocks.end(), [](BBlock* a, BBlock* b) {
return a->getInstructions()[0]->getInstruction()->getOperator()->lineNumber() > b->getInstructions()[0]->getInstruction()->getOperator()->lineNumber();
});
for (auto& i : nextBlocks)
renumberBlocks(i, n, res, visited);
(*res)[current->getNumber()] = *n;
*n -= 1;
}
static map<BBlock*, vector<BBlock*>> findDominatorBorders(const vector<BBlock*>& blocks, map<BBlock*, BBlock*>& iDominators) {
map<BBlock*, vector<BBlock*>> result;
for (auto& block : blocks) for (auto& block : blocks)
result[block] = *(new vector<BBlock*>()); result[block] = *(new vector<SAPFOR::BasicBlock*>());
for (auto& block : blocks) for (auto& block : blocks)
{ {
@@ -185,13 +109,11 @@ static map<BBlock*, vector<BBlock*>> findDominatorBorders(const vector<BBlock*>&
for (auto prev : block->getPrev()) for (auto prev : block->getPrev())
{ {
auto tmpBlock = prev; auto tmpBlock = prev;
auto test = iDominators[block];
auto test2 = iDominators[prev];
while (tmpBlock != iDominators[block]) while (tmpBlock != block->getDom())
{ {
result[tmpBlock].push_back(block); result[tmpBlock].push_back(block);
tmpBlock = iDominators[tmpBlock]; tmpBlock = tmpBlock->getDom();
} }
} }
} }
@@ -200,122 +122,14 @@ static map<BBlock*, vector<BBlock*>> findDominatorBorders(const vector<BBlock*>&
return result; return result;
} }
static BBlock* findImmediateDominatorsDfsHelper(BBlock* block, BBlock* currentBlock, BBlock* currentImmediateDominator, vector<BBlock*> &visited, map<BBlock*, vector<BBlock*>>& dominators) static pair<set<SAPFOR::Argument*>, map<SAPFOR::Argument*, set<SAPFOR::BasicBlock*>>> getGlobalsAndVarBlocks(const vector<SAPFOR::BasicBlock*>& blocks)
{ {
if (block == currentBlock) set<SAPFOR::Argument*> globals;
return currentImmediateDominator; map<SAPFOR::Argument*, set<SAPFOR::BasicBlock*>> varBlocks;
if (find(visited.begin(), visited.end(), currentBlock) != visited.end())
return NULL;
visited.push_back(currentBlock);
if (find(dominators[block].begin(), dominators[block].end(), currentBlock) != dominators[block].end())
currentImmediateDominator = currentBlock;
for (auto& nextBlock : currentBlock->getNext())
{
auto result = findImmediateDominatorsDfsHelper(block, nextBlock, currentImmediateDominator, visited, dominators);
if (result)
return result;
}
return NULL;
}
bool checkoDom(vector<BBlock*> a, vector<BBlock*> b, BBlock* c) {
if (a.size() != b.size() + 1) {
return false;
}
for (auto i : a)
{
if (i != c && find(b.begin(), b.end(), i) == b.end()) {
return false;
}
}
return true;
}
static map<BBlock*, BBlock*> findImmediateDominators1(const map<BBlock*, vector<BBlock*>>& dominators, BBlock* entry)
{
map<BBlock*, BBlock*> iDom;
for (const auto& pair : dominators) {
BBlock* b = pair.first;
if (b == entry) continue;
const auto& doms = pair.second;
// candidates = all dominators of b except itself
bool found = false;
for (auto& d : doms) {
if (d == b) continue;
if (checkoDom(doms, dominators.at(d), b)) {
iDom[b] = d;
found = true;
break;
}
}
if (!found) {
cout << "ERRORERRORERROR " << b->getNumber() << endl;
}
}
return iDom;
}
static map<BBlock*, BBlock*> findImmediateDominators(map<BBlock*, vector<BBlock*>>& dominators, BBlock* fistBlock)
{
map<BBlock*, BBlock*> iDominators;
for (const auto& [block, domBlocks] : dominators) {
vector<BBlock*> visited;
if (block == fistBlock)
continue;
iDominators[block] = findImmediateDominatorsDfsHelper(block, fistBlock, fistBlock, visited, dominators);
}
return iDominators;
}
static vector<BArgument*> getDefForBlock(const BBlock& block)
{
vector<BArgument*> def;
const auto& instructions = block.getInstructions();
for (const auto& irBlock : instructions)
{
if (irBlock)
{
Instruction* instr = irBlock->getInstruction();
if (instr)
{
BArgument* result = instr->getResult();
if (result)
def.push_back(result);
}
}
}
return def;
}
static pair<set<BArgument*>, map<BArgument*, set<BBlock*>>> getGlobalsAndVarBlocks(const vector<BBlock*>& blocks) {
set<BArgument*> globals;
map<BArgument*, set<BBlock*>> varBlocks;
for (auto& block : blocks) for (auto& block : blocks)
{ {
set<BArgument*> def; set<SAPFOR::Argument*> def;
const auto& instructions = block->getInstructions(); const auto& instructions = block->getInstructions();
for (const auto& irBlock : instructions) for (const auto& irBlock : instructions)
@@ -349,18 +163,18 @@ static pair<set<BArgument*>, map<BArgument*, set<BBlock*>>> getGlobalsAndVarBloc
return make_pair(globals, varBlocks); return make_pair(globals, varBlocks);
} }
static void getBlocksWithFiFunctions(const vector<BBlock*> blocks, set<BArgument*>& globals, static void getBlocksWithFiFunctions(const vector<SAPFOR::BasicBlock*> blocks, set<SAPFOR::Argument*>& globals,
map<BArgument*, set<BBlock*>>& varBlocks, map<SAPFOR::Argument*, set<SAPFOR::BasicBlock*>>& varBlocks,
map<BBlock*, vector<BBlock*>>& dominatorBorders) map<SAPFOR::BasicBlock*, vector<SAPFOR::BasicBlock*>>& dominatorBorders)
{ {
vector<BBlock*> blocksWithFiFunctions; vector<SAPFOR::BasicBlock*> blocksWithFiFunctions;
auto fiFunc = new BArgument(CFG_ARG_TYPE::FUNC, CFG_MEM_TYPE::NONE_, "FI_FUNCTION"); auto fiFunc = new SAPFOR::Argument(CFG_ARG_TYPE::FUNC, CFG_MEM_TYPE::NONE_, "FI_FUNCTION");
auto paramCount = new BArgument(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::LOCAL_, "0"); auto paramCount = new SAPFOR::Argument(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::LOCAL_, "0");
for (auto& var : globals) for (auto& var : globals)
{ {
auto worklist = varBlocks[var]; auto worklist = varBlocks[var];
set<BBlock*> hasFiFunction; set<SAPFOR::BasicBlock*> hasFiFunction;
while (!worklist.empty()) while (!worklist.empty())
{ {
@@ -372,81 +186,53 @@ static void getBlocksWithFiFunctions(const vector<BBlock*> blocks, set<BArgument
if (hasFiFunction.find(dfBlock) == hasFiFunction.end()) if (hasFiFunction.find(dfBlock) == hasFiFunction.end())
{ {
hasFiFunction.insert(dfBlock); hasFiFunction.insert(dfBlock);
Instruction* phiInstruction = new Instruction(CFG_OP::F_CALL, new BArgument(*fiFunc), new BArgument(*paramCount), var, dfBlock->getInstructions()[0]->getInstruction()->getOperator()); Instruction* phiInstruction = new Instruction(CFG_OP::F_CALL, new SAPFOR::Argument(*fiFunc), new SAPFOR::Argument(*paramCount), var, dfBlock->getInstructions()[0]->getInstruction()->getOperator());
IR_Block* phiBlock = new IR_Block(phiInstruction); IR_Block* phiBlock = new IR_Block(phiInstruction);
dfBlock->addInstruction(phiBlock, true); dfBlock->addInstruction(phiBlock, true);
//blocksWithFiFunctions.push_back(dfBlock);
} }
} }
} }
} }
//return blocksWithFiFunctions;
} }
static string ToString(CFG_ARG_TYPE type) static void restoreConnections(const vector<SAPFOR::BasicBlock*>& originalBlocks, vector<SAPFOR::BasicBlock*>& copiedBlocks)
{ {
switch (type) { map<SAPFOR::BasicBlock*, SAPFOR::BasicBlock*> blockMapping;
case CFG_ARG_TYPE::NONE: return "NONE";
case CFG_ARG_TYPE::REG: return "REG";
case CFG_ARG_TYPE::VAR: return "VAR";
case CFG_ARG_TYPE::ARRAY: return "ARRAY";
case CFG_ARG_TYPE::CONST: return "CONST";
case CFG_ARG_TYPE::FUNC: return "FUNC";
case CFG_ARG_TYPE::LAB: return "LAB";
case CFG_ARG_TYPE::INSTR: return "INSTR";
case CFG_ARG_TYPE::CONST_STR: return "CONST_STR";
case CFG_ARG_TYPE::RECORD: return "RECORD";
case CFG_ARG_TYPE::CONSTR_REF: return "CONSTR_REF";
default: return "UNKNOWN";
}
}
static void restoreConnections(const vector<BBlock*>& originalBlocks, vector<BBlock*>& copiedBlocks)
{
// Создаем отображение оригинальных блоков в их копии
map<BBlock*, BBlock*> blockMapping;
for (size_t i = 0; i < originalBlocks.size(); ++i) for (size_t i = 0; i < originalBlocks.size(); ++i)
blockMapping[originalBlocks[i]] = copiedBlocks[i]; blockMapping[originalBlocks[i]] = copiedBlocks[i];
// Восстанавливаем связи между копиями
for (size_t i = 0; i < originalBlocks.size(); ++i) for (size_t i = 0; i < originalBlocks.size(); ++i)
{ {
BBlock* originalBlock = originalBlocks[i]; SAPFOR::BasicBlock* originalBlock = originalBlocks[i];
BBlock* copiedBlock = copiedBlocks[i]; SAPFOR::BasicBlock* copiedBlock = copiedBlocks[i];
auto prevCopy = copiedBlock->getPrev(); auto prevCopy = copiedBlock->getPrev();
for (auto j : prevCopy) for (auto j : prevCopy)
copiedBlock->removePrev(j); copiedBlock->removePrev(j);
// Копируем, затем удаляем next связи
auto nextCopy = copiedBlock->getNext(); auto nextCopy = copiedBlock->getNext();
for (auto j : nextCopy) for (auto j : nextCopy)
copiedBlock->removeNext(j); copiedBlock->removeNext(j);
// Восстанавливаем связи succ (следующих блоков)
for (auto* succ : originalBlock->getNext()) for (auto* succ : originalBlock->getNext())
copiedBlock->addNext(blockMapping[succ]); copiedBlock->addNext(blockMapping[succ]);
// Восстанавливаем связи prev (предыдущих блоков)
for (auto* prev : originalBlock->getPrev()) for (auto* prev : originalBlock->getPrev())
copiedBlock->addPrev(blockMapping[prev]); copiedBlock->addPrev(blockMapping[prev]);
} }
} }
static BArgument* newName(BArgument* var, map<string, int>& counter, map<string, stack<BArgument*>>& stack, int number) { static SAPFOR::Argument* newName(SAPFOR::Argument* var, map<string, int>& counter, map<string, stack<SAPFOR::Argument*>>& stack, int number) {
//int index = counter[var->getValue()];
counter[var->getValue()]++; counter[var->getValue()]++;
BArgument* newName = new BArgument(var->getType(), var->getMemType(), var->getValue(), number); SAPFOR::Argument* newName = new SAPFOR::Argument(var->getType(), var->getMemType(), var->getValue(), number);
stack[var->getValue()].push(newName); stack[var->getValue()].push(newName);
return newName; return newName;
} }
static void renameFiFunctionResultVar(BBlock* block, map<string, int>& counter, map<string, stack<BArgument*>>& stack) { static void renameFiFunctionResultVar(SAPFOR::BasicBlock* block, map<string, int>& counter, map<string, stack<SAPFOR::Argument*>>& stack) {
for (auto& irBlock : block->getInstructions()) for (auto& irBlock : block->getInstructions())
{ {
auto instruction = irBlock->getInstruction(); auto instruction = irBlock->getInstruction();
@@ -458,7 +244,7 @@ static void renameFiFunctionResultVar(BBlock* block, map<string, int>& counter,
} }
} }
static void renameInstructionVars(BBlock* block, map<string, int>& counter, map<string, stack<BArgument*>>& stack) static void renameInstructionVars(SAPFOR::BasicBlock* block, map<string, int>& counter, map<string, stack<SAPFOR::Argument*>>& stack)
{ {
for (auto& irBlock : block->getInstructions()) for (auto& irBlock : block->getInstructions())
{ {
@@ -475,13 +261,11 @@ static void renameInstructionVars(BBlock* block, map<string, int>& counter, map<
} }
} }
static void renameFiFunctionArgsVar(BBlock* block, map<string, stack<BArgument*>>& stack) static void renameFiFunctionArgsVar(SAPFOR::BasicBlock* block, map<string, stack<SAPFOR::Argument*>>& stack)
{ {
auto size = block->getInstructions().size(); auto size = block->getInstructions().size();
auto& instructions = block->getInstructions(); auto& instructions = block->getInstructions();
//cout << "try to insert Phi to block - " << block->getNumber() << endl;
for (size_t i = 0; i < size; ++i) for (size_t i = 0; i < size; ++i)
{ {
auto irBlock = instructions[i]; auto irBlock = instructions[i];
@@ -490,17 +274,16 @@ static void renameFiFunctionArgsVar(BBlock* block, map<string, stack<BArgument*>
instruction->getArg1()->getValue() == "FI_FUNCTION" && instruction->getResult() != NULL && instruction->getArg1()->getValue() == "FI_FUNCTION" && instruction->getResult() != NULL &&
instruction->getArg2() != NULL) instruction->getArg2() != NULL)
{ {
//cout << "Insert Phi to block - " << block->getNumber() << endl;
Instruction* paramInstruction; Instruction* paramInstruction;
if (stack[instruction->getResult()->getValue()].size() > 0) if (stack[instruction->getResult()->getValue()].size() > 0)
{ {
BArgument* tmp = new BArgument(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::COMMON_, to_string(stack[instruction->getResult()->getValue()].top()->getNumber())); SAPFOR::Argument* tmp = new SAPFOR::Argument(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::COMMON_, to_string(stack[instruction->getResult()->getValue()].top()->getNumber()));
paramInstruction = new Instruction(CFG_OP::PARAM, tmp); paramInstruction = new Instruction(CFG_OP::PARAM, tmp);
} }
else else
{ {
BArgument* tmp = new BArgument(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::COMMON_, "-1"); SAPFOR::Argument* tmp = new SAPFOR::Argument(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::COMMON_, "-1");
paramInstruction = new Instruction(CFG_OP::PARAM, tmp); paramInstruction = new Instruction(CFG_OP::PARAM, tmp);
} }
@@ -513,30 +296,27 @@ static void renameFiFunctionArgsVar(BBlock* block, map<string, stack<BArgument*>
} }
} }
static vector<BBlock*> findBlocksWithValue(map<BBlock*, BBlock*>& iDominators, BBlock* x) static vector<SAPFOR::BasicBlock*> findBlocksWithValue(vector<SAPFOR::BasicBlock*>& blocks, SAPFOR::BasicBlock* x)
{ {
vector<BBlock*> result; vector<SAPFOR::BasicBlock*> result;
// Проходим по всем элементам map for (auto& block : blocks)
for (auto& pair : iDominators) if (block->getDom() == x)
if (pair.second == x) // Если значение равно x, добавляем ключ в результат result.push_back(block);
result.push_back(pair.first);
return result; return result;
} }
static void renameIR(BBlock* block, map<BBlock*, BBlock*>& iDominators, map<string, int>& counter, map<string, stack<BArgument*>>& stack) { static void renameIR(SAPFOR::BasicBlock* block, vector<SAPFOR::BasicBlock*>& blocks, map<string, int>& counter, map<string, stack<SAPFOR::Argument*>>& stack)
{
//cout << "renameIR for block " << block->getNumber() << endl;
renameFiFunctionResultVar(block, counter, stack); renameFiFunctionResultVar(block, counter, stack);
renameInstructionVars(block, counter, stack); renameInstructionVars(block, counter, stack);
for (auto& successor : block->getNext()) for (auto& successor : block->getNext())
renameFiFunctionArgsVar(successor, stack); renameFiFunctionArgsVar(successor, stack);
for (auto& child : findBlocksWithValue(iDominators, block)) for (auto& child : findBlocksWithValue(blocks, block))
renameIR(child, iDominators, counter, stack); renameIR(child, blocks, counter, stack);
for (auto& irBlock : block->getInstructions()) for (auto& irBlock : block->getInstructions())
{ {
@@ -560,119 +340,47 @@ static void renameIR(BBlock* block, map<BBlock*, BBlock*>& iDominators, map<stri
} }
} }
bool isEqual1(const char* cstr, const std::string& str) { void buildFuncIRSSAForm(FuncInfo* funcInfo, const std::vector<SAPFOR::BasicBlock*>& funcIRConst, std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& result)
return str == cstr; {
} vector<SAPFOR::BasicBlock*> funcIR;
void buildIRSSAForm(const map<FuncInfo*, vector<BBlock*>>& fullIR, for (auto& i : funcIRConst)
map<FuncInfo*, vector<BBlock*>>& result) { funcIR.push_back(new SAPFOR::BasicBlock(*i));
for (auto& [funcinfo, funcIRConst]: fullIR) { restoreConnections(funcIRConst, funcIR);
if (isEqual1("csol.for", funcinfo->fileName) || isEqual1("reblns.for", funcinfo->fileName) || isEqual1("adjont.for", funcinfo->fileName)
|| isEqual1("beginf.for", funcinfo->fileName) || isEqual1("dsnp1.for", funcinfo->fileName) || isEqual1("dsnpnm.for", funcinfo->fileName)
|| isEqual1("decod3.for", funcinfo->fileName))
continue;
cout << "Testing " << funcinfo->funcName << endl; SAPFOR::buildDominatorTree(funcIR);
vector<BBlock*> funcIR; auto dominatorBorders = findDominatorBorders(funcIR);
/* for (auto& i : funcIRConst) { auto globalsAndVarBlocks = getGlobalsAndVarBlocks(funcIR);
printBlock(i); auto globals = globalsAndVarBlocks.first;
}*/ auto varBlocks = globalsAndVarBlocks.second;
for (auto& i : funcIRConst) getBlocksWithFiFunctions(funcIR, globals, varBlocks, dominatorBorders);
funcIR.push_back(new BBlock(*i));
restoreConnections(funcIRConst, funcIR); map<string, int> count;
map<string, stack<SAPFOR::Argument*>> varStack;
/*for (auto& i : funcIR) { for (auto& var : globals)
printBlock(i); {
}*/ count[var->getValue()] = 0;
for (auto& [func, bblocks] : result)
SAPFOR::buildDominatorTree(bblocks);
auto dominators = findDominators(funcIR);
/*cout << endl << endl << endl << "DOMINATORS" << endl << endl << endl; stack<SAPFOR::Argument*> tmp;
tmp.push(new SAPFOR::Argument(CONST_UNDEFINED_ARG));
for (auto i : dominators) { varStack[var->getValue()] = tmp;
cout << "block - " << i.first->getNumber() << endl;
for (auto j : i.second) {
cout << "dominators - " << j->getNumber() << endl;
}
cout << endl;
}*/
auto iDominators = findImmediateDominators1(dominators, funcIR[0]);
/*for (auto i : iDominators) {
cout << "block - " << i.first->getNumber() << endl;
cout << "Idominators - " << i.second->getNumber() << endl;
cout << endl;
}
*/
auto dominatorBorders = findDominatorBorders(funcIR, iDominators);
/*for (auto i : dominatorBorders) {
cout << "block - " << i.first->getNumber() << endl;
for (auto j : i.second) {
cout << "border - " << j->getNumber() << endl;
}
cout << endl;
}*/
auto globalsAndVarBlocks = getGlobalsAndVarBlocks(funcIR);
auto globals = globalsAndVarBlocks.first;
auto varBlocks = globalsAndVarBlocks.second;
/*for (auto i : globals) {
cout << i->getValue() << " " << ToString(i->getType()) << " " << i->getNumber() << endl;
}
cout << endl;
for (auto i : varBlocks) {
cout << i.first->getValue() << " - ";
for (auto j : i.second) {
cout << j->getNumber() << ", ";
}
cout << endl;
}
cout << endl;
*/
getBlocksWithFiFunctions(funcIR, globals, varBlocks, dominatorBorders);
map<string, int> count;
map<string, stack<BArgument*>> varStack;
for (auto& var : globals)
{
count[var->getValue()] = 0;
stack<BArgument*> tmp;
BArgument* tmpArgument = new BArgument(CFG_ARG_TYPE::CONST, CFG_MEM_TYPE::COMMON_, "-1");
tmp.push(tmpArgument);
varStack[var->getValue()] = tmp;
}
/*for (auto& i : funcIR) {
printBlock(i);
}*/
renameIR(funcIR[0], iDominators, count, varStack);
//cout << endl << endl << "___________________" << endl << endl;
/*for (auto& i : funcIR) {
printBlock(i);
}*/
//cout << endl << endl << endl << endl << endl;
//for (auto i : funcIRConst) {
// printBlock(i);
//}
result[funcinfo] = funcIR;
} }
renameIR(funcIR[0], funcIR, count, varStack);
result[funcInfo] = funcIR;
} }
FuncInfo* getIRByFilename(const std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& fullIR, const char* filename)
{
for (auto ir : fullIR)
if (ir.first->fileName == filename)
return ir.first;
return nullptr;
}

View File

@@ -3,4 +3,6 @@
#include "CFGraph.h" #include "CFGraph.h"
#include "IR.h" #include "IR.h"
void buildIRSSAForm(const std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& fullIR, std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& result); void buildFuncIRSSAForm(FuncInfo* funcInfo, const std::vector<SAPFOR::BasicBlock*>& fullIR, std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& result);
FuncInfo* getIRByFilename(const std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& fullIR, const char* filename);

View File

@@ -250,7 +250,7 @@ static set<SAPFOR::BasicBlock*> analyzeLoop(LoopGraph* loop, const set<SAPFOR::B
const map<string, SgSymbol*>& commonArgs, FuncInfo* func, const map<string, SgSymbol*>& commonArgs, FuncInfo* func,
map<string, vector<Messages>>& messages) map<string, vector<Messages>>& messages)
{ {
if (!loop->isFor) if (!loop->isFor())
printInternalError(convertFileName(__FILE__).c_str(), __LINE__); //should be called only with FOR loops printInternalError(convertFileName(__FILE__).c_str(), __LINE__); //should be called only with FOR loops
SgStatement* loop_operator = loop->loop->GetOriginal(); SgStatement* loop_operator = loop->loop->GetOriginal();
@@ -450,7 +450,7 @@ static void recAnalyzeLoop(LoopGraph* loop, const set<SAPFOR::BasicBlock*>& bloc
const map<string, SgSymbol*>& commonArgs, const map<string, SgSymbol*>& commonArgs,
FuncInfo* func, map<string, vector<Messages>>& messages) FuncInfo* func, map<string, vector<Messages>>& messages)
{ {
const auto& loop_body = loop->isFor ? analyzeLoop(loop, blocks, commonVars, commonArgs, func, messages) : blocks; const auto& loop_body = loop->isFor() ? analyzeLoop(loop, blocks, commonVars, commonArgs, func, messages) : blocks;
for (const auto& inner_loop : loop->children) for (const auto& inner_loop : loop->children)
recAnalyzeLoop(inner_loop, loop_body, commonVars, commonArgs, func, messages); recAnalyzeLoop(inner_loop, loop_body, commonVars, commonArgs, func, messages);

View File

@@ -75,7 +75,7 @@ static LoopGraph* createDirectiveForLoop(LoopGraph *currentLoop, MapToArray &mai
} }
} }
directive->parallel.push_back(currentLoop->loopSymbol); directive->parallel.push_back(currentLoop->loopSymbol());
directive->arrayRef = mainArray.arrayRef; directive->arrayRef = mainArray.arrayRef;
DIST::Array *tmp = mainArray.arrayRef; DIST::Array *tmp = mainArray.arrayRef;
@@ -84,7 +84,7 @@ static LoopGraph* createDirectiveForLoop(LoopGraph *currentLoop, MapToArray &mai
for (int i = 0; i < tmp->GetDimSize(); ++i) for (int i = 0; i < tmp->GetDimSize(); ++i)
{ {
if (i == pos) if (i == pos)
directive->on.push_back(make_pair(currentLoop->loopSymbol, mainAccess)); directive->on.push_back(make_pair(currentLoop->loopSymbol(), mainAccess));
else else
directive->on.push_back(make_pair("*", make_pair(0, 0))); directive->on.push_back(make_pair("*", make_pair(0, 0)));
} }
@@ -808,7 +808,7 @@ void createParallelDirectives(const map<LoopGraph*, map<DIST::Array*, ArrayInfo*
for (int i = 0; i < mainArrayOfLoop->GetDimSize(); ++i) for (int i = 0; i < mainArrayOfLoop->GetDimSize(); ++i)
{ {
if (i == dimPos) if (i == dimPos)
parDir->on2.push_back(make_pair(currLoop->loopSymbol, mainAccess)); parDir->on2.push_back(make_pair(currLoop->loopSymbol(), mainAccess));
else else
parDir->on2.push_back(make_pair("*", make_pair(0, 0))); parDir->on2.push_back(make_pair("*", make_pair(0, 0)));
} }
@@ -1100,7 +1100,7 @@ static bool tryToResolveUnmatchedDims(const map<DIST::Array*, vector<bool>> &dim
LoopGraph* tmpL = loop; LoopGraph* tmpL = loop;
for (int z = 0; z < nested; ++z) for (int z = 0; z < nested; ++z)
{ {
deprecateToMatch.insert(tmpL->loopSymbol); deprecateToMatch.insert(tmpL->loopSymbol());
if (tmpL->children.size()) if (tmpL->children.size())
tmpL = tmpL->children[0]; tmpL = tmpL->children[0];
else if (z != nested - 1) else if (z != nested - 1)
@@ -1113,7 +1113,7 @@ static bool tryToResolveUnmatchedDims(const map<DIST::Array*, vector<bool>> &dim
tmpL = loop->parent; tmpL = loop->parent;
while (tmpL) while (tmpL)
{ {
if (!tmpL->isFor) // TODO: need to add all inductive variables! if (tmpL->isWhile()) // TODO: need to add all inductive variables!
{ {
SgWhileStmt* dow = isSgWhileStmt(tmpL->loop->GetOriginal()); SgWhileStmt* dow = isSgWhileStmt(tmpL->loop->GetOriginal());
if (dow->conditional()) if (dow->conditional())
@@ -1124,7 +1124,7 @@ static bool tryToResolveUnmatchedDims(const map<DIST::Array*, vector<bool>> &dim
} }
} }
else else
deprecateToMatch.insert(tmpL->loopSymbol); deprecateToMatch.insert(tmpL->loopSymbol());
tmpL = tmpL->parent; tmpL = tmpL->parent;
} }

View File

@@ -346,7 +346,7 @@ static vector<SgExpression*>
{ {
needToAdd = true; needToAdd = true;
dim_found = true; dim_found = true;
subs[i] = new SgVarRefExp(findSymbolOrCreate(file, currLoop->loopSymbol)); subs[i] = new SgVarRefExp(findSymbolOrCreate(file, currLoop->loopSymbol()));
break; break;
} }
} }

View File

@@ -699,7 +699,12 @@ void loopGraphAnalyzer(SgFile *file, vector<LoopGraph*> &loopGraph, const vector
newLoop->hasPrints = hasThisIds(st, newLoop->linesOfIO, { WRITE_STAT, READ_STAT, OPEN_STAT, CLOSE_STAT, PRINT_STAT } ); // FORMAT_STAT newLoop->hasPrints = hasThisIds(st, newLoop->linesOfIO, { WRITE_STAT, READ_STAT, OPEN_STAT, CLOSE_STAT, PRINT_STAT } ); // FORMAT_STAT
newLoop->hasStops = hasThisIds(st, newLoop->linesOfStop, { STOP_STAT, PAUSE_NODE }); newLoop->hasStops = hasThisIds(st, newLoop->linesOfStop, { STOP_STAT, PAUSE_NODE });
newLoop->hasDvmIntervals = hasThisIds(st, tmpLines, { DVM_INTERVAL_DIR, DVM_ENDINTERVAL_DIR, DVM_EXIT_INTERVAL_DIR }); newLoop->hasDvmIntervals = hasThisIds(st, tmpLines, { DVM_INTERVAL_DIR, DVM_ENDINTERVAL_DIR, DVM_EXIT_INTERVAL_DIR });
newLoop->isFor = isSgForStmt(st) ? true : false; if (isSgForStmt(st))
newLoop->loopType = LoopType::FOR;
else if (isSgWhileStmt(st))
newLoop->loopType = LoopType::WHILE;
else
newLoop->loopType = LoopType::NONE;
newLoop->inCanonicalFrom = isSgForStmt(st) ? true : false; newLoop->inCanonicalFrom = isSgForStmt(st) ? true : false;
newLoop->hasSubstringRefs = hasSubstringRef(st); newLoop->hasSubstringRefs = hasSubstringRef(st);
@@ -777,7 +782,7 @@ void loopGraphAnalyzer(SgFile *file, vector<LoopGraph*> &loopGraph, const vector
newLoop->startEndExpr = std::make_pair((Expression*)NULL, (Expression*)NULL); newLoop->startEndExpr = std::make_pair((Expression*)NULL, (Expression*)NULL);
newLoop->loop = new Statement(st); newLoop->loop = new Statement(st);
newLoop->loopSymbol = st->symbol() ? st->symbol()->identifier() : "unknown"; newLoop->loopSymbols.addMainVar(st->symbol() ? st->symbol()->identifier() : "unknown");
findArrayRefs(newLoop); findArrayRefs(newLoop);
SgStatement *lexPrev = st->lexPrev(); SgStatement *lexPrev = st->lexPrev();

View File

@@ -25,6 +25,33 @@ namespace DIST = Distribution;
void getRealArrayRefs(DIST::Array* addTo, DIST::Array* curr, std::set<DIST::Array*>& realArrayRefs, const std::map<DIST::Array*, std::set<DIST::Array*>>& arrayLinksByFuncCalls); void getRealArrayRefs(DIST::Array* addTo, DIST::Array* curr, std::set<DIST::Array*>& realArrayRefs, const std::map<DIST::Array*, std::set<DIST::Array*>>& arrayLinksByFuncCalls);
void getAllArrayRefs(DIST::Array* addTo, DIST::Array* curr, std::set<DIST::Array*>& realArrayRefs, const std::map<DIST::Array*, std::set<DIST::Array*>>& arrayLinksByFuncCalls); void getAllArrayRefs(DIST::Array* addTo, DIST::Array* curr, std::set<DIST::Array*>& realArrayRefs, const std::map<DIST::Array*, std::set<DIST::Array*>>& arrayLinksByFuncCalls);
enum class LoopType { NONE, FOR, WHILE, IMPLICIT };
struct InductiveVariables
{
private:
std::string mainVar;
std::set<std::string> allVars;
public:
InductiveVariables() { }
explicit InductiveVariables(const std::string& mainVar, const std::set<std::string>& allVars) : mainVar(mainVar), allVars(allVars) { };
std::string getMainVar() const { return mainVar; }
std::set<std::string> getAllVars() const { return allVars; }
void addVar(const std::string& var) { allVars.insert(var); }
void addMainVar(const std::string& var) { mainVar = var; allVars.insert(var); }
void replaceMainVar(const std::string& var)
{
allVars.erase(mainVar);
addMainVar(var);
}
};
struct LoopGraph struct LoopGraph
{ {
private: private:
@@ -70,7 +97,7 @@ public:
calculatedCountOfIters = 0; calculatedCountOfIters = 0;
executionTimeInSec = -1.0; executionTimeInSec = -1.0;
inDvmhRegion = 0; inDvmhRegion = 0;
isFor = false; loopType = LoopType::NONE;
inCanonicalFrom = false; inCanonicalFrom = false;
hasAccessToSubArray = false; hasAccessToSubArray = false;
hasSubstringRefs = false; hasSubstringRefs = false;
@@ -113,21 +140,24 @@ public:
{ {
return hasUnknownArrayDep || hasUnknownScalarDep || hasGoto || hasPrints || (hasConflicts.size() != 0) || hasStops || hasNonPureProcedures || return hasUnknownArrayDep || hasUnknownScalarDep || hasGoto || hasPrints || (hasConflicts.size() != 0) || hasStops || hasNonPureProcedures ||
hasUnknownArrayAssigns || hasNonRectangularBounds || hasIndirectAccess || hasWritesToNonDistribute || hasDifferentAlignRules || hasDvmIntervals || hasUnknownArrayAssigns || hasNonRectangularBounds || hasIndirectAccess || hasWritesToNonDistribute || hasDifferentAlignRules || hasDvmIntervals ||
!isFor || lastprivateScalars.size() || hasAccessToSubArray || hasSubstringRefs; !isFor() || lastprivateScalars.size() || hasAccessToSubArray || hasSubstringRefs;
} }
bool hasLimitsToSplit() const bool hasLimitsToSplit() const
{ {
return hasGoto || hasStops || !isFor || hasPrints; return hasGoto || hasStops || !isFor() || hasPrints;
} }
bool hasLimitsToCombine() const bool hasLimitsToCombine() const
{ {
return hasGoto || hasStops || !isFor || hasPrints || linesOfCycle.size(); return hasGoto || hasStops || !isFor() || hasPrints || linesOfCycle.size();
} }
void addConflictMessages(std::vector<Messages> *messages) void addConflictMessages(std::vector<Messages> *messages)
{ {
if (messages == NULL)
return;
const int line = altLineNum > 0 ? altLineNum : lineNum; const int line = altLineNum > 0 ? altLineNum : lineNum;
if (hasUnknownArrayDep) if (hasUnknownArrayDep)
messages->push_back(Messages(NOTE, line, R113, L"unknown array dependency prevents parallelization of this loop", 3006)); messages->push_back(Messages(NOTE, line, R113, L"unknown array dependency prevents parallelization of this loop", 3006));
@@ -168,7 +198,7 @@ public:
if (hasDvmIntervals) if (hasDvmIntervals)
messages->push_back(Messages(NOTE, line, R145, L"DVM intervals prevent parallelization of this loop", 3006)); messages->push_back(Messages(NOTE, line, R145, L"DVM intervals prevent parallelization of this loop", 3006));
if (!isFor || !inCanonicalFrom) if (!isFor() || !inCanonicalFrom)
messages->push_back(Messages(NOTE, line, R178, L"This type of loop is not supported by the system", 3006)); messages->push_back(Messages(NOTE, line, R178, L"This type of loop is not supported by the system", 3006));
if (lastprivateScalars.size()) if (lastprivateScalars.size())
@@ -393,6 +423,14 @@ public:
void* getRealStat(const char* file) const; void* getRealStat(const char* file) const;
bool isFor() const { return loopType == LoopType::FOR; }
bool isWhile() const { return loopType == LoopType::WHILE; }
bool isImplicit() const { return loopType == LoopType::IMPLICIT; }
std::string loopSymbol() const { return loopSymbols.getMainVar(); }
public: public:
int lineNum; int lineNum;
int altLineNum; int altLineNum;
@@ -407,7 +445,7 @@ public:
int startVal, endVal, stepVal; int startVal, endVal, stepVal;
std::tuple<Expression*, Expression*, Expression*> startEndStepVals; std::tuple<Expression*, Expression*, Expression*> startEndStepVals;
std::string loopSymbol; InductiveVariables loopSymbols;
std::pair<Expression*, Expression*> startEndExpr; std::pair<Expression*, Expression*> startEndExpr;
bool hasGoto; bool hasGoto;
@@ -448,7 +486,7 @@ public:
bool hasSubstringRefs; bool hasSubstringRefs;
bool isFor; LoopType loopType;
bool inCanonicalFrom; bool inCanonicalFrom;

View File

@@ -551,7 +551,7 @@ void addToDistributionGraph(const map<LoopGraph*, map<DIST::Array*, ArrayInfo*>>
continue; continue;
} }
if (!loopAccess.first->isFor) if (!loopAccess.first->isFor())
continue; continue;
DIST::GraphCSR<int, double, attrType>& G = currReg->GetGraphToModify(); DIST::GraphCSR<int, double, attrType>& G = currReg->GetGraphToModify();
@@ -775,7 +775,7 @@ static void isAllOk(const vector<LoopGraph*> &loops, vector<Messages> &currMessa
{ {
if (loops[i]->region) if (loops[i]->region)
{ {
if (loops[i]->countOfIters == 0 && loops[i]->region && loops[i]->isFor) if (loops[i]->countOfIters == 0 && loops[i]->region && loops[i]->isFor())
{ {
wstring bufE, bufR; wstring bufE, bufR;
__spf_printToLongBuf(bufE, L" Can not calculate count of iterations for this loop, information about iterations in all loops in parallel regions '%s' will be ignored", __spf_printToLongBuf(bufE, L" Can not calculate count of iterations for this loop, information about iterations in all loops in parallel regions '%s' will be ignored",

View File

@@ -27,97 +27,51 @@ enum VisitState { UNVISITED = 0, VISITING = 1, VISITED = 2 };
void dfs(SAPFOR::BasicBlock* block, void dfs(SAPFOR::BasicBlock* block,
std::map<int, int>& visit, std::map<int, int>& visit,
std::vector<std::pair<SAPFOR::BasicBlock*, SAPFOR::BasicBlock*>>& startAndEnd, std::vector<std::pair<SAPFOR::BasicBlock*, SAPFOR::BasicBlock*>>& startAndEnd,
SAPFOR::BasicBlock* prev) { SAPFOR::BasicBlock* prev)
if (!block) return; {
if (!block)
return;
int id = block->getNumber(); int id = block->getNumber();
if (visit[id] == VISITING) { if (visit[id] == VISITING) {
// Обратное ребро — фиксируем цикл
startAndEnd.emplace_back(prev, block); startAndEnd.emplace_back(prev, block);
//std::cout << "Back edge detected: " << prev->getNumber() << " -> " << id << std::endl;
return; return;
} }
if (visit[id] == VISITED) { if (visit[id] == VISITED)
return; return;
}
visit[id] = VISITING; visit[id] = VISITING;
for (auto next : block->getNext()) { for (auto next : block->getNext())
dfs(next, visit, startAndEnd, block); dfs(next, visit, startAndEnd, block);
}
visit[id] = VISITED; visit[id] = VISITED;
} }
static void printBlock(SAPFOR::BasicBlock* block) { void getLoopBody(SAPFOR::BasicBlock* loopHeader, const std::set<SAPFOR::BasicBlock*>& loopExits, std::vector<SAPFOR::BasicBlock*>& loopBody)
cout << "block - " << block->getNumber() << endl; {
cout << "next -";
for (auto i : block->getNext())
{
cout << " " << i->getNumber();
}
cout << endl << "prev -";
for (auto i : block->getPrev())
{
cout << " " << i->getNumber();
}
cout << endl;
for (auto i : block->getInstructions())
{
string resValue = "";
string arg1Value = "";
string arg2Value = "";
if (i->getInstruction()->getResult() != nullptr && i->getInstruction()->getResult()->getType() == CFG_ARG_TYPE::VAR) {
resValue = i->getInstruction()->getResult()->getValue();
i->getInstruction()->getResult()->setValue(i->getInstruction()->getResult()->getValue() + to_string(i->getInstruction()->getResult()->getNumber()));
}
if (i->getInstruction()->getArg1() != nullptr && i->getInstruction()->getArg1()->getType() == CFG_ARG_TYPE::VAR) {
arg1Value = i->getInstruction()->getArg1()->getValue();
i->getInstruction()->getArg1()->setValue(i->getInstruction()->getArg1()->getValue() + to_string(i->getInstruction()->getArg1()->getNumber()));
}
if (i->getInstruction()->getArg2() != nullptr && i->getInstruction()->getArg2()->getType() == CFG_ARG_TYPE::VAR) {
arg2Value = i->getInstruction()->getArg2()->getValue();
i->getInstruction()->getArg2()->setValue(i->getInstruction()->getArg2()->getValue() + to_string(i->getInstruction()->getArg2()->getNumber()));
}
cout << i->getNumber() << " " << i->getInstruction()->dump() << endl;
if (i->getInstruction()->getResult() != nullptr && i->getInstruction()->getResult()->getType() == CFG_ARG_TYPE::VAR) {
i->getInstruction()->getResult()->setValue(resValue);
}
if (i->getInstruction()->getArg1() != nullptr && i->getInstruction()->getArg1()->getType() == CFG_ARG_TYPE::VAR) {
i->getInstruction()->getArg1()->setValue(arg1Value);
}
if (i->getInstruction()->getArg2() != nullptr && i->getInstruction()->getArg2()->getType() == CFG_ARG_TYPE::VAR) {
i->getInstruction()->getArg2()->setValue(arg2Value);
}
}
cout << endl;
}
void getLoopBody(SAPFOR::BasicBlock* loopHeader, const std::set<SAPFOR::BasicBlock*>& loopExits, std::vector<SAPFOR::BasicBlock*>& loopBody) {
std::set<SAPFOR::BasicBlock*> visited; std::set<SAPFOR::BasicBlock*> visited;
std::stack<SAPFOR::BasicBlock*> stack; std::stack<SAPFOR::BasicBlock*> stack;
stack.push(loopHeader); stack.push(loopHeader);
while (!stack.empty()) { while (!stack.empty())
{
auto block = stack.top(); auto block = stack.top();
stack.pop(); stack.pop();
if (visited.count(block)) continue; if (visited.count(block))
continue;
visited.insert(block); visited.insert(block);
for (auto succ : block->getNext()) { for (auto succ : block->getNext())
if (loopExits.count(succ)) continue; {
if (!visited.count(succ)) { if (loopExits.count(succ))
continue;
if (!visited.count(succ))
stack.push(succ); stack.push(succ);
}
} }
} }
@@ -125,127 +79,127 @@ void getLoopBody(SAPFOR::BasicBlock* loopHeader, const std::set<SAPFOR::BasicBlo
std::stack<SAPFOR::BasicBlock*> reverseStack; std::stack<SAPFOR::BasicBlock*> reverseStack;
reverseStack.push(loopHeader); reverseStack.push(loopHeader);
while (!reverseStack.empty()) { while (!reverseStack.empty())
{
auto block = reverseStack.top(); auto block = reverseStack.top();
reverseStack.pop(); reverseStack.pop();
if (backReachable.count(block)) continue; if (backReachable.count(block))
continue;
backReachable.insert(block); backReachable.insert(block);
for (auto pred : block->getPrev()) { for (auto pred : block->getPrev())
if (visited.count(pred) && !backReachable.count(pred)) { if (visited.count(pred) && !backReachable.count(pred))
reverseStack.push(pred); reverseStack.push(pred);
}
}
} }
for (auto block : visited) { for (auto block : visited)
if (backReachable.count(block)) { if (backReachable.count(block))
loopBody.push_back(block); loopBody.push_back(block);
}
}
} }
SAPFOR::Instruction* findDef(const SAPFOR::Argument* arg, SAPFOR::Instruction* findDef(const SAPFOR::Argument* arg,
const std::vector<SAPFOR::BasicBlock*>& blocks) { const std::vector<SAPFOR::BasicBlock*>& blocks)
if (!arg) return nullptr; {
if (!arg)
return nullptr;
std::string argName = arg->getValue(); std::string argName = arg->getValue();
for (auto block : blocks) { for (auto block : blocks) {
for (auto instrWrapper : block->getInstructions()) { for (auto instrWrapper : block->getInstructions()) {
auto instr = instrWrapper->getInstruction(); auto instr = instrWrapper->getInstruction();
if (!instr) continue; if (!instr)
continue;
auto res = instr->getResult(); auto res = instr->getResult();
if (!res) continue; if (!res)
continue;
if (res->getValue() == argName) { if (res->getValue() == argName)
return instr; return instr;
}
} }
} }
return nullptr; return nullptr;
} }
const SAPFOR::Argument* getBaseSource(const SAPFOR::Argument* arg, const std::vector<SAPFOR::BasicBlock*>& blocks) { const SAPFOR::Argument* getBaseSource(const SAPFOR::Argument* arg, const std::vector<SAPFOR::BasicBlock*>& blocks)
while (arg && arg->getType() == CFG_ARG_TYPE::REG) { {
while (arg && arg->getType() == CFG_ARG_TYPE::REG)
{
auto defInstr = findDef(arg, blocks); auto defInstr = findDef(arg, blocks);
if (!defInstr) break; if (!defInstr)
break;
auto defOp = defInstr->getOperation(); auto defOp = defInstr->getOperation();
if (defOp == CFG_OP::ASSIGN) { if (defOp == CFG_OP::ASSIGN)
arg = defInstr->getArg1(); arg = defInstr->getArg1();
} else
else {
break; break;
}
} }
return arg; return arg;
} }
void findInductiveVars(const std::vector<SAPFOR::BasicBlock*>& Loopblocks, const std::vector<SAPFOR::BasicBlock*>& blocks) { void findInductiveVars(const std::vector<SAPFOR::BasicBlock*>& Loopblocks, const std::vector<SAPFOR::BasicBlock*>& blocks)
{
std::set<std::string> inductiveVars; std::set<std::string> inductiveVars;
for (auto block : Loopblocks) { for (auto block : Loopblocks)
for (auto instrWrapper : block->getInstructions()) { {
for (auto instrWrapper : block->getInstructions())
{
auto instr = instrWrapper->getInstruction(); auto instr = instrWrapper->getInstruction();
if (!instr) continue; if (!instr)
continue;
auto res = instr->getResult(); auto res = instr->getResult();
if (!res || res->getType() != SAPFOR::CFG_ARG_TYPE::VAR) continue; if (!res || res->getType() != SAPFOR::CFG_ARG_TYPE::VAR)
continue;
while (instr && instr->getOperation() == CFG_OP::ASSIGN) { while (instr && instr->getOperation() == CFG_OP::ASSIGN)
instr = findDef(instr->getArg1(), blocks); instr = findDef(instr->getArg1(), blocks);
}
if (!instr || instr->getOperation() != CFG_OP::ADD && instr->getOperation() != CFG_OP::SUBT) continue; if (!instr || instr->getOperation() != CFG_OP::ADD && instr->getOperation() != CFG_OP::SUBT)
continue;
auto arg1 = getBaseSource(instr->getArg1(), blocks); auto arg1 = getBaseSource(instr->getArg1(), blocks);
auto arg2 = getBaseSource(instr->getArg2(), blocks); auto arg2 = getBaseSource(instr->getArg2(), blocks);
bool ok = false; bool ok = false;
if (res->getValue() == arg1->getValue() && if (res->getValue() == arg1->getValue() && arg2->getType() == CFG_ARG_TYPE::CONST)
arg2->getType() == CFG_ARG_TYPE::CONST) {
ok = true; ok = true;
} else if (res->getValue() == arg2->getValue() && arg1->getType() == CFG_ARG_TYPE::CONST)
else if (res->getValue() == arg2->getValue() &&
arg1->getType() == CFG_ARG_TYPE::CONST) {
ok = true; ok = true;
}
if (ok) { if (ok)
inductiveVars.insert(res->getValue()); inductiveVars.insert(res->getValue());
}
} }
} }
if (inductiveVars.empty()) { if (inductiveVars.empty())
std::cout << "No inductive variables found." << std::endl; std::cout << "No inductive variables found." << std::endl;
} else
else { for (const auto& var : inductiveVars)
for (const auto& var : inductiveVars) {
std::cout << "Inductive variable: " << var << std::endl; std::cout << "Inductive variable: " << var << std::endl;
}
}
} }
Instruction* findInstructionAfterLoop(const std::vector<SAPFOR::BasicBlock*>& loopBody) { Instruction* findInstructionAfterLoop(const std::vector<SAPFOR::BasicBlock*>& loopBody)
{
std::set<SAPFOR::BasicBlock*> loopSet(loopBody.begin(), loopBody.end()); std::set<SAPFOR::BasicBlock*> loopSet(loopBody.begin(), loopBody.end());
for (auto block : loopBody) { for (auto block : loopBody)
for (auto succ : block->getNext()) { {
if (!loopSet.count(succ)) { for (auto succ : block->getNext())
// Нашли выход из цикла — возьмём первую инструкцию {
if (!loopSet.count(succ))
{
auto instructions = succ->getInstructions(); auto instructions = succ->getInstructions();
if (instructions.empty()) { if (instructions.empty())
std::cout << "Exit block has no instructions." << std::endl; std::cout << "Exit block has no instructions." << std::endl;
}
for (auto wrapper : instructions) { for (auto wrapper : instructions)
if (auto instr = wrapper->getInstruction()) { if (auto instr = wrapper->getInstruction())
return instr; return instr;
}
}
} }
} }
} }
@@ -253,118 +207,75 @@ Instruction* findInstructionAfterLoop(const std::vector<SAPFOR::BasicBlock*>& lo
return nullptr; return nullptr;
} }
bool isEqual(const char* cstr, const std::string& str) { void findImplicitLoops(const std::vector<SAPFOR::BasicBlock*>& irSSA, const std::vector<LoopGraph*> loopGraph)
return str == cstr; {
} map<int, int> visited;
for (auto i : irSSA)
visited[i->getNumber()] = UNVISITED;
void findImplicitLoops(const std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& fullIR_SSA, const char* fileName) { vector<pair<SAPFOR::BasicBlock*, SAPFOR::BasicBlock*>> startAndEnd;
for (auto& i : fullIR_SSA) dfs(irSSA[0], visited, startAndEnd, NULL);
vector<LoopGraph*> loops;
for (auto& [tail, header] : startAndEnd)
{ {
//for (auto j : i.second) set<SAPFOR::BasicBlock*> loopExits;
// printblock(j);
if (!isEqual(fileName, i.first->fileName)) for (auto succ : tail->getNext())
if (succ != header)
loopExits.insert(succ);
vector<SAPFOR::BasicBlock*> loopBody;
getLoopBody(header, loopExits, loopBody);
findInductiveVars(loopBody, irSSA);
Instruction* instructionAfterLoop = findInstructionAfterLoop(loopBody);
if (instructionAfterLoop == NULL)
{
cout << "Warning: instruction after loop not found!" << endl;
continue; continue;
if (isEqual("csol.for", i.first->fileName) || isEqual("reblns.for", i.first->fileName) || isEqual("adjont.for", i.first->fileName)
|| isEqual("beginf.for", i.first->fileName) || isEqual("dsnp1.for", i.first->fileName) || isEqual("dsnpnm.for", i.first->fileName)
|| isEqual("decod3.for", i.first->fileName))
continue;
//if (!isEqual("iter3.for", i.first->fileName))
// continue;
map<int, int> visited;
for (auto i : i.second)
visited[i->getNumber()] = UNVISITED;
//for (auto j : i.second)
// printBlock(j);
//continue;
//vector<int> visited(i.second.size(), UNVISITED);
vector<pair<SAPFOR::BasicBlock*, SAPFOR::BasicBlock*>> startAndEnd;
dfs(i.second[0], visited, startAndEnd, NULL);
//continue;
vector<LoopGraph*> loops;
for (auto& [tail, header] : startAndEnd) {
set<SAPFOR::BasicBlock*> loopExits;
for (auto succ : tail->getNext()) {
if (succ != header) {
loopExits.insert(succ);
}
}
vector<SAPFOR::BasicBlock*> loopBody;
getLoopBody(header, loopExits, loopBody);
//cout << "LOOP DETECTED:" << endl;
//cout << " Header: " << header->getNumber() << endl;
//cout << " Tail: " << tail->getNumber() << endl;
//cout << " Body blocks: ";
//for (auto block : loopBody) {
// cout << block->getNumber() << " ";
//}
//cout << endl;
findInductiveVars(loopBody, i.second);
continue;
Instruction* instructionAfterLoop = findInstructionAfterLoop(loopBody);
if (instructionAfterLoop == NULL) {
cout << "Warning: instruction after loop not found!" << endl;
cout << i.first->fileName << endl;
continue;
}
auto firstInstruction = header->getInstructions()[0]->getInstruction();
auto lastInstruction = tail->getInstructions().back()->getInstruction();
//cout << "first - " << firstInstruction->getNumber() << " last - " << lastInstruction->getNumber() << " after - " << instructionAfterLoop->getNumber() << endl;
//auto x = firstInstruction->getOperator();
auto tmpLoop = new LoopGraph();
tmpLoop->isFor = true;
tmpLoop->lineNum = firstInstruction->getOperator()->lineNumber();
tmpLoop->lineNumAfterLoop = instructionAfterLoop->getOperator()->lineNumber();
//continue;
if (firstInstruction->getOperator()->variant() == FOR_NODE) {
SgForStmt* stmt = isSgForStmt(firstInstruction->getOperator());
cout << "for loop" << endl;// << stmt->sunparse() << endl;
}
else if (firstInstruction->getOperator()->variant() == WHILE_NODE) {
SgWhileStmt* stmt = isSgWhileStmt(firstInstruction->getOperator());
cout << (stmt->conditional() == NULL ? "infinit" : "") << "while loop" << endl;//<< stmt->sunparse() << endl;
}
else if (firstInstruction->getOperator()->variant() == DO_WHILE_NODE) {
SgWhileStmt* stmt = isSgDoWhileStmt(firstInstruction->getOperator());
cout << "do while loop" << endl;// << stmt->sunparse() << endl;
}
else if (firstInstruction->getOperator()->variant() == LOOP_NODE) {
cout << "not known loop" << endl;// << firstInstruction->getOperator()->sunparse() << endl;
}
else {
cout << "goto loop" << endl;// firstInstruction->getOperator()->sunparse() << endl;
}
cout << "loop start line " << tmpLoop->lineNum << endl;
cout << "after loop line " << tmpLoop->lineNumAfterLoop << endl << endl;
loops.push_back(tmpLoop);
} }
auto firstInstruction = header->getInstructions()[0]->getInstruction();
auto lastInstruction = tail->getInstructions().back()->getInstruction();
auto tmpLoop = new LoopGraph();
tmpLoop->lineNum = firstInstruction->getOperator()->lineNumber();
tmpLoop->lineNumAfterLoop = instructionAfterLoop->getOperator()->lineNumber();
if (firstInstruction->getOperator()->variant() == FOR_NODE)
{
SgForStmt* stmt = isSgForStmt(firstInstruction->getOperator());
cout << "for loop" << endl;
}
else if (firstInstruction->getOperator()->variant() == WHILE_NODE)
{
SgWhileStmt* stmt = isSgWhileStmt(firstInstruction->getOperator());
cout << (stmt->conditional() == NULL ? "infinit" : "") << "while loop" << endl;
}
else if (firstInstruction->getOperator()->variant() == DO_WHILE_NODE)
{
SgWhileStmt* stmt = isSgDoWhileStmt(firstInstruction->getOperator());
cout << "do while loop" << endl;
}
else if (firstInstruction->getOperator()->variant() == LOOP_NODE)
{
cout << "not known loop" << endl;
}
else
{
cout << "goto loop" << endl;
}
cout << "loop start line " << tmpLoop->lineNum << endl;
cout << "after loop line " << tmpLoop->lineNumAfterLoop << endl << endl;
loops.push_back(tmpLoop);
} }
} }

View File

@@ -4,4 +4,4 @@
#include "../CFGraph/CFGraph.h" #include "../CFGraph/CFGraph.h"
#include "../GraphCall/graph_calls.h" #include "../GraphCall/graph_calls.h"
void findImplicitLoops(const std::map<FuncInfo*, std::vector<SAPFOR::BasicBlock*>>& fullIR_SSA, const char* fileName); void findImplicitLoops(const std::vector<SAPFOR::BasicBlock*>& fullIR_SSA, const std::vector<LoopGraph*> loopGraph);

View File

@@ -2199,7 +2199,7 @@ void loopAnalyzer(SgFile *file, vector<ParallelRegion*> &regions, map<tuple<int,
LoopGraph *tmpLoop = new LoopGraph(); LoopGraph *tmpLoop = new LoopGraph();
tmpLoop->region = reg; tmpLoop->region = reg;
tmpLoop->isFor = true; tmpLoop->loopType = LoopType::FOR;
tmpLoops.push_back(tmpLoop); tmpLoops.push_back(tmpLoop);

View File

@@ -51,7 +51,7 @@ pair<SAPFOR::BasicBlock*, unordered_set<SAPFOR::BasicBlock*>> GetBasicBlocksForL
} }
static void BuildLoopIndex(map<string, LoopGraph*>& loopForIndex, LoopGraph* loop) { static void BuildLoopIndex(map<string, LoopGraph*>& loopForIndex, LoopGraph* loop) {
string index = loop->loopSymbol; string index = loop->loopSymbol();
loopForIndex[index] = loop; loopForIndex[index] = loop;
for (const auto& childLoop : loop->children) for (const auto& childLoop : loop->children)

View File

@@ -1023,11 +1023,15 @@ static bool runAnalysis(SgProject &project, const int curr_regime, const bool ne
} }
else if (curr_regime == BUILD_IR_SSA_FORM) else if (curr_regime == BUILD_IR_SSA_FORM)
{ {
if (fullIR_SSA.size() == 0) auto irFound = getIRByFilename(fullIR, file_name);
buildIRSSAForm(fullIR, fullIR_SSA); buildFuncIRSSAForm(irFound, fullIR[irFound], fullIR_SSA);
} }
else if (curr_regime == FIND_IMPLICIT_LOOPS) else if (curr_regime == FIND_IMPLICIT_LOOPS)
findImplicitLoops(fullIR_SSA, file_name); {
auto itFound = loopGraph.find(file_name);
auto irFound = getIRByFilename(fullIR_SSA, file_name);
findImplicitLoops(fullIR_SSA[irFound], itFound->second);
}
else if (curr_regime == FIND_PRIVATE_ARRAYS) else if (curr_regime == FIND_PRIVATE_ARRAYS)
findPrivateArrays(loopGraph, fullIR); findPrivateArrays(loopGraph, fullIR);
else if (curr_regime == TEST_PASS) else if (curr_regime == TEST_PASS)

View File

@@ -20,7 +20,7 @@ using std::wstring;
static SgSymbol* getLoopSymbol(const LoopGraph* loop) static SgSymbol* getLoopSymbol(const LoopGraph* loop)
{ {
if (!loop || !loop->isFor) if (!loop || !loop->isFor())
return NULL; return NULL;
SgForStmt* stmt = (SgForStmt*)loop->loop->GetOriginal(); SgForStmt* stmt = (SgForStmt*)loop->loop->GetOriginal();
@@ -667,12 +667,12 @@ static void renameIterationVariables(LoopGraph* loop, const map<SgSymbol*, SgSym
{ {
if (loop) if (loop)
{ {
string& loopName = loop->loopSymbol; const string& loopName = loop->loopSymbol();
for (auto& pair : symbols) for (auto& [from, to] : symbols)
{ {
if (pair.first->identifier() == loopName) if (from->identifier() == loopName)
{ {
loop->loopSymbol = (string)pair.second->identifier(); loop->loopSymbols.replaceMainVar(to->identifier());
break; break;
} }
} }
@@ -691,9 +691,9 @@ static void renameVariablesInLoop(LoopGraph* loop, const map<SgSymbol*, SgSymbol
if (st->variant() == FOR_NODE) if (st->variant() == FOR_NODE)
{ {
SgForStmt* for_st = (SgForStmt*)st; SgForStmt* for_st = (SgForStmt*)st;
for (auto& pair : symbols) for (auto& [from, to] : symbols)
if (isEqSymbols(pair.first, for_st->symbol())) if (isEqSymbols(from, for_st->symbol()))
for_st->setDoName(*pair.second); for_st->setDoName(*to);
} }
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
@@ -710,12 +710,12 @@ static void renamePrivatesInMap(LoopGraph* loop, const map<SgSymbol*, SgSymbol*>
for (auto& priv : privates->second) for (auto& priv : privates->second)
{ {
bool found = false; bool found = false;
for (auto& pair : symbols) for (auto& [from, to] : symbols)
{ {
if (isEqSymbols(priv, pair.first)) if (isEqSymbols(priv, from))
{ {
found = true; found = true;
newList.insert(pair.second); newList.insert(to);
break; break;
} }
} }
@@ -1590,7 +1590,7 @@ static bool combine(LoopGraph* firstLoop, const vector<LoopGraph*>& nextLoops, s
bool wasCombine = false; bool wasCombine = false;
for (LoopGraph* loop : nextLoops) for (LoopGraph* loop : nextLoops)
{ {
if (!loop->isFor) if (!loop->isFor())
return wasCombine; return wasCombine;
int perfectLoop = std::min(firstLoop->perfectLoop, loop->perfectLoop); int perfectLoop = std::min(firstLoop->perfectLoop, loop->perfectLoop);
@@ -1723,7 +1723,7 @@ static bool tryToCombine(vector<LoopGraph*>& loopGraphs, map<LoopGraph*, set<SgS
{ {
LoopGraph* loop = loops[z]; LoopGraph* loop = loops[z];
newloopGraphs.push_back(loop); newloopGraphs.push_back(loop);
if (!loop->isFor) if (!loop->isFor())
continue; continue;
vector<LoopGraph*> nextLoops = getNextLoops(loop, loopGraphs, -1); vector<LoopGraph*> nextLoops = getNextLoops(loop, loopGraphs, -1);

View File

@@ -1035,7 +1035,7 @@ int splitLoops(SgFile *file, vector<LoopGraph*> &loopGraphs, vector<Messages> &m
for (auto &loopPair : mapLoopGraph) for (auto &loopPair : mapLoopGraph)
{ {
if (!loopPair.second->isFor) if (!loopPair.second->isFor())
continue; continue;
LoopGraph *loop = loopPair.second; LoopGraph *loop = loopPair.second;

View File

@@ -2257,7 +2257,7 @@ void removePrivatesAnalysis(string filename,
{ {
for (LoopGraph* loop : loopGraphs) for (LoopGraph* loop : loopGraphs)
{ {
if (!loop->isFor) if (!loop->isFor())
continue; continue;
SgForStmt* loopStmt = (SgForStmt*)loop->loop->GetOriginal(); SgForStmt* loopStmt = (SgForStmt*)loop->loop->GetOriginal();

View File

@@ -74,7 +74,7 @@ static void fillIterationVariables(const LoopGraph* loop, set<string>& vars, int
{ {
if (dimensions == -1) if (dimensions == -1)
{ {
vars.insert(loop->loopSymbol); vars.insert(loop->loopSymbol());
for (LoopGraph* child : loop->children) for (LoopGraph* child : loop->children)
fillIterationVariables(child, vars); fillIterationVariables(child, vars);
} }
@@ -82,7 +82,7 @@ static void fillIterationVariables(const LoopGraph* loop, set<string>& vars, int
{ {
for (int i = 0; i < dimensions; ++i) for (int i = 0; i < dimensions; ++i)
{ {
vars.insert(loop->loopSymbol); vars.insert(loop->loopSymbol());
if (i != dimensions - 1) if (i != dimensions - 1)
loop = loop->children[0]; loop = loop->children[0];
} }

View File

@@ -1,3 +1,3 @@
#pragma once #pragma once
#define VERSION_SPF "2430" #define VERSION_SPF "2432"