This commit is contained in:
2025-03-12 12:37:19 +03:00
parent 1c851baa7e
commit 6a4040be3e
426 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
#pragma once
#if !__SPC
#include "dvm.h"
template<typename T>
class Base
{
void *orig;
public:
explicit Base(T init) { orig = init; }
T GetOriginal() const { return (T)orig; }
};
class Statement : public SgStatement, public Base<SgStatement*>
{
private:
std::string includedToFile;
public:
explicit Statement(SgStatement* init) : SgStatement(*init), Base(init) { includedToFile = current_file->filename(); }
const std::string& GetFileNameIncludedTo() const { return includedToFile; }
};
class Expression : public SgExpression, public Base<SgExpression*>
{
public:
explicit Expression(SgExpression *init) : SgExpression(*init), Base(init) { }
};
class File : public SgFile, public Base<SgFile*>
{
public:
explicit File(SgFile *init) : SgFile(*init), Base(init) { }
};
class ArrayRefExp : public SgArrayRefExp, public Base<SgArrayRefExp*>
{
public:
explicit ArrayRefExp(SgArrayRefExp *init) : SgArrayRefExp(*init), Base(init) { }
};
class Symbol : public SgSymbol, public Base<SgSymbol*>
{
public:
explicit Symbol(SgSymbol *init) : SgSymbol(*init), Base(init) { }
};
#else
#define DVM_DISTRIBUTE_DIR 277
#define DVM_REDISTRIBUTE_DIR 299
#define DVM_ALIGN_DIR 219
#define DVM_REALIGN_DIR 220
#define DVM_SHADOW_DIR 224
#define DVM_VAR_DECL 248
#define SPF_PARALLEL_DIR 951
class ArrayRefExp;
class Expression;
class File;
class Statement;
class Symbol;
#endif

View File

@@ -0,0 +1,67 @@
#include <string>
#define printInternalError(file, line)
#define allocAndPrint(buf, format, ...) do { \
const int bufLen = 32 * 1024 * 1024;\
buf = new char[bufLen];\
const int countW = sprintf(buf, format, ##__VA_ARGS__);\
if (countW + 1 > bufLen) \
{ \
delete []buf; \
printInternalError(__FILE__, __LINE__);\
} \
} while (0)
#define __spf_print(needPrint, format, ...) do {\
if (needPrint == 1) {\
char *buf = NULL; \
allocAndPrint(buf, format, ##__VA_ARGS__); \
addToGlobalBufferAndPrint(buf);\
delete []buf;\
} \
} while (0)
extern void addToGlobalBufferAndPrint(const std::string&);
extern std::string convertFileName(const char *file);
#if _WIN32 && NDEBUG
//#define BOOST_STACKTRACE_USE_WINDBG
//#include <boost/stacktrace.hpp>
void printStackTrace()
{
/*__spf_print(1, "printStack\n");
auto stack = boost::stacktrace::stacktrace().as_vector();
for (auto &elem : stack)
{
const std::string fname = elem.name();
const std::string file = elem.source_file();
const int line = (int)elem.source_line();
if (line)
__spf_print(1, "%s %s : %d\n", fname.c_str(), convertFileName(file.c_str()).c_str(), line);
}*/
}
#undef BOOST_STACKTRACE_USE_WINDBG
#else
void printStackTrace() { }
#endif
//this function is here due to problem with compilation
#include "statlist.h"
std::string openDvmStatistic(const char* path, bool& isOk)
{
CStat stat;
stat.init(path);
isOk = true;
if (!stat.isinitialized)
{
isOk = false;
return "";
}
json j;
stat.to_json(j);
return j.dump();
}

View File

@@ -0,0 +1,120 @@
#pragma once
enum varType { SCALAR, ARRAY, CONST, ANOTHER };
struct CommonVariableUse
{
private:
std::string fileName;
std::string functionName;
SgSymbol *useS;
SgFile *file;
SgStatement *function;
bool isBlockData;
public:
explicit CommonVariableUse(SgFile *file, SgStatement *function, SgSymbol *useS) :
file(file), function(function), useS(useS),
fileName(std::string(file->filename())), functionName(std::string(function->symbol()->identifier()))
{
if (function->variant() == BLOCK_DATA)
isBlockData = true;
else
isBlockData = false;
}
const std::string& getFileName() const { return fileName; }
const std::string& getFunctionName() const { return functionName; }
bool isBlockDataUse() const { return isBlockData; }
SgFile* getFile() const { return file; }
SgStatement* getFunction() const { return function; }
SgSymbol* getUseS() const { return useS; }
SgStatement* getDeclaratedPlace() const
{
if (current_file->filename() != fileName)
SgFile::switchToFile(fileName);
return useS->declaredInStmt();
}
};
struct Variable
{
private:
std::vector<CommonVariableUse> allUse;
SgSymbol *symbol; // variable symbol
SgStatement *declPace;
std::string name; // variable name
varType type; // variable type
int position;
public:
explicit Variable(SgFile* file, SgStatement* function, SgSymbol* symbol, const std::string& name, const varType type, const int position);
SgSymbol* getSymbol() const { return symbol; }
const std::vector<CommonVariableUse>& getAllUse() const { return allUse; }
const std::string& getName() const { return name; }
varType getType() const { return type; }
int getPosition() const { return position; }
SgStatement *getDeclarated() const { return declPace; }
void addUse(SgFile *file, SgStatement *function, SgSymbol *useS)
{
for (auto &use : allUse)
if (use.getFile() == file && use.getFunction() == function)
return;
allUse.push_back(CommonVariableUse(file, function, useS));
}
bool hasUse(const std::string &file, const std::string &function) const
{
for (auto &use : allUse)
if (use.getFileName() == file && use.getFunctionName() == function)
return true;
return false;
}
void print(FILE *fileOut) const
{
fprintf(fileOut, " %3d, '%s', %s\n", position, name.c_str(), type == SCALAR ? "SCALAR" : type == ARRAY ? "ARRAY" : "ANOTHER");
}
};
struct CommonBlock
{
private:
std::string name;
std::vector<Variable*> variables;
// position -> variables
std::map<int, std::vector<Variable*>> groupedVars;
Variable* hasVariable(const std::string &name, const varType type, const int position);
Variable* hasVariable(SgSymbol *symbol, const varType type, const int position);
// copy and assignment not allowed
CommonBlock(const CommonBlock&) = delete;
void operator=(const CommonBlock&) = delete;
public:
explicit CommonBlock(const std::string &name) : name(name) { }
const std::string& getName() const { return name; }
const std::vector<Variable*>& getVariables() const { return variables; }
const std::map<int, std::vector<Variable*>>& getGroupedVars() const { return groupedVars; }
const std::vector<const Variable*> getVariables(SgFile *file, SgStatement *function) const;
const std::vector<const Variable*> getVariables(const std::string &file, const std::string &function) const;
const std::vector<const Variable*> getVariables(int position) const;
DIST::Array* getFirstSynonym(DIST::Array* array) const;
void addVariables(SgFile *file, SgStatement *function, const std::vector<std::pair<SgSymbol*, int>> &newVariables);
void print(FILE *fileOut) const;
~CommonBlock()
{
for (auto& elem : variables)
delete elem;
}
};

View File

@@ -0,0 +1,57 @@
#pragma once
struct DefUseList
{
private:
int type; // def(0) or use(1)
SgStatement *place;
SgExpression *expr;
SgFile *file;
std::pair<SgSymbol*, std::string> paramOfFunction;
int parameterPosition;
std::pair<SgSymbol*, std::string> varName;
int parameterPositionInFunction;
public:
explicit DefUseList(int type, SgStatement *place, SgExpression *expr, SgFile *file,
const std::pair<SgSymbol*, std::string> &inFuncParam,
const std::pair<SgSymbol*, std::string> &varName,
const int parameterPosition, const int paramenterPostionInFunction) :
type(type), place(place), expr(expr), file(file), paramOfFunction(inFuncParam), varName(varName),
parameterPosition(parameterPosition), parameterPositionInFunction(paramenterPostionInFunction)
{
}
bool isDef() const { return type == 0; }
bool isUse() const { return type == 1; }
std::string getVar() const { return varName.second; }
SgSymbol* getVarS() const { return varName.first; }
SgFile* getFile() const { return file; }
SgStatement* getPlace() const { return place; }
SgExpression* getExpr() const { return expr; }
std::string getParamOfFunction() const { return paramOfFunction.second; }
SgSymbol* getParamOfFunctionS() const { return paramOfFunction.first; }
int getParameterPosition() const { return parameterPosition; }
int getParameterPositionInFunction() const { return parameterPositionInFunction; }
void print(FILE *fileOut = NULL, const bool onlyPositiveLine = false) const
{
if (onlyPositiveLine && place->lineNumber() < 0)
return;
if (fileOut == NULL)
{
printf("%s: [file: %s, line: %d], '%s' ", (type == 0) ? "DEF" : "USE", file->filename(), place->lineNumber(), varName.second.c_str());
if (parameterPosition != -1)
printf(" under call of '%s' function on %d position of args (alt pos %d)", paramOfFunction.second.c_str(), parameterPosition, parameterPositionInFunction);
printf("\n");
}
else
{
fprintf(fileOut, "%s: [file: %s, line: %d], '%s' ", (type == 0) ? "DEF" : "USE", file->filename(), place->lineNumber(), varName.second.c_str());
if (parameterPosition != -1)
fprintf(fileOut, " under call of '%s' function on %d position of args (alt pos %d)", paramOfFunction.second.c_str(), parameterPosition, parameterPositionInFunction);
fprintf(fileOut, "\n");
}
}
};

View File

@@ -0,0 +1,340 @@
#pragma once
#include <map>
#include <set>
#include <vector>
#include "../Sapfor.h"
using std::vector;
using std::map;
using std::set;
#define list vector<Pass>
static map<passes, vector<passes>> *passDeps;
static map<passes, set<passes>> passRemovals;
class Pass
{
private:
passes name;
public:
const Pass& operator<=(const Pass &right) const
{
if ((*passDeps).find(right.name) == (*passDeps).end())
(*passDeps)[right.name] = vector<passes>();
(*passDeps)[right.name].push_back(this->name);
return right;
}
Pass& operator<=(Pass &right) const
{
if ((*passDeps).find(right.name) == (*passDeps).end())
(*passDeps)[right.name] = vector<passes>();
(*passDeps)[right.name].push_back(this->name);
return right;
}
const list& operator<=(const list &right_vec) const
{
for (int i = 0; i < right_vec.size(); ++i)
{
if ((*passDeps).find(right_vec[i].name) == (*passDeps).end())
(*passDeps)[right_vec[i].name] = vector<passes>();
(*passDeps)[right_vec[i].name].push_back(this->name);
}
return right_vec;
}
friend const Pass& operator<=(const list &left_vec, const Pass &right)
{
if ((*passDeps).find(right.name) == (*passDeps).end())
(*passDeps)[right.name] = vector<passes>();
for (int i = 0; i < left_vec.size(); ++i)
(*passDeps)[right.name].push_back(left_vec[i].name);
return right;
}
friend const list& operator<=(const list &left_vec, const list &right_vec)
{
for (int k = 0; k < right_vec.size(); ++k)
{
if ((*passDeps).find(right_vec[k].name) == (*passDeps).end())
(*passDeps)[right_vec[k].name] = vector<passes>();
for (int i = 0; i < left_vec.size(); ++i)
(*passDeps)[right_vec[k].name].push_back(left_vec[i].name);
}
return right_vec;
}
friend void operator-=(const list& left_vec, const list& right_vec)
{
/* erase each pass in right_vec from dependency tree for each pass in left_vec */
for(const auto& left : left_vec)
{
auto& eraseFrom = passRemovals[left.name];
for(const auto& right : right_vec)
eraseFrom.insert(right.name);
}
}
friend void operator-=(const list& left_vec, const Pass& right)
{
left_vec -= list({right});
}
void operator-=(const list& right_vec) const
{
list({ *this }) -= right_vec;
}
void operator-=(const Pass& right) const
{
list({ *this }) -= list({ right });
}
void applyRemovals()
{
map<passes, set<passes>> to_process, processed;
to_process[name] = {};
while (!to_process.empty())
{
map<passes, set<passes>> to_process_next;
for (const auto& pass : to_process)
{
auto processed_it = processed.find(pass.first);
auto& done_removals = processed_it != processed.end() ? processed_it->second : processed[pass.first];
set<passes> removals_to_do;
bool process_pass = false;
if (processed_it == processed.end())
{
removals_to_do = done_removals = pass.second;
process_pass = true;
}
else
{
const auto& needed_removals = pass.second;
set_difference(needed_removals.begin(), needed_removals.end(), done_removals.begin(), done_removals.end(),
inserter(removals_to_do, removals_to_do.begin()));
process_pass = needed_removals.size() != 0;
done_removals.insert(removals_to_do.begin(), removals_to_do.end());
}
if (process_pass)
{
processed[pass.first] = pass.second;
auto removals_it = passRemovals.find(pass.first);
if (removals_it != passRemovals.end())
{
auto& removals_saved = removals_it->second;
set<passes> add;
set_difference(removals_saved.begin(), removals_saved.end(), done_removals.begin(), done_removals.end(),
inserter(add, add.begin()));
done_removals.insert(add.begin(), add.end());
removals_to_do.insert(add.begin(), add.end());
}
auto deps_it = passDeps->find(pass.first);
if (deps_it != passDeps->end())
{
auto& deps = deps_it->second;
for (auto dep_it = deps.begin(); dep_it != deps.end();)
{
if (removals_to_do.find(*dep_it) == removals_to_do.end())
to_process_next[*(dep_it++)].insert(removals_to_do.begin(), removals_to_do.end());
else
dep_it = deps.erase(dep_it);
}
}
}
}
to_process = to_process_next;
}
}
Pass(passes name) : name(name) { }
};
static void depsToGraphViz(const map<passes, vector<passes>> &passDepsIn)
{
FILE *file = fopen("pass_tree.txt", "w");
if (!file)
printf("ERROR in creating 'pass_tree.txt' file\n");
else
{
fprintf(file, "digraph G {");
for (auto it = passDepsIn.begin(); it != passDepsIn.end(); ++it)
{
for (int k = 0; k < it->second.size(); ++k)
fprintf(file, "\"%s\" -> \"%s\";\n", passNames[it->first], passNames[it->second[k]]);
}
fprintf(file, "}\n");
fclose(file);
printf("write to 'pass_tree.txt' file complited\n");
}
}
void InitPassesDependencies(map<passes, vector<passes>> &passDepsIn, set<passes> &passesIgnoreStateDone, bool printTree = false)
{
passDepsIn.clear();
passDeps = &passDepsIn;
Pass(PREPROC_SPF) <= Pass(CREATE_INTER_TREE);
list({ CREATE_INTER_TREE, CORRECT_VAR_DECL }) <= list({ GCOV_PARSER, PREDICT_SCHEME, INSERT_INTER_TREE });
list({ FILE_LINE_INFO, BUILD_INCLUDE_DEPENDENCIES }) <= Pass(CORRECT_VAR_DECL);
Pass(DEF_USE_STAGE1) <= Pass(DEF_USE_STAGE2);
list({ VERIFY_DVM_DIRS, PRIVATE_CALL_GRAPH_STAGE1, PRIVATE_CALL_GRAPH_STAGE2, MACRO_EXPANSION, CONVERT_ASSIGN_TO_LOOP, DEF_USE_STAGE1, DEF_USE_STAGE2, FILL_PARALLEL_REG_IR, VERIFY_COMMON, FILL_COMMON_BLOCKS, CALL_GRAPH_IR }) <= list({ SUBST_EXPR, SUBST_EXPR_RD, BUILD_IR });
Pass(BUILD_IR) <= Pass(SUBST_EXPR) <= Pass(SUBST_EXPR_AND_UNPARSE);
Pass(BUILD_IR) <= Pass(SUBST_EXPR_RD) <= Pass(SUBST_EXPR_RD_AND_UNPARSE);
list({ LOOP_ANALYZER_DATA_DIST_S1, SUBST_EXPR_RD } ) <= Pass(PRIVATE_REMOVING_ANALYSIS);
list({ PRIVATE_REMOVING_ANALYSIS, REVERT_SUBST_EXPR_RD }) <= Pass(PRIVATE_REMOVING);
Pass(RESTORE_LOOP_FROM_ASSIGN) <= list({ SUBST_EXPR_AND_UNPARSE, SUBST_EXPR_RD_AND_UNPARSE });
Pass(GET_ALL_ARRAY_DECL) <= list({ CALL_GRAPH_IR, INSERT_NO_DISTR_FLAGS_FROM_GUI });
Pass(LOOP_GRAPH) <= Pass(PRIVATE_CALL_GRAPH_STAGE3) <= list(FIND_FUNC_TO_INCLUDE, PRIVATE_ANALYSIS_IR) <= list({ LOOP_ANALYZER_DATA_DIST_S0, LOOP_ANALYZER_DATA_DIST_S1, ONLY_ARRAY_GRAPH, LOOP_ANALYZER_ALIGNS });
Pass(PRIVATE_ANALYSIS_IR) <= Pass(LOOP_ANALYZER_NODIST);
Pass(CORRECT_VAR_DECL) <= list({ VERIFY_DVM_DIRS, VERIFY_OPERATORS, VERIFY_FORMAT, VERIFY_ENDDO, PREPROC_SPF, VERIFY_INCLUDES, PREPROC_ALLOCATES, CHECK_FUNC_TO_INCLUDE, FILL_PAR_REGIONS_LINES, CONVERT_ASSIGN_TO_LOOP, VERIFY_COMMON, VERIFY_EQUIVALENCE, PRINT_PAR_REGIONS_ERRORS }) <= Pass(CODE_CHECKER_PASSES);
list({ VERIFY_OPERATORS, VERIFY_ENDDO, VERIFY_INCLUDES, PREPROC_SPF, PREPROC_ALLOCATES, GET_ALL_ARRAY_DECL, GCOV_PARSER }) <= list({ CALL_GRAPH, MACRO_EXPANSION, DEF_USE_STAGE1 });
list({ VERIFY_OPERATORS, VERIFY_ENDDO, VERIFY_INCLUDES, PREPROC_ALLOCATES, FILL_PARALLEL_REG_IR }) <= list({ GET_ALL_ARRAY_DECL, FILL_COMMON_BLOCKS, PARSE_OMP_DIRS }) <= Pass(PREPROC_SPF);
Pass(CHECK_PAR_REG_DIR) <= Pass(FILL_PARALLEL_REG_IR);
list({ CODE_CHECKER_PASSES, GET_ALL_ARRAY_DECL, CALL_GRAPH2, SUBST_EXPR_RD, ARRAY_ACCESS_ANALYSIS_FOR_CORNER }) <= list({ LOOP_ANALYZER_NODIST, LOOP_ANALYZER_DATA_DIST_S0, LOOP_ANALYZER_DATA_DIST_S1, ONLY_ARRAY_GRAPH });
list({ LOOP_ANALYZER_NODIST, REMOVE_OMP_DIRS }) <= Pass(INSERT_PARALLEL_DIRS_NODIST);
Pass(CHECK_ARGS_DECL) <= Pass(CREATE_TEMPLATE_LINKS);
Pass(LOOP_ANALYZER_DATA_DIST_S0) <= Pass(LOOP_ANALYZER_DATA_DIST_S1) <= Pass(LOOP_ANALYZER_DATA_DIST_S2) <= Pass(CREATE_TEMPLATE_LINKS) <= Pass(LOOP_ANALYZER_COMP_DIST);
list({ VERIFY_OPERATORS, VERIFY_ENDDO, VERIFY_FORMAT, SUBST_EXPR_RD, CONVERT_ASSIGN_TO_LOOP }) <= Pass(LOOP_GRAPH) <= Pass(CALL_GRAPH) <= Pass(CALL_GRAPH2);
Pass(MACRO_EXPANSION) <= Pass(CALL_GRAPH);
list({ PREPROC_SPF, PROCESS_IO, CALL_GRAPH2, CONVERT_SAVE_TO_MODULE, REVERT_SUBST_EXPR_RD }) <= Pass(CREATE_CHECKPOINTS);
Pass(FILL_PAR_REGIONS_LINES) <= Pass(VERIFY_EQUIVALENCE);
Pass(LOOP_ANALYZER_DATA_DIST_S2) <= Pass(CREATE_NESTED_LOOPS);
list({ CORRECT_VAR_DECL, PREPROC_SPF }) <= list({ LOOP_GRAPH, CALL_GRAPH, CALL_GRAPH2 });
list({ PREPROC_SPF, CALL_GRAPH2 }) <= Pass(FILL_PAR_REGIONS_LINES) <= list({ EXPAND_EXTRACT_PAR_REGION, CHECK_FUNC_TO_INCLUDE, FIND_FUNC_TO_INCLUDE, CHECK_ARGS_DECL });
list({ PREPROC_SPF, CALL_GRAPH2, FILL_PAR_REGIONS_LINES }) <= Pass(FILL_PAR_REGIONS) <= Pass(RESOLVE_PAR_REGIONS);
list({ REVERT_SUBST_EXPR_RD, CONVERT_LOOP_TO_ASSIGN }) <= Pass(RESOLVE_PAR_REGIONS);
list({ REVERT_SUBST_EXPR_RD, CONVERT_LOOP_TO_ASSIGN, FILL_PAR_REGIONS}) <= Pass(REMOVE_DIST_ARRAYS_FROM_IO);
Pass(REVERT_SUBST_EXPR_RD) <= Pass(EXPAND_EXTRACT_PAR_REGION);
Pass(FILL_PAR_REGIONS) <= Pass(PRINT_PAR_REGIONS_ERRORS);
list({ PREPROC_SPF, CORRECT_VAR_DECL }) <= Pass(FILL_PAR_REGIONS_LINES);
list({ LOOP_ANALYZER_COMP_DIST, REMOVE_OMP_DIRS }) <= list({ CREATE_DISTR_DIRS, CREATE_PARALLEL_DIRS, INSERT_PARALLEL_DIRS });
Pass(CALL_GRAPH2) <= list({ ONLY_ARRAY_GRAPH, CREATE_NESTED_LOOPS, FIND_FUNC_TO_INCLUDE, CHECK_FUNC_TO_INCLUDE, FIND_PARAMETERS, GET_STATS_FOR_PREDICTOR });
Pass(CALL_GRAPH2) <= list({ PURE_SAVE_TO_PARAMS, PURE_MODULE_TO_PARAMS, PURE_COMMON_TO_PARAMS, PURE_INTENT_INSERT });
Pass(REVERT_SUBST_EXPR_RD) <= list({ PURE_SAVE_TO_PARAMS, PURE_MODULE_TO_PARAMS, PURE_COMMON_TO_PARAMS, PURE_INTENT_INSERT });
list({ CORRECT_VAR_DECL, REVERT_SUBST_EXPR_RD, VERIFY_INCLUDES }) <= list({ CONVERT_TO_ENDDO, CORRECT_CODE_STYLE, REMOVE_DVM_DIRS, REMOVE_DVM_DIRS_TO_COMMENTS, REMOVE_DVM_INTERVALS });
list({ CALL_GRAPH2, CONVERT_LOOP_TO_ASSIGN, REVERT_SUBST_EXPR_RD, RESTORE_LOOP_FROM_ASSIGN }) <= Pass(INLINE_PROCEDURES);
list({ CONVERT_LOOP_TO_ASSIGN, CORRECT_FORMAT_PLACE }) <= list({ CONVERT_TO_ENDDO, CORRECT_CODE_STYLE, INSERT_INCLUDES, REMOVE_DVM_DIRS, REMOVE_DVM_DIRS_TO_COMMENTS, REMOVE_DVM_INTERVALS });
list({ CORRECT_VAR_DECL, REVERT_SUBST_EXPR_RD }) <= list({ INSERT_INCLUDES, UNPARSE_FILE, SET_TO_ALL_DECL_INIT_ZERO });
Pass(CALL_GRAPH2) <= Pass(PRIVATE_ARRAYS_SHRINKING_ANALYSIS) <= Pass(PRIVATE_ARRAYS_SHRINKING);
list({ CALL_GRAPH2, LOOP_ANALYZER_ALIGNS, REVERT_SUBST_EXPR_RD }) <= list({ PRIVATE_ARRAYS_EXPANSION, PRIVATE_ARRAYS_SHRINKING });
list({ GCOV_PARSER, CREATE_INTER_TREE, CALL_GRAPH, CALL_GRAPH2 }) <= Pass(CREATE_PARALLEL_REGIONS);
list({ PRIVATE_CALL_GRAPH_STAGE1, PRIVATE_CALL_GRAPH_STAGE2, MACRO_EXPANSION, CONVERT_ASSIGN_TO_LOOP, DEF_USE_STAGE1, DEF_USE_STAGE2, LOOP_GRAPH, CALL_GRAPH, PRIVATE_ANALYSIS_IR, FIND_FUNC_TO_INCLUDE }) <= Pass(INSERT_REGIONS);
list({ LOOP_ANALYZER_DATA_DIST_S1, REVERT_SUBST_EXPR_RD }) <= list({ LOOPS_SPLITTER, LOOPS_COMBINER, UNROLL_LOOPS, INSERT_REGIONS });
list({ CALL_GRAPH2, REVERT_SUBST_EXPR_RD, CONVERT_LOOP_TO_ASSIGN, RESTORE_LOOP_FROM_ASSIGN }) <= list({ DUPLICATE_FUNCTIONS, REMOVE_UNUSED_FUNCTIONS });
list({ CONVERT_LOOP_TO_ASSIGN, RESTORE_LOOP_FROM_ASSIGN }) <= list({ LOOPS_SPLITTER, LOOPS_COMBINER, PRIVATE_ARRAYS_EXPANSION, PRIVATE_ARRAYS_SHRINKING, CREATE_PARALLEL_REGIONS, PURE_SAVE_TO_PARAMS, PURE_MODULE_TO_PARAMS, PURE_COMMON_TO_PARAMS, PURE_INTENT_INSERT, PRIVATE_REMOVING });
list({ GET_ALL_ARRAY_DECL, FILL_PARALLEL_REG_IR }) <= Pass(CONVERT_ASSIGN_TO_LOOP);
list({ CALL_GRAPH2, REVERT_SUBST_EXPR_RD }) <= Pass(RENAME_SYMBOLS);
list({ BUILD_IR, CALL_GRAPH }) <= Pass(LIVE_ANALYSIS_IR);
list({ BUILD_IR, LOOP_GRAPH, LIVE_ANALYSIS_IR }) <= Pass(PRIVATE_ANALYSIS_IR);
Pass(FILE_LINE_INFO) <= Pass(GET_MIN_MAX_BLOCK_DIST);
Pass(CALL_GRAPH2) <= Pass(FIX_COMMON_BLOCKS);
Pass(REMOVE_OMP_DIRS) <= Pass(REMOVE_OMP_DIRS_TRANSFORM);
list({ CALL_GRAPH2, REVERT_SUBST_EXPR_RD }) <= Pass(REMOVE_DEAD_CODE);
list({ REMOVE_DEAD_CODE, CONVERT_LOOP_TO_ASSIGN, RESTORE_LOOP_FROM_ASSIGN }) <= Pass(REMOVE_DEAD_CODE_AND_UNPARSE);
list({ VERIFY_INCLUDES, CORRECT_VAR_DECL }) <= Pass(SET_IMPLICIT_NONE);
passesIgnoreStateDone.insert({ CREATE_PARALLEL_DIRS, INSERT_PARALLEL_DIRS, INSERT_SHADOW_DIRS, EXTRACT_PARALLEL_DIRS,
EXTRACT_SHADOW_DIRS, CREATE_REMOTES, UNPARSE_FILE, REMOVE_AND_CALC_SHADOW,
REVERSE_CREATED_NESTED_LOOPS, PREDICT_SCHEME, CALCULATE_STATS_SCHEME, REVERT_SPF_DIRS, CLEAR_SPF_DIRS, TRANSFORM_SHADOW_IF_FULL,
RESTORE_LOOP_FROM_ASSIGN, RESTORE_LOOP_FROM_ASSIGN_BACK, INSERT_REGIONS, REMOVE_COPIES, RESTORE_COPIES, SHADOW_GROUPING,
SWAP_LOOPS, RESTORE_SWAP_LOOPS, TEST_PASS, GROUP_ACTUAL_AND_REMOTE, GROUP_ACTUAL_AND_REMOTE_RESTORE, ADD_TEMPL_TO_USE_ONLY });
//only for print
if (printTree)
{
list({ CREATE_PARALLEL_DIRS, PRIVATE_ANALYSIS_IR, CREATE_REMOTES, REVERT_SUBST_EXPR_RD, UNPARSE_FILE, EXTRACT_PARALLEL_DIRS }) <= Pass(INSERT_PARALLEL_DIRS);
depsToGraphViz(passDepsIn);
exit(0);
}
}
void removalsFromPassesDependencies(map<passes, vector<passes>>& passDepsIn, const int curr_regime)
{
passDeps = &passDepsIn;
list({ INSERT_PARALLEL_DIRS_NODIST, LOOP_ANALYZER_NODIST }) -= list({ FIND_FUNC_TO_INCLUDE, CHECK_FUNC_TO_INCLUDE });
Pass(passes(curr_regime)).applyRemovals();
}
#undef list

View File

@@ -0,0 +1,247 @@
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <limits.h>
#include "RationalNum.h"
using std::vector;
using std::ostream;
static inline void getFactors(int num, vector<int64_t>& factorSet)
{
if (num != 1)
factorSet.push_back(num);
for (int i = 2; i <= sqrt(static_cast<double>(num)); i++)
{
if (num % i == 0)
{
factorSet.push_back(i);
factorSet.push_back(num / i);
}
}
}
static inline void simplifyFun(int64_t& a, int64_t& b)
{
int64_t tempN = a;
int64_t tempD = b;
int64_t small, temp;
vector<int64_t> factorSet;
if (tempN == tempD)
{
a = 1;
b = 1;
return;
}
else if (tempN == -tempD)
{
a = -1;
b = 1;
return;
}
else if (tempN == 0)
{
b = 1;
return;
}
if (abs(tempN) < abs(tempD))
small = abs(tempN);
else
small = abs(tempD);
getFactors(small, factorSet);
for (int i = 0; i < factorSet.size(); i++)
{
temp = factorSet[i];
while (tempN % temp == 0 && tempD % temp == 0)
{
tempN /= temp;
tempD /= temp;
}
}
a = tempN;
b = tempD;
}
//friend functions definitions
RationalNum operator+(const RationalNum& left, const RationalNum& right)
{
RationalNum temp;
int64_t tempLD = left.getDenominator();
int64_t tempRD = right.getDenominator();
simplifyFun(tempLD, tempRD);
temp.setDenominator(left.getDenominator() * tempRD);
temp.setNumerator(left.getNumerator() * tempRD + right.getNumerator() * tempLD);
temp.simplify();
return temp;
}
RationalNum operator-(const RationalNum& left, const RationalNum& right) { return left + (-right); }
RationalNum operator*(const RationalNum& left, const RationalNum& right)
{
RationalNum temp;
RationalNum temp_2(right.getNumerator(), left.getDenominator());
RationalNum temp_3(left.getNumerator(), right.getDenominator());
auto a = temp_2.getDenominator();
auto b = temp_2.getNumerator();
auto c = temp_3.getDenominator();
auto d = temp_3.getNumerator();
temp.setNumerator(b * d);
temp.setDenominator(a * c);
return temp;
}
RationalNum operator/(const RationalNum& left, const RationalNum& right)
{
RationalNum temp_1(left.getNumerator(), left.getDenominator());
RationalNum temp_2(right.getDenominator(), right.getNumerator());
return temp_1 * temp_2;
}
bool operator==(const RationalNum& left, const RationalNum& right)
{
return (left.numerator == right.numerator && left.denominator == right.denominator);
}
bool operator!=(const RationalNum& left, const RationalNum& right) { return !(left == right); }
bool operator<(const RationalNum& left, const RationalNum& right)
{
auto lside = left.getNumerator() * right.getDenominator();
auto rside = left.getDenominator() * right.getNumerator();
return (lside < rside);
}
bool operator>(const RationalNum& left, const RationalNum& right)
{
auto lside = left.getNumerator()*right.getDenominator();
auto rside = left.getDenominator()*right.getNumerator();
return (lside > rside);
}
bool operator<=(const RationalNum& left, const RationalNum& right) { return ((left < right) || (left == right)); }
bool operator>=(const RationalNum& left, const RationalNum& right) { return ((left > right) || (left == right)); }
ostream& operator<<(ostream& out, const RationalNum& obj)
{
out << obj.numerator;
if (obj.numerator != 0 && obj.denominator != 1)
out << "/" << obj.denominator;
return out;
}
//member function definition
RationalNum::RationalNum()
{
setNumerator(0);
setDenominator(1);
}
RationalNum::RationalNum(int64_t numerator_, int64_t denominator_)
{
setNumerator(numerator_);
setDenominator(denominator_);
simplify();
}
RationalNum& RationalNum::operator=(const RationalNum& obj)
{
setNumerator(obj.getNumerator());
setDenominator(obj.getDenominator());
return *this;
}
RationalNum& RationalNum::operator+=(const RationalNum& obj)
{
*this = *this + obj;
return *this;
}
RationalNum& RationalNum::operator-=(const RationalNum& obj)
{
*this = *this - obj;
return *this;
}
RationalNum& RationalNum::operator*=(const RationalNum& obj)
{
*this = *this*obj;
return *this;
}
RationalNum& RationalNum::operator/=(const RationalNum& obj)
{
*this = *this / obj;
return *this;
}
RationalNum& RationalNum::operator++()
{
*this = *this + 1;
return *this;
}
RationalNum RationalNum::operator++(int)
{
RationalNum before = *this;
*this = *this + 1;
return before;
}
RationalNum& RationalNum::operator--()
{
*this = *this - 1;
return *this;
}
RationalNum RationalNum::operator--(int)
{
RationalNum before = *this;
*this = *this - 1;
return before;
}
RationalNum RationalNum::operator+() const { return *this; }
RationalNum RationalNum::operator-() const
{
RationalNum temp;
temp.setNumerator(-getNumerator());
temp.setDenominator(getDenominator());
return temp;
}
void RationalNum::setNumerator(int64_t numerator_) { numerator = numerator_; }
int64_t RationalNum::getNumerator() const { return numerator; }
void RationalNum::setDenominator(int64_t denominator_)
{
if (denominator_ == 0)
{
denominator = 1;
numerator = 0;
std::cout << "Denominator is 0! Not good! THe whole is set to 0." << std::endl;
}
else
denominator = denominator_;
}
int64_t RationalNum::getDenominator() const { return denominator; }
void RationalNum::simplify()
{
int64_t tempN = numerator;
int64_t tempD = denominator;
simplifyFun(tempN, tempD);
setNumerator(tempN);
setDenominator(tempD);
}

View File

@@ -0,0 +1,44 @@
#pragma once
#include <iostream>
class RationalNum
{
friend RationalNum operator+(const RationalNum& left, const RationalNum& right);
friend RationalNum operator-(const RationalNum& left, const RationalNum& right);
friend RationalNum operator*(const RationalNum& left, const RationalNum& right);
friend RationalNum operator/(const RationalNum& left, const RationalNum& right);
friend bool operator==(const RationalNum& left, const RationalNum& right);
friend bool operator!=(const RationalNum& left, const RationalNum& right);
friend bool operator<(const RationalNum& left, const RationalNum& right);
friend bool operator>(const RationalNum& left, const RationalNum& right);
friend bool operator<=(const RationalNum& left, const RationalNum& right);
friend bool operator>=(const RationalNum& left, const RationalNum& right);
friend std::ostream& operator<<(std::ostream& out, const RationalNum& obj);
public:
RationalNum();
RationalNum(int64_t numerator_, int64_t denominator_ = 1);
RationalNum& operator=(const RationalNum& obj);
RationalNum& operator+=(const RationalNum& obj);
RationalNum& operator-=(const RationalNum& obj);
RationalNum& operator*=(const RationalNum& obj);
RationalNum& operator/=(const RationalNum& obj);
RationalNum& operator++();
RationalNum operator++(int);
RationalNum& operator--();
RationalNum operator--(int);
RationalNum operator+() const;
RationalNum operator-() const;
void setNumerator(int64_t numerator_);
int64_t getNumerator() const;
void setDenominator(int64_t denominator_);
int64_t getDenominator() const;
private:
int64_t numerator;
int64_t denominator;
void simplify();
};

File diff suppressed because it is too large Load Diff

122
Sapfor/_src/Utils/SgUtils.h Normal file
View File

@@ -0,0 +1,122 @@
#pragma once
#include "dvm.h"
#include "utils.h"
#include "../Distribution/Distribution.h"
#include "../GraphCall/graph_calls.h"
#include "../DynamicAnalysis/gcov_info.h"
#include "module_utils.h"
SgStatement* declaratedInStmt(SgSymbol *toFind, std::vector<SgStatement*> *allDecls = NULL, bool printInternal = true, SgStatement* scope = NULL);
#include "DefUseList.h"
#include "CommonBlock.h"
std::string removeIncludeStatsAndUnparse(SgFile *file, const char *fileName, const char *fout, std::set<std::string> &allIncludeFiles, bool outFree, const std::map<std::string, std::set<std::string>> &moduleUsesByFile, const std::map<std::string, std::string>& moduleDelcs, const std::map<SgStatement*, std::vector<SgStatement*>>& exctactedModuleStats, bool toString, bool renameIncludes, bool dontReplaceIncls);
SgSymbol* findSymbolOrCreate(SgFile *file, const std::string toFind, SgType *type = NULL, SgStatement *scope = NULL);
void recExpressionPrint(SgExpression *exp);
void removeSubstrFromStr(std::string &str, const std::string &del);
void tryToFindPrivateInAttributes(SgStatement* st, std::set<std::string>& privatesVars, bool onlyReduction = false, bool onlyUsers = false);
void fillNonDistrArraysAsPrivate(SgStatement *st,
const std::map<std::tuple<int, std::string, std::string>, std::pair<DIST::Array*, DIST::ArrayAccessInfo*>> &declaredArrays,
const std::map<SgStatement*, std::set<std::tuple<int, std::string, std::string>>> &declaratedArraysSt,
std::set<std::string> &privatesVars);
DIST::Array* getArrayFromDeclarated(SgStatement *st, const std::string &arrayName);
void initTags();
bool isDVM_stat(SgStatement *st);
bool isSPF_stat(SgStatement *st);
bool isEqExpressions(SgExpression *left, SgExpression *right, std::map<SgExpression*, std::string> &collection);
void getCommonBlocksRef(std::map<std::string, std::vector<SgExpression*>> &commonBlocks, SgStatement *start, SgStatement *end, const std::string *nameToSkip = NULL);
int checkCommonInMainUnit(SgProject& project, std::map<std::string, std::vector<Messages>>& SPF_messages, const std::set<DIST::Array*>& arrays, bool forDistrbuted);
std::tuple<int, std::string, std::string> getFromUniqTable(SgSymbol *symb);
std::tuple<int, std::string, std::string> getUniqName(const std::map<std::string, std::vector<SgExpression*>> &commonBlocks, SgStatement *decl, SgSymbol *symb);
SgStatement* findMainUnit(SgProject *proj, std::map<std::string, std::vector<Messages>>& SPF_messages);
template<typename IN_TYPE, typename OUT_TYPE>
const std::vector<OUT_TYPE> getAttributes(IN_TYPE st, const std::set<int> dataType);
template<typename IN_TYPE>
void deleteAttributes(IN_TYPE st, const std::set<int> dataType);
void constructDefUseStep1(SgFile *file, std::map<std::string, std::vector<DefUseList>> &defUseByFunctions, std::map<std::string, std::vector<FuncInfo*>> &allFuncInfo, std::vector<Messages> &messages);
void constructDefUseStep2(SgFile *file, std::map<std::string, std::vector<DefUseList>> &defUseByFunctions);
std::set<std::string> getAllDefVars(const std::string &funcName);
std::set<std::string> getAllUseVars(const std::string &funcName);
const std::vector<DefUseList>& getAllDefUseVarsList(const std::string &funcName);
const std::vector<DefUseList> getAllDefUseVarsList(const std::string &funcName, const std::string varName);
int printDefUseSets(const char *fileName, const std::map<std::string, std::vector<DefUseList>> &defUseLists);
int printCommonBlocks(const char *fileName, const std::map<std::string, CommonBlock*> &commonBlocks);
void groupDeclarations(SgFile *file);
bool ifSymbolExists(SgFile *file, const std::string &symbName);
int checkSymbNameAndCorrect(const std::string& symbName, int complite);
std::string checkSymbNameAndCorrect(const std::string& symbName, const std::string complite = "_");
const CommonBlock* isArrayInCommon(const std::map<std::string, CommonBlock*> &commonBlocks, const DIST::Array *array);
std::vector<DIST::Array*> fillArraysFromDir(Statement *st);
void printSymbolTable(SgFile* file, std::string filter = "", const std::set<int>& vars = {});
SgStatement* getFuncStat(SgStatement *st, const std::set<int> additional = std::set<int>());
std::map<SgStatement*, std::vector<DefUseList>> createDefUseMapByPlace();
SgStatement* duplicateProcedure(SgStatement* toDup, const std::string* newName, bool withAttributes = false, bool withComment = false, bool withSameLines = true, bool dontInsert = false);
SgExpression* makeExprList(const std::vector<SgExpression*>& items, bool withSort = true);
std::string unparseProjectToString(SgFile* file, const int curr_regime);
SgStatement* makeDeclaration(SgStatement* curr, const std::vector<SgSymbol*>& s, std::vector<SgExpression*>* inits = NULL);
std::vector<SgStatement*> makeDeclaration(const std::vector<SgSymbol*>& symbolsToDeclare, SgStatement* where, std::vector<SgExpression*>* inits = NULL);
int getNextFreeLabel();
void fillVisibleInUseVariables(SgStatement *useSt, std::map<std::string, SgSymbol*> &vars);
std::string preprocDataString(std::string data, bool full = true);
std::map<std::string, std::string> splitData(const std::set<SgValueExp*>& dataStats);
void extractComments(SgStatement* where, const std::string& what);
void getVariables(SgExpression* ex, std::set<std::string>& variables, const std::set<int> variants);
void getVariables(SgExpression* ex, std::set<SgSymbol*>& variables, const std::set<int> variants);
template<typename T>
std::set<T> getAllVariables(SgStatement* stFrom, SgStatement* stTo, const std::set<int>& variants);
SgProject* createProject(const char* proj_name, std::vector<ParallelRegion*>& parallelRegions,
std::vector<ParallelRegion*>& subs_parallelRegions,
std::map<std::string, std::vector<SgStatement*>>& hiddenData,
std::map<std::string, int>& filesNameWithoutExt,
std::map<std::string, std::set<std::string>>& moduleUsesByFile,
std::map<std::string, std::string>& moduleDecls,
std::map<std::string, std::map<SgStatement*, std::vector<SgStatement*>>>& exctactedModuleStats, bool printSymbTable);
bool isArrayType(SgType* type);
bool isArrayRef(SgExpression* ex);
bool isStringArrayType(SgType* type);
void moveLabelBefore(SgStatement* st, SgStatement* next = NULL);
bool isEqSymbols(SgSymbol* sym1, SgSymbol* sym2);
std::set<std::string> getAllFilesInProject();
void LogIftoIfThen(SgStatement* stmt);
void removeSpecialCommentsFromProject(SgFile* file);
void getMaxMinBlockDistribution(SgFile* file, std::pair<int, int>& min_max);
void addPrivatesToArraysFromGUI(SgFile* file, const std::map<std::tuple<int, std::string, std::string>, std::pair<DIST::Array*, DIST::ArrayAccessInfo*>>& declaredArrays, const std::map<std::string, int>& distrStateFromGUI);
void shiftLines(SgProject* project, bool print = true);
template<typename T>
static inline std::multimap<std::string, T> setToMapWithSortByStr(const std::set<T>& setIn)
{
std::multimap<std::string, T> retMap;
for (auto& elem : setIn)
retMap.insert(make_pair(elem->identifier(), elem));
return retMap;
}

631
Sapfor/_src/Utils/errors.h Normal file
View File

@@ -0,0 +1,631 @@
#pragma once
#include <string>
#ifdef __SPF
#include "dvm.h"
#endif
enum typeMessage { WARR, ERROR, NOTE };
//Гайд по русификации сообщений смотри ниже.
// GROUP:
// 10xx - analysis
// 20xx - transform
// 30xx - parallel
// 50xx - checkpoint
// 10xx ANALISYS GROUP
// 01 "bad directive position, it can be placed only"
// 02 "variable '%s' is not used in loop"
// 03 "variable '%s' is not changed in loop"
// 04 "dimention of array '%s' is %d, but must be 1"
// 05 "type of array '%s' but must be INTEGER"
// 06 "type of variable '%s' must be array"
// 07 "array size can't be computed"
// 08 "size of array '%s' is %d, but you enter %d"
// 09 "array '%s' is private"
// 10 "only positive numbers are supported"
// 11 "no such expression '%s' on loop"
// 12 "More information is required about sizes of array '%s'"
// 13 "Function '%s' needs to be inlined ..."
// 14 "Found recursive chain calls: %s, this function will be ignored"
// 15 "This function is not called in current project"
// 16 "Can not calculate count of iterations for this loop, information about iterations in all loops in parallel regions '%s' will be ignored"
// 17 "Can not find declaration for symbol '%s' in current scope"
// 18 "This loop does not have END DO format"
// 19 "Include '%s' has executable operators"
// 20 "Active DVM directives are not supported yet"
// 21 "array ref '%s' has more than one loop's variables"
// 22 "array ref '%s' has indirect access"
// 23 "can not calculate index expression for array ref '%s'"
// 24 "coefficient A in A*x+B is not positive for array ref '%s', inverse distribution in not supported yet"
// 25 "can not map write to array '%s' to this loop"
// 26 "write to non distributed array '%s' in this loop"
// 27 "many operator in the same line"
// 28 "Module with name '%s' must be placed in current file"
// 29 lowlevel warnings from private analyzer
// 30 lowlevel notes from private analyzer
// 31 "wrong parallel region identifier: variable '%s' was declared on line %d"
// 32 "wrong parallel region identifier: variable '%s' was declared in common block '%s'"
// 33 "parallel region '%s' is included in file '%s'"
// 34 "parallel regions '%s' and '%s' are crossed"
// 35 "parallel region '%s' has data statement(s)"
// 36 "Can not build align graph from user's DVM directives in this region"
// 37 "Array can not be distributed because of DVM's I/O constraints"
// 38 "An equivalence operator at line %d is not supported yet"
// 39 "Variabled '%s' and '%s' in one storage association (common block '%s') have different types"
// 40 "First %d dimensions of array '%s' were deprecated to distributon due to function call '%s'"
// 41 "parallel region '%s' has line included in another region"
// 42 "distributed array in common block %s must have declaration in main unit"
// 43 "bad directive expression"
// 44 "Only pure procedures were supported"
// 45 "function's argument '%s' does not have declaration statement"
// 46 "mismatch of count formal and actual parameters "
// 47 "inconsistent array use"
// 48 "the same function name in different places was found"
// 49 "reasons of non pure function"
// 50 "count of PROGRAM unit"
// 51 "Detected mpi call, turn on special regime of paralyzing"
// 52 "error in user DVM intervals"
// 53 "variable in shrink clause must be arrayy in file '%s' on line %d"
// 54 "length of mask for array '%s' must be %d, but you enter only %d dimenions in file '%s' on line %d"
// 55 "wrong mask value in %d position: it can be only 0 or 1 in file '%s' on line %d"
// 56 "array '%s' in shrink clause must be also declared in private clause in file '%s' on line %d"
// 57 "Variable '%s' in %s clause must be used in next statement in file '%s' on line %d.\n."
// 58 "Left part of PARAMETER clause must be a variable in file '%s' on line %d.\n"
// 59 "Reduction by element of array '%s' is not implemented yet"
// 60 "Format misplaced"
// 61 "Array has declaration area conflict"
// 62 "need to move common declaration to main for DECLATE"
//
// 20xx TRANSFORM GROUP
// 01 "can not convert array assign to loop"
// 02 "converted arithmetic IF to simple IF"
// 03 "can not convert to END DO loop"
// 04 "convert to END DO loop"
// 05 "loops on lines %d and %d were combined"
// 06 "substitute statement function with name '%s'"
// 07 "Internal error during unparsing process has occurred"
// 08 "Can not do PRIVATE EXPANSION for this loop - privates not found"
// 09 "Can not split this loop because of dependecy: %s"
// 10 "This loop has indirect child loops and can not be splitted"
// 11 "It is allowed to inline function only at execution code section"
// 12 "for function duplication"
// 13 "for function duplication"
// 14 inlining errors - dims mismatch
// 15 unrolling loop errors
// 16 "cannot remove private var '%s' - it doesn't match any fixed dimensions mask"
// 17 cannot remove private var '%s' - it has recursive dependency or it depends on non-invariant var '%s'
// 18 "private variable '%s' was removed" or "private variable '%s' was partially removed"
// 19 "Removing of private var '%s' was made with assumption that references '%s' and '%s' are different"
// 20 "Function inlining failed with an error"
// 21 "cannot remove private var '%s' - cannot find reaching definition for the statement"
// 22 "cannot transform ..."
// 23 "cannot transform ..."
// 24 "Cannot remove private var '%s' - its references have different alignment with the loop"
// 25 "Cannot remove private var '%s' - it is used in the call of function '%s'"
// 30xx PARALLEL GROUP
// 01 "add across dependencies by array '%s' to loop"
// 02 "add private scalar '%s' to loop on line %d"
// 03 "add reduction scalar '%s' with operation '%s' to loop on line %d"
// 04 "unknown type of reduction scalar '%s'"
// 05 "unknown scalar dependencies by '%s' (try to specify its type)"
// 06 "... prevents parallelization"
// 07 "Can not create distributed link for array '%s': dim size of this array is '%d' and it is not equal '%d'"
// 08 "internal error in analysis, parallel directives will not be generated for this file!"
// 09 "Added remote access for array ref '%s' can significantly reduce performance"
// 10 "Can not find arrays for distribution for parallel region '%s', ignored"
// 11 "Arrays have different align rules in this loop according to their write accesses"
// 12 "parallel regions %shave common function '%s' which is used inside them"
// 13 "parallel regions %shave local array '%s' which is used inside them"
// 14 "parallel region '%s' has common array '%s' which is used inside and outside region"
// 15 "parallel region '%s' does not have DVM interval for fragment"
// 16 "expected only assign operands in DVM interval"
// 17 "parallel region '%s' does not have copying of array '%s' in DVM interval"
// 18 "parallel region '%s' does not have copying of common array '%s' in DVM interval"
// 19 "Can not find execution time for this loop, try to get times statistic"
// 20 "detected distributed and non distributed array links by function's calls for array %s\n"
// 21 "empty parallel regions is forbidden"
// 22 "Can not find align rules"
// 23 "Array reference '%s' has a different size from the original array"
// 24 "Array's memory intersections prevents this loop from parallelization"
// 40xx LOW LEVEL WARNINGS
// 01
// 02 Wrong pure declaration - INTENT mismatch
// 50xx CHECKPOINT GROUP
// 01 "The first argument must be TIME or ITER and the second must be integer in INTERVAL clause."
// 02 "CHECKPOINT directive with %s clause can be only at executable code section."
// 03 "CHECKPOINT directive with FILES clause must contain integer value."
// 04 "Variable '%s' in %s clause must be declared at the same module."
// 05 "Illegal option in TYPE clause."
// 06 "%s clause can be used only once."
// 07 "Variable '%s' can't be used in FILES and EXCEPT clauses at the same time."
extern int langOfMessages;
struct Messages
{
private:
//explicit Messages(const typeMessage type, const int line, const std::string &value_) : Messages(type, line, value_, 0) { }
explicit Messages(const typeMessage type, const int line, const std::wstring &value_, const int group) : type(type), line(line), group(group)
{
value = value_;
//check for \n at the end
if (value[value.size() - 1] == '\n')
value.erase(value.begin() + value.size() - 1);
}
public:
explicit Messages(const typeMessage type, const int line, const std::wstring &rus, const std::wstring &eng, const int group) :
Messages(type, line, (langOfMessages == 1) ? rus : eng, group)
{
engMessage = eng;
if (engMessage[engMessage.size() - 1] == '\n')
engMessage.erase(engMessage.begin() + engMessage.size() - 1);
}
std::wstring toString() const
{
std::wstring retVal = L"|";
retVal += std::to_wstring((int)type) + L" ";
retVal += std::to_wstring(line) + L" ";
retVal += std::to_wstring(group);
retVal += L"|" + value;
return retVal;
}
std::string getString() const { return std::string(engMessage.begin(), engMessage.end()); }
public:
typeMessage type;
int group;
int line;
std::wstring value;
std::wstring engMessage;
};
// from Utils.cpp
#ifdef _WIN32
extern void printStackTrace();
#else
static void printStackTrace() { };
#endif
#if __SPC
#define printInternalError(file, line) do {\
char buf[512];\
sprintf(buf, "Internal error at line %d and file %s\n", line, file);\
addToGlobalBufferAndPrint(buf);\
throw(-1);\
} while (0)
#else
#define printInternalError(file, line) do {\
printStackTrace(); \
char buf[512];\
sprintf(buf, "Internal error at line %d and file %s\n", line, file);\
addToGlobalBufferAndPrint(buf);\
\
if (SgStatement::getCurrProcessFile() != "" && SgStatement::getCurrProcessLine() != -1)\
{ \
sprintf(buf, "Internal error in user code at line %d and file %s\n", SgStatement::getCurrProcessLine(), SgStatement::getCurrProcessFile().c_str());\
addToGlobalBufferAndPrint(buf);\
} \
throw(-1);\
} while (0)
#endif
#define checkNull(address, file, line) do { \
if ((address) == NULL) \
printInternalError(file, line); \
} while (0)
//TODO: count of string len of all parameters
#define allocAndPrint(buf, format, ...) do { \
const int bufLen = 32 * 1024 * 1024;\
buf = new char[bufLen];\
const int countW = sprintf(buf, format, ##__VA_ARGS__);\
if (countW + 1 > bufLen) \
{ \
delete []buf; \
printInternalError(__FILE__, __LINE__);\
} \
} while (0)
#ifdef _WIN32
#define allocAndPrintLong(buf, format, ...) do { \
const int bufLen = 32 * 1024 * 1024;\
buf = new wchar_t[bufLen];\
const int countW = swprintf(buf, format, ##__VA_ARGS__);\
if (countW + 1 > bufLen) \
{ \
delete []buf; \
printInternalError(__FILE__, __LINE__);\
} \
} while (0)
#else
#define allocAndPrintLong(buf, format, ...) do { \
const int bufLen = 32 * 1024 * 1024;\
buf = new wchar_t[bufLen];\
const int countW = swprintf(buf, bufLen, format, ##__VA_ARGS__);\
if (countW + 1 > bufLen) \
{ \
delete []buf; \
printInternalError(__FILE__, __LINE__);\
} \
} while (0)
#endif
#define __spf_printToBuf(outval, format, ...) do {\
char *buf = NULL; \
allocAndPrint(buf, format, ##__VA_ARGS__); \
outval = std::string(buf);\
delete []buf;\
} while (0)
#define __spf_printToLongBuf(outval, format, ...) do {\
wchar_t *buf = NULL; \
allocAndPrintLong(buf, fixedLongFormat(format).c_str(), ##__VA_ARGS__); \
outval = std::wstring(buf);\
delete []buf;\
} while (0)
#define __spf_print(needPrint, format, ...) do {\
if (needPrint == 1) {\
char *buf = NULL; \
allocAndPrint(buf, format, ##__VA_ARGS__); \
addToGlobalBufferAndPrint(buf);\
delete []buf;\
} \
} while (0)
// Свободный - R206
// Гайд по русификации сообщений: При добавлении нового сообщения, меняется последний сводобный идентификатор.
// В этом файле остаются только спецификаторы, для которых будет заполнен текст. Полный текст пишется в файле
// russian_errors_text.txt. Спецификаторы там тоже сохраняются, по ним в визуализаторе будет восстановлен
// закодированный текст.
//russian messages
//1001
static const wchar_t *R1 = L"R1:%ls#%ls#%ls";
static const wchar_t *RR1_1 = L"RR1_1:";
static const wchar_t *RR1_2 = L"RR1_2:";
static const wchar_t *RR1_3 = L"RR1_3:";
static const wchar_t *RR1_4 = L"RR1_4:";
static const wchar_t *RR1_5 = L"RR1_5:";
static const wchar_t *RR1_6 = L"RR1_6:";
static const wchar_t *RR1_7 = L"RR1_7:";
static const wchar_t *RR1_8 = L"RR1_8:";
static const wchar_t *R2 = L"R2:";
static const wchar_t *R3 = L"R3:";
static const wchar_t *R4 = L"R4:%s";
static const wchar_t *R5 = L"R5:%s";
static const wchar_t *R6 = L"R6:%s";
static const wchar_t *R7 = L"R7:";
static const wchar_t *R8 = L"R8:";
static const wchar_t *R9 = L"R9:";
static const wchar_t *R10 = L"R10:%s";
static const wchar_t *R11 = L"R11:%s";
static const wchar_t *R12 = L"R12:";
static const wchar_t *R13 = L"R13:";
static const wchar_t *R14 = L"R14:";
static const wchar_t *R15 = L"R15:";
static const wchar_t *R16 = L"R16:";
static const wchar_t *R17 = L"R17:";
static const wchar_t *R18 = L"R18:";
static const wchar_t *R19 = L"R19:%d#%d";
static const wchar_t *R20 = L"R20:";
//1002
static const wchar_t *R21 = L"R21:%s";
static const wchar_t *R22 = L"R22:%s";
//1003
static const wchar_t *R23 = L"R23:%s";
static const wchar_t *R24 = L"R24:%s";
//1004
static const wchar_t *R25 = L"R25:%s#%d";
//1005
static const wchar_t *R26 = L"R26:%s";
//1006
static const wchar_t *R27 = L"R27:%s";
static const wchar_t *R28 = L"R28:%s";
static const wchar_t *R29 = L"R29:%s";
//1007
static const wchar_t *R30 = L"R30:";
//1008
static const wchar_t *R31 = L"R31:%s#%d#%d";
static const wchar_t *R32 = L"R32:%s#%d#%d";
//1009
static const wchar_t *R33 = L"R33:%s";
static const wchar_t *R34 = L"R34:%s";
//1010
static const wchar_t *R35 = L"R35:";
//1011
static const wchar_t *R36 = L"R36:%s";
//1012
static const wchar_t *R37 = L"R37:%s";
static const wchar_t *R149 = L"R149:%s";
//1013
static const wchar_t *R38 = L"R38:%s";
static const wchar_t *R39 = L"R39:%s#%s#%s#%s#%d#%s";
static const wchar_t *R40 = L"R40:%s";
static const wchar_t *R41 = L"R41:%s#%s#%d#%s";
static const wchar_t *R42 = L"R42:%s#%s#%ls";
static const wchar_t *RR42_1 = L"RR42_1:";
static const wchar_t *RR42_2 = L"RR42_2:";
static const wchar_t *R43 = L"R43:%s#%s#%d#%d";
static const wchar_t *R44 = L"R44:%s#%s";
static const wchar_t *R45 = L"R45:%s#%d#%d";
//1014
static const wchar_t *R46 = L"R46:%s";
//1015
static const wchar_t *R47 = L"R47:";
//1016
static const wchar_t *R48 = L"R48:%s";
//1017
static const wchar_t *R49 = L"R49:%s";
//1018
static const wchar_t *R50 = L"R50:";
static const wchar_t *R51 = L"R51:";
//1019
static const wchar_t *R52 = L"R52:%s";
//1020
static const wchar_t *R53 = L"R53:";
//1021
static const wchar_t *R54 = L"R54:%s";
static const wchar_t *R55 = L"R55:%s#%d";
//1022
static const wchar_t *R56 = L"R56:%s";
//1023
static const wchar_t *R57 = L"R57:%s";
//1024
static const wchar_t *R58 = L"R58:%s";
//1025
static const wchar_t *R59 = L"R59:%s";
//1026
static const wchar_t *R60 = L"R60:%s";
static const wchar_t *R61 = L"R61:%s";
//1027
static const wchar_t *R179 = L"R179:";
//1028
static const wchar_t *R62 = L"R62:%s";
//1029 && 1030
static const wchar_t *R158 = L"R158:%s";
static const wchar_t *R159 = L"R159:%s";
static const wchar_t *R160 = L"R160:%s";
static const wchar_t *R161 = L"R161:%s";
static const wchar_t *R162 = L"R162:%s";
static const wchar_t *R163 = L"R163:%s";
static const wchar_t *RR158_1 = L"RR158_1:";
//1031
static const wchar_t *R63 = L"R63:%s#%d";
//1032
static const wchar_t *R64 = L"R64:%s#%s";
//1033
static const wchar_t *R65 = L"R65:%s#%s";
//1034
static const wchar_t *R66 = L"R66:%s#%s";
//1035
//--- TODO
//1036
static const wchar_t *R67 = L"R67:";
//1037
static const wchar_t *R68 = L"R68:%s";
//1038
static const wchar_t *R69 = L"R69:";
static const wchar_t *R70 = L"R70:";
//1039
static const wchar_t *R71 = L"R71:%s#%s#%s#%s#%d#%s#%d";
//1040
static const wchar_t *R72 = L"R72:%d#%s#%s";
static const wchar_t *R73 = L"R73:%s#%s";
//1041
static const wchar_t *R74 = L"R74:%s";
//1042
static const wchar_t *R75 = L"R75:%s#%s";
//1043
static const wchar_t *R76 = L"R76:";
static const wchar_t *R77 = L"R77:%d#%d#%d";
static const wchar_t *R78 = L"R78:%s#%d";
//1044
static const wchar_t *R79 = L"R79:";
static const wchar_t *R80 = L"R80:";
//1045
static const wchar_t *R81 = L"R81:%s#%s";
//1046
static const wchar_t *R82 = L"R82:%s";
static const wchar_t *R83 = L"R83:%s";
static const wchar_t *R84 = L"R84:%s";
//1047
static const wchar_t *R85 = L"R85:%d#%s";
static const wchar_t *R86 = L"R86:%s";
static const wchar_t *R87 = L"R87:%s";
static const wchar_t *R88 = L"R88:%s";
static const wchar_t *R89 = L"R89:%s";
static const wchar_t *R90 = L"R90:%s";
static const wchar_t *R91 = L"R91:%s";
static const wchar_t *R164 = L"R164:%s";
//1048
static const wchar_t *R92 = L"R92:%s#%s#%d#%s#%d";
//1049
static const wchar_t *R93 = L"R93:";
//1050
static const wchar_t *R146 = L"R146:";
static const wchar_t *R147 = L"R147:";
//1051
static const wchar_t *R148 = L"R148:";
//1052
static const wchar_t *R150 = L"R150:";
//1053
static const wchar_t *R154 = L"R154:%s";
//1054
static const wchar_t *R155 = L"R155:%s#%d#%d#%s";
//1055
static const wchar_t *R156 = L"R156:%d#%s#%s";
//1056
static const wchar_t *R157 = L"R157:%s#%s";
//1057
static const wchar_t *R175 = L"R175:%s";
//1058
static const wchar_t *R176 = L"R176:";
//1059
static const wchar_t *R182 = L"R176:%s";
//1060
static const wchar_t *R183 = L"R183:";
//1061
static const wchar_t *R184 = L"R184:%s";
//1062
static const wchar_t* R205 = L"R205:%s#%s";
//2001
static const wchar_t *R94 = L"R94:";
static const wchar_t *R95 = L"R95:";
//2002
static const wchar_t *R96 = L"R96:";
static const wchar_t *R97 = L"R97:";
//2003
static const wchar_t *R98 = L"R98:";
//2004
static const wchar_t *R99 = L"R99:";
//2005
static const wchar_t *R100 = L"R100:%d#%d";
//2006
static const wchar_t *R101 = L"R101:%s";
//2007
static const wchar_t *R102 = L"R102:";
static const wchar_t *R103 = L"R103:";
//2008
// -- TODO
//2009
static const wchar_t *R104 = L"R104:%s";
//2010
static const wchar_t *R105 = L"R105:";
static const wchar_t *R106 = L"R106:";
static const wchar_t *R107 = L"R107:";
//2011
static const wchar_t *R177 = L"R177:";
//2012
static const wchar_t *R173 = L"R173:";
//2013
static const wchar_t *R174 = L"R174:%s";
//2014
static const wchar_t *R180 = L"R180:%s#%s";
//2015
static const wchar_t *R185 = L"R185:";
static const wchar_t *R186 = L"R186:";
static const wchar_t *R187 = L"R187:";
static const wchar_t *R195 = L"R195:";
//2016
static const wchar_t *R188 = L"R188:%s";
//2017
static const wchar_t *R189 = L"R189:%s";
static const wchar_t *R190 = L"R190:%s#%s";
//2018
static const wchar_t *R191 = L"R191:%s";
static const wchar_t *R201 = L"R201:%s";
//2019
static const wchar_t *R192 = L"R192:%s#%s#%s";
//2020
static const wchar_t *R193 = L"R193:";
//2021
static const wchar_t *R194 = L"R194:%s";
//2022
static const wchar_t *R196 = L"R196:";
//2023
static const wchar_t *R197 = L"R197:";
//2024
static const wchar_t *R198 = L"R198:%s";
//2025
static const wchar_t *R203 = L"R203:%s#%s";
//3001
static const wchar_t *R108 = L"R108:%s";
//3002
static const wchar_t *R109 = L"R109:%s#%d";
static const wchar_t *R200 = L"R200:%s#%d";
//3003
static const wchar_t *R110 = L"R110:%s#%s#%d";
//3004
static const wchar_t *R111 = L"R111:%s";
//3005
static const wchar_t *R112 = L"R112:%s";
//3006
static const wchar_t *R113 = L"R113:";
static const wchar_t *R114 = L"R114:";
static const wchar_t *R115 = L"R115:";
static const wchar_t *R116 = L"R116:";
static const wchar_t *R117 = L"R117:";
static const wchar_t *R118 = L"R118:";
static const wchar_t *R119 = L"R119:";
static const wchar_t *R120 = L"R120:";
static const wchar_t *R121 = L"R121:";
static const wchar_t *R122 = L"R122:";
static const wchar_t *R123 = L"R123:";
static const wchar_t *R124 = L"R124:%s#%s#%d#%s#%d#%d";
static const wchar_t *R125 = L"R124:%s#%s#%d#%s#%d";
static const wchar_t *R144 = L"R144:";
static const wchar_t *R145 = L"R145:";
static const wchar_t *R178 = L"R178:";
static const wchar_t *R199 = L"R199:";
//3007
static const wchar_t *R126 = L"R126:%s#%d#%d";
static const wchar_t *R127 = L"R127:";
//3008
static const wchar_t *R128 = L"R128:";
//3009
static const wchar_t *R129 = L"R129:%s";
//3010
static const wchar_t *R130 = L"R130:";
static const wchar_t *R131 = L"R131:";
//3011
static const wchar_t *R132 = L"R132:%s#%s";
//3012
static const wchar_t *R133 = L"R133:%s#%s";
//3013
static const wchar_t *R134 = L"R134:%s#%s";
static const wchar_t *R152 = L"R152:%s#%s";
//3014
static const wchar_t *R135 = L"R135:%s#%s";
//3015
static const wchar_t *R136 = L"R136:%s";
//3016
static const wchar_t *R137 = L"R137:";
//3017
static const wchar_t *R138 = L"R138:%s#%s";
//3018
static const wchar_t *R139 = L"R139:%s#%s";
//3019
//--- TODO предиктор
//3020
static const wchar_t *R140 = L"R140:%s";
static const wchar_t *R141 = L"R141:%s";
static const wchar_t *R153 = L"R153:%s";
static const wchar_t *R142 = L"R142:%s";
//3021
static const wchar_t *R151 = L"R151:";
//3022
static const wchar_t *R171 = L"R171:%s";
//3023
static const wchar_t *R202 = L"R202:%s";
//3024
static const wchar_t* R204 = L"R204:";
//4001
//---TODO ошибки из SAGE
//4002
static const wchar_t *R143 = L"R143:";
//5001
static const wchar_t *R165 = L"R165:";
//5002
static const wchar_t *R166 = L"R166:%s#%s";
//5003
static const wchar_t *R167 = L"R167:";
//5004
static const wchar_t *R168 = L"R168:%s#%s";
//5005
static const wchar_t *R169 = L"R169:";
//5006
static const wchar_t *R170 = L"R170:%s";
//5007
static const wchar_t *R172 = L"R172:%s";

View File

@@ -0,0 +1,18 @@
#pragma once
#ifdef _WIN32
#ifdef _LEAK_
//_DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif
#endif

View File

@@ -0,0 +1,664 @@
#include <vector>
#include <set>
#include <map>
#include <string>
#include "dvm.h"
#include "errors.h"
#include "utils.h"
#include "../GraphCall/graph_calls_func.h"
#include "module_utils.h"
using std::vector;
using std::set;
using std::string;
using std::map;
using std::pair;
using std::make_pair;
void findModulesInFile(SgFile* file, vector<SgStatement*>& modules)
{
SgStatement* first = file->firstStatement();
set<SgStatement*> functions;
int funcNum = file->numberOfFunctions();
for (int i = 0; i < funcNum; ++i)
functions.insert(file->functions(i));
while (first)
{
if (first->variant() == MODULE_STMT)
{
modules.push_back(first);
first = first->lastNodeOfStmt();
}
else
{
if (functions.size())
{
auto it = functions.find(first);
if (it != functions.end())
first = (*it)->lastNodeOfStmt();
}
}
first = first->lexNext();
}
}
void getModulesAndFunctions(SgFile* file, vector<SgStatement*>& modulesAndFunctions)
{
findModulesInFile(file, modulesAndFunctions);
int funcNum = file->numberOfFunctions();
for (int i = 0; i < funcNum; ++i)
modulesAndFunctions.push_back(file->functions(i));
}
map<string, set<string>> createMapOfModuleUses(SgFile* file)
{
map<string, set<string>> retValMap;
vector<SgStatement*> modules;
findModulesInFile(file, modules);
for (int z = 0; z < modules.size(); ++z)
{
SgStatement* curr = modules[z];
string modName = curr->symbol()->identifier();
for (SgStatement* st = curr->lexNext(); st != curr->lastNodeOfStmt(); st = st->lexNext())
{
if (st->variant() == USE_STMT)
retValMap[modName].insert(st->symbol()->identifier());
else if (st->variant() == PROC_HEDR || st->variant() == FUNC_HEDR)
break;
}
}
bool repeat = true;
while (repeat)
{
repeat = false;
for (auto& elem : retValMap)
{
set<string> toAdd(elem.second);
for (auto& inUse : elem.second)
{
auto it = retValMap.find(inUse);
if (it != retValMap.end())
{
for (auto& inUseToAdd : it->second)
{
if (toAdd.find(inUseToAdd) == toAdd.end())
{
toAdd.insert(inUseToAdd);
repeat = true;
}
}
}
}
elem.second = toAdd;
}
}
return retValMap;
}
void fillModuleUse(SgFile* file, map<string, set<string>>& moduleUses, map<string, string>& moduleDecls)
{
const string currFN = file->filename();
for (SgStatement* st = file->firstStatement(); st; st = st->lexNext())
{
if (st->fileName() == currFN)
{
if (st->variant() == USE_STMT)
moduleUses[currFN].insert(st->symbol()->identifier());
if (st->variant() == MODULE_STMT)
{
string moduleN = st->symbol()->identifier();
auto it = moduleDecls.find(moduleN);
if (it != moduleDecls.end())
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
moduleDecls[moduleN] = currFN;
}
}
}
}
void filterModuleUse(map<string, set<string>>& moduleUsesByFile, map<string, string>& moduleDecls)
{
for (auto& elem : moduleUsesByFile)
{
set<string> newSet;
for (auto& setElem : elem.second)
{
auto it = moduleDecls.find(setElem);
if (it == moduleDecls.end())
newSet.insert(setElem);
else if (elem.first != it->second)
newSet.insert(setElem);
}
elem.second = newSet;
}
/*map<string, set<string>> modIncludeMod;
for (auto& mod : moduleDecls)
{
string name = mod.first;
string file = mod.second;
auto it = moduleUsesByFile.find(file);
if (it != moduleUsesByFile.end())
modIncludeMod[name] = it->second;
}
bool change = true;
while (change)
{
change = false;
for (auto& mod : modIncludeMod)
{
set<string> newSet = mod.second;
for (auto& included : mod.second)
{
auto it = modIncludeMod.find(included);
if (it == modIncludeMod.end())
continue;
for (auto& elem : it->second)
{
if (newSet.find(elem) == newSet.end())
{
newSet.insert(elem);
change = true;
}
}
}
mod.second = newSet;
}
}
for (auto& elem : moduleUsesByFile)
{
set<string> newSet = elem.second;
for (auto& setElem : elem.second)
{
auto it = modIncludeMod.find(setElem);
if (it != modIncludeMod.end())
for (auto& toRem : it->second)
newSet.erase(toRem);
}
elem.second = newSet;
}*/
}
static void addUseStatements(SgStatement* currF, SgStatement* obj, vector<SgStatement*>& useStats,
const vector<SgStatement*>& funcContains)
{
for (auto& funcSt : funcContains)
{
if (currF == funcSt)
{
SgStatement* last = obj->lastNodeOfStmt();
for (SgStatement* st = obj->lexNext(); st != last; st = st->lexNext())
{
if (st->variant() == USE_STMT)
useStats.push_back(st);
else if (st->variant() == CONTAINS_STMT)
break;
}
break;
}
}
}
void fillUsedModulesInFunction(SgStatement* st, vector<SgStatement*>& useStats)
{
checkNull(st, convertFileName(__FILE__).c_str(), __LINE__);
int var = st->variant();
while (var != PROG_HEDR && var != PROC_HEDR && var != FUNC_HEDR)
{
st = st->controlParent();
checkNull(st, convertFileName(__FILE__).c_str(), __LINE__);
var = st->variant();
}
for (SgStatement* stat = st->lexNext(); !isSgExecutableStatement(stat); stat = stat->lexNext())
if (stat->variant() == USE_STMT)
useStats.push_back(stat);
for (int i = 0; i < current_file->numberOfFunctions(); ++i)
{
vector<SgStatement*> funcContains;
findContainsFunctions(current_file->functions(i), funcContains);
addUseStatements(st, current_file->functions(i), useStats, funcContains);
}
vector<SgStatement*> modules;
findModulesInFile(st->getFile(), modules);
for (auto& module : modules)
{
vector<SgStatement*> funcContains;
findContainsFunctions(module, funcContains, true);
addUseStatements(st, module, useStats, funcContains);
}
}
static void findByUse(map<string, vector<pair<SgSymbol*, SgSymbol*>>>& modByUse, const string& varName,
const set<string>& locNames, vector<string>& altNames)
{
for (auto& elem : modByUse)
{
if (locNames.count(elem.first))
{
for (auto& byUse : elem.second)
{
SgSymbol* toCmp = byUse.second ? byUse.second : byUse.first;
checkNull(toCmp, convertFileName(__FILE__).c_str(), __LINE__);
if (toCmp->identifier() == varName)
altNames.push_back(byUse.first->identifier());
}
}
}
}
static void fillInfo(SgStatement* start,
set<string>& useMod,
map<string, vector<pair<SgSymbol*, SgSymbol*>>>& modByUse,
map<string, vector<pair<SgSymbol*, SgSymbol*>>>& modByUseOnly)
{
for (SgStatement* st = start; st != start->lastNodeOfStmt(); st = st->lexNext())
{
if (isSgExecutableStatement(st))
break;
if (st->variant() == CONTAINS_STMT)
break;
if (st != start && (st->variant() == PROC_HEDR || st->variant() == FUNC_HEDR))
break;
fillUseStatement(st, useMod, modByUse, modByUseOnly);
}
}
static SgStatement* findModWithName(const vector<SgStatement*>& modules, const string& name)
{
for (auto& elem : modules)
if (elem->variant() == MODULE_STMT)
if (elem->symbol()->identifier() == name)
return elem;
return NULL;
}
static map<SgStatement*, set<SgSymbol*>> symbolsForFunc;
static set<string> allFiles;
static void getModuleSymbols(SgStatement* func, set<SgSymbol*>& symbs)
{
SgSymbol* s = func->symbol()->next();
while (s)
{
if (s->scope() == func && IS_BY_USE(s))
symbs.insert(s);
s = s->next();
}
}
const set<SgSymbol*>& getModuleSymbols(SgStatement *func)
{
if (symbolsForFunc.find(func) != symbolsForFunc.end())
return symbolsForFunc[func];
set<SgSymbol*> symbs;
getModuleSymbols(func, symbs);
//if function in contains
func = func->controlParent();
if (isSgProgHedrStmt(func))
getModuleSymbols(func, symbs);
symbolsForFunc[func] = symbs;
return symbolsForFunc[func];
}
SgSymbol* getNameInLocation(SgStatement* func, const string& varName, const string& locName)
{
map<string, SgSymbol*> altNames;
for (const auto& s : getModuleSymbols(func))
{
SgSymbol* orig = OriginalSymbol(s);
//any suitable symbol can be used
if (orig->identifier() == varName && orig->scope()->symbol()->identifier() == locName)
altNames[s->identifier()] = s;
}
if (altNames.size() > 0)
return altNames.begin()->second;
else {
__spf_print(1, "%s %s %s\n", func->symbol()->identifier(), varName.c_str(), locName.c_str());
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
}
return NULL;
}
SgSymbol* getNameInLocation(SgSymbol* curr, SgStatement* location)
{
string oldFileName = "";
if (location->getFileId() != current_file_id)
{
oldFileName = current_file->filename();
if (!location->switchToFile())
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
}
SgStatement* func = getFuncStat(location, { MODULE_STMT });
if (func == NULL)
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
SgSymbol* returnVal = curr;
if (IS_BY_USE(curr))
{
const string location = OriginalSymbol(curr)->scope()->symbol()->identifier();
returnVal = getNameInLocation(func, OriginalSymbol(curr)->identifier(), location);
}
checkNull(returnVal, convertFileName(__FILE__).c_str(), __LINE__);
if (oldFileName != "" && SgFile::switchToFile(oldFileName) == -1)
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
return returnVal;
}
namespace Distribution
{
const string Array::GetNameInLocation(void* location_p) const
{
return ((SgSymbol*)GetNameInLocationS(location_p))->identifier();
}
void* Array::GetNameInLocationS(void* location_p) const
{
SgStatement* location = (SgStatement*)location_p;
string oldFileName = "";
if (location->getFileId() != current_file_id)
{
oldFileName = current_file->filename();
if (!location->switchToFile())
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
}
SgStatement* func = getFuncStat(location, { MODULE_STMT });
if (func == NULL)
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
if (allFiles.size() == 0)
allFiles = getAllFilesInProject();
const pair<int, int> lineRange = make_pair(func->lineNumber(), func->lastNodeOfStmt()->lineNumber());
const string& filename = func->fileName();
SgSymbol* returnVal = NULL;
if (locationPos.first == l_MODULE)
{
const string& varName = shortName;
const string& locName = locationPos.second;
returnVal = getNameInLocation(func, varName, locName);
}
else
returnVal = GetDeclSymbol(filename, lineRange, allFiles);
checkNull(returnVal, convertFileName(__FILE__).c_str(), __LINE__);
if (oldFileName != "" && SgFile::switchToFile(oldFileName) == -1)
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
return returnVal;
}
}
void fixUseOnlyStmt(SgFile *file, const vector<ParallelRegion*> &regs)
{
for (int z = 0; z < file->numberOfFunctions(); ++z)
{
vector<SgStatement*> modules;
findModulesInFile(file, modules);
map<string, SgStatement*> mod;
for (auto &elem : modules)
mod[elem->symbol()->identifier()] = elem;
if (modules.size())
{
SgStatement *func = file->functions(z);
bool hasTemplateUse = false;
set<DIST::Array*> needToAdd;
for (auto st = func; st != func->lastNodeOfStmt(); st = st->lexNext())
{
if (isSgExecutableStatement(st))
break;
if (st->variant() == USE_STMT)
{
SgExpression *ex = st->expr(0);
string modName = st->symbol()->identifier();
auto it = mod.find(modName);
if (modName == "dvmh_Template_Mod")
{
hasTemplateUse = true;
break;
}
if (ex && ex->variant() == ONLY_NODE && it != mod.end())
{
set<string> allS;
for (auto exI = ex->lhs(); exI; exI = exI->rhs())
{
if (exI->lhs()->variant() == RENAME_NODE)
{
if (exI->lhs()->lhs()->symbol())
allS.insert(exI->lhs()->lhs()->symbol()->identifier());
if (exI->lhs()->rhs() && exI->lhs()->rhs()->symbol())
allS.insert(exI->lhs()->rhs()->symbol()->identifier());
}
}
for (auto &parReg : regs)
{
const DataDirective &dataDir = parReg->GetDataDir();
for (auto &rule : dataDir.distrRules)
{
DIST::Array *curr = rule.first;
auto location = curr->GetLocation();
if (location.first == 2 && location.second == modName)
needToAdd.insert(curr);
}
for (auto& rule : dataDir.alignRules)
{
DIST::Array* curr = rule.alignArray;
auto location = curr->GetLocation();
if (location.first == 2 && location.second == modName)
needToAdd.insert(curr);
}
}
}
}
}
if (!hasTemplateUse && needToAdd.size())
{
SgStatement* useSt = new SgStatement(USE_STMT);
useSt->setSymbol(*findSymbolOrCreate(file, "dvmh_Template_Mod"));
useSt->setlineNumber(getNextNegativeLineNumber());
func->insertStmtAfter(*useSt, *func);
}
}
}
}
void fillUseStatement(SgStatement *st, set<string> &useMod,
map<string, vector<pair<SgSymbol*, SgSymbol*>>> &modByUse,
map<string, vector<pair<SgSymbol*, SgSymbol*>>> &modByUseOnly)
{
if (st->variant() == USE_STMT)
{
SgExpression *ex = st->expr(0);
string modName = st->symbol()->identifier();
convertToLower(modName);
useMod.insert(modName);
if (ex)
{
SgExpression *start = ex;
bool only = false;
if (ex->variant() == ONLY_NODE)
{
start = ex->lhs();
only = true;
}
for (auto exI = start; exI; exI = exI->rhs())
{
if (exI->lhs()->variant() == RENAME_NODE)
{
SgSymbol *left = NULL, *right = NULL;
if (exI->lhs()->lhs()->symbol())
left = exI->lhs()->lhs()->symbol();
if (exI->lhs()->rhs() && exI->lhs()->rhs()->symbol())
right = exI->lhs()->rhs()->symbol();
if (only)
modByUseOnly[modName].push_back(std::make_pair(left, right));
else
modByUse[modName].push_back(std::make_pair(left, right));
}
}
}
}
}
static void fillUseStmt(SgStatement* stat, map<string, set<SgSymbol*>>& byUse)
{
if (stat->variant() != USE_STMT)
printInternalError(convertFileName(__FILE__).c_str(), __LINE__);
SgExpression* ex = stat->expr(0);
if (ex && ex->variant() == ONLY_NODE)
{
for (auto exI = ex->lhs(); exI; exI = exI->rhs())
{
if (exI->lhs()->variant() == RENAME_NODE)
{
SgExpression* ren = exI->lhs();
if (ren->lhs()->symbol() && ren->rhs() && ren->rhs()->symbol())
byUse[ren->rhs()->symbol()->identifier()].insert(ren->lhs()->symbol());
}
}
}
else if (ex && ex->lhs())
{
for (auto exI = ex; exI; exI = exI->rhs())
{
if (exI->lhs()->variant() == RENAME_NODE)
{
SgExpression* ren = exI->lhs();
if (ren->lhs()->symbol() && ren->rhs() && ren->rhs()->symbol())
byUse[ren->rhs()->symbol()->identifier()].insert(ren->lhs()->symbol());
}
}
}
}
map<string, set<SgSymbol*>> moduleRefsByUseInFunction(SgStatement* stIn)
{
checkNull(stIn, convertFileName(__FILE__).c_str(), __LINE__);
map<string, set<SgSymbol*>> byUse;
int var = stIn->variant();
while (var != PROG_HEDR && var != PROC_HEDR && var != FUNC_HEDR)
{
stIn = stIn->controlParent();
if (stIn == NULL)
return byUse;
var = stIn->variant();
}
auto mapOfUses = createMapOfModuleUses(stIn->getFile());
set<string> useMods;
for (SgStatement* stat = stIn->lexNext(); !isSgExecutableStatement(stat); stat = stat->lexNext())
{
if (stat->variant() == USE_STMT)
{
fillUseStmt(stat, byUse);
useMods.insert(stat->symbol()->identifier());
}
}
const int cpOfSt = stIn->controlParent()->variant();
//contains of func
if (cpOfSt == PROG_HEDR || cpOfSt == PROC_HEDR || cpOfSt == FUNC_HEDR)
{
for (SgStatement* stat = stIn->controlParent()->lexNext(); !isSgExecutableStatement(stat); stat = stat->lexNext())
{
if (stat->variant() == USE_STMT)
{
fillUseStmt(stat, byUse);
useMods.insert(stat->symbol()->identifier());
}
}
}
bool chages = true;
while (chages)
{
chages = false;
set<string> newUseMods(useMods);
for (auto& elem : useMods)
{
auto it = mapOfUses.find(elem);
if (it != mapOfUses.end())
{
for (auto& elem2 : it->second)
{
if (newUseMods.find(elem2) == newUseMods.end())
{
newUseMods.insert(elem2);
chages = true;
}
}
}
}
useMods = newUseMods;
}
vector<SgStatement*> modules;
findModulesInFile(stIn->getFile(), modules);
for (auto& mod : modules)
{
if (useMods.find(mod->symbol()->identifier()) != useMods.end())
{
for (SgStatement* stat = mod->lexNext(); stat != mod->lastNodeOfStmt(); stat = stat->lexNext())
{
const int var = stat->variant();
if (var == USE_STMT)
{
fillUseStmt(stat, byUse);
useMods.insert(stat->symbol()->identifier());
}
else if (var == PROC_HEDR || var == FUNC_HEDR)
break;
}
}
}
return byUse;
}

View File

@@ -0,0 +1,14 @@
#pragma once
const std::set<SgSymbol*>& getModuleSymbols(SgStatement* func);
void getModulesAndFunctions(SgFile* file, std::vector<SgStatement*>& modulesAndFunctions);
void findModulesInFile(SgFile* file, std::vector<SgStatement*>& modules);
std::map<std::string, std::set<std::string>> createMapOfModuleUses(SgFile* file);
void fillModuleUse(SgFile* file, std::map<std::string, std::set<std::string>>& moduleUses, std::map<std::string, std::string>& moduleDecls);
void filterModuleUse(std::map<std::string, std::set<std::string>>& moduleUses, std::map<std::string, std::string>& moduleDecls);
SgSymbol* getNameInLocation(SgStatement* func, const std::string& varName, const std::string& locName);
SgSymbol* getNameInLocation(SgSymbol* curr, SgStatement* location);
void fillUsedModulesInFunction(SgStatement* st, std::vector<SgStatement*>& useStats);
void fillUseStatement(SgStatement* st, std::set<std::string>& useMod, std::map<std::string, std::vector<std::pair<SgSymbol*, SgSymbol*>>>& modByUse, std::map<std::string, std::vector<std::pair<SgSymbol*, SgSymbol*>>>& modByUseOnly);
void fixUseOnlyStmt(SgFile* file, const std::vector<ParallelRegion*>& regs);
std::map<std::string, std::set<SgSymbol*>> moduleRefsByUseInFunction(SgStatement* stIn);

View File

@@ -0,0 +1,340 @@
//1001
R1 = "Неверное расположение директивы: можно располагать только %s %s %s"
RR1_1 = "перед"
RR1_2 = "объявлением переменных"
RR1_3 = "циклом"
RR1_4 = "после"
RR1_5 = "всех операторов объявления"
RR1_6 = "заголовка функции"
RR1_7 = "единожды"
RR1_8 = "только"
R2 = "Неверное выражение: слишком много переменных цикла"
R3 = "Неверное выражение: возможно только вида a * i + b"
R4 = "Неверное расположение директивы: для области '%s' ожидается 'SPF END PARALLEL_REG_DIR', а была получена 'SPF PARALLEL_REG_DIR'"
R5 = "Неверное расположение директивы: для области '%s' ожидается 'SPF END PARALLEL_REG_DIR'"
R6 = "Неверное расположение директивы: для области '%s' ожидается 'SPF END PARALLEL_REG_DIR'"
R7 = "Неверное расположение директивы: ожидается 'SPF PARALLEL_REG_DIR', а была получена 'SPF END PARALLEL_REG_DIR'"
R8 = "Неверное расположение директивы: ожидается 'SPF PARALLEL_REG_DIR' в той же области видимости"
R9 = "Неверное расположение директивы: ожидается 'SPF PARALLEL_REG_DIR'"
R10 = "Не правильная расстановка области распараллеливания: есть несколько входов во фрагмент '%s', вызванные оператором ENTRY"
R11 = "Не правильная расстановка области распараллеливания: есть несколько входов во фрагмент '%s', вызванные оператором GOTO"
R12 = "Неправильное расположение строк: можно выбирать строки только в исполняемой части кода"
R13 = "Неправильное расположение строк: начало не может быть больше конца"
R14 = "Неправильное расположение строк: начало и конец при расширении не могут лежать в разных областях"
R15 = "Неправильное положение строки: начало и конец не могут быть в неявных фрагментах"
R16 = "Неправильное положение строк: начало и конец не могут быть в разных функциях"
R17 = "Неправильное расположение строк: выделенный фрагмент при расширении не должен включать фрагменты разных областей"
R18 = "Неправильное расположение строк: начало и конец должны быть в одной области видимости"
R19 = "Неправильное расположение строк %d-%d: нельзя объединить фрагменты в разных областях видимости"
R20 = "Неправильное расположение строк: начало и конец должны быть в одной области видимости"
//1002
R21 = "Переменная '%s' не используется в цикле"
R22 = "Переменная '%s' не используется в цикле"
//1003
R23 = "Переменная '%s' не изменяется в цикле"
R24 = "Переменная '%s' не изменяется в цикле"
//1004
R25 = "Размерность массива '%s' %d, а должна быть 1"
//1005
R26 = "Тип массива '%s' должен быть INTEGER"
//1006
R27 = "Типом переменной '%s' должен быть массив"
R28 = "Переменная '%s' не является массивом"
R29 = "Переменная '%s' не является массивом"
//1007
R30 = "Размер массива не может быть вычислен"
//1008
R31 = "Размер массива '%s' %d, а вы вводите %d"
R32 = "Размерность массива '%s' %d, а вы вводите %d"
//1009
R33 = "Массив '%s' является приватным"
R34 = "Массив '%s' является приватным"
//1010
R35 = "Разрешены только положительные числа"
//1011
R36 = "Нет такого выражения '%s' в цикле"
//1012
R37 = "Невозможно определить размеры массива '%s'"
R149 = "Невозможно определить размеры цикла '%s'"
//1013
R38 = "Отличается количество формальных и фактических параметров для функции '%s'" //Требуется выполнить подстановку функции '%s', так как
R39 = "Отличается тип фактического (%s : %s) и формального (%s : %s) %d-го параметра для функции '%s'" //Требуется выполнить подстановку функции '%s', так как
R40 = "Требуется выполнить подстановку функции '%s', так как можно передавать массивы только целиком"
R41 = "Требуется выполнить подстановку функции '%s' из-за обращения к неприватному массиву '%s' в цикле на строке %d %s"
R42 = "Требуется выполнить подстановку функции '%s' из-за обращения к неприватному массиву '%s' %s"
R43 = "Требуется подставить функцию '%s' из-за разной размерности массива %s', передаваемого в качестве параметра: размерность формального параметра = %d и фактического параметра = %d"
R44 = "Для процедуры '%s' обнаружено несоответствие типов формального и фактического параметра для массива '%s'."
R45 = "Необходимо подставить функцию '%s', так как через параметр %d передается итерационная переменная цикла на строке %d и она используется в индексном выражении в обращении к массиву в теле этой функции"
//1014
R46 = "Была найдена рекурсивная цепочка вызовов: %s, данная функция исключена из рассмотрения"
//1015
R47 = "Данная функция не вызывается в данном проекте"
//1016
R48 = "Невозможно вычислить количество итераций данного цикла, информация о количестве итераций для всех остальных циклов в области распараллеливания '%s' будет проигнорирована"
//1017
R49 = "Невозможно найти определение для символа '%s' в данной области видимости"
//1018
R50 = "Данный цикл не в END DO формате"
R51 = "Данный цикл не в END DO формате"
//1019
R52 = "Включаемый файл '%s' содержит исполняемые операторы, что запрещено к распараллеливанию в системе SAPFOR"
//1020
R53 = "Активные DVM-директивы не поддерживаются (необходимо включить опцию <<Учитывать DVM-директивы>>)"
//1021
R54 = "Обращение к массиву '%s' содержит более одной индексной переменной циклов"
R55 = "Обращение к массиву '%s' по измерению '%d' не содержит итерационных переменных циклов"
//1022
R56 = "Обращение к массиву '%s' имеет косвенную адресацию"
//1023
R57 = "Невозможно вычислить индексное выражение в обращении к массиву '%s'"
//1024
R58 = "Коэффициент A в линейном обращении A*x+B к массиву '%s' не может быть отрицательным, так как инверсное распределение не поддерживается"
//1025
R59 = "Невозможно сопоставить обращение к массиву на запись '%s' с данными циклом"
//1026
R60 = "Обнаружен оператор записи в нераспределенный массив '%s', связанный с данным циклом"
R61 = "Обнаружен оператор записи в нераспределенный массив '%s', связанный с данным циклом"
//1027
R179 = "Обнаружен более, чем один оператор в одной и той же строке, попробуйте применить проход Коррекция стиля кода"
//1028
R62 = "Описание модуля '%s' должно находиться в данном файле"
//1029 && 1030
R158 = "Рекурсия не анализируется для приватных переменных в коммон блоке '%s'"
R159 = "Анализ приватных переменных невозможен для данного цикла из-за: '%s'"
R160 = "Переменная '%s' из списка приватных переменных не может быть классифицирована как приватная"
R161 = "Массив '%s' из списка приватных переменных не может быть классифицирована как приватный"
R162 = "Добавлена приватная переменная '%s'"
R163 = "Добавлена приватная переменная по массиву '%s'"
RR158_1 = " для этого цикла"
//1031
R63 = "Неверное имя области: имя '%s' уже объявлено на строке %d"
//1032
R64 = "Неверное имя области: имя '%s' уже объявлено в common-блоке '%s'"
//1033
R65 = "Область распараллеливания '%s' включает саму себя в файле '%s'"
//1034
R66 = "Неверное расположение области: не существует common-блока в текущей функции %s со следующими массивами:%s"
//1035
//--- TODO
//1036
R67 = "Невозможно построить дерево выравнивания в данной области распараллеливания, используя пользовательские DVM-директивы"
//1037
R68 = "Массив '%s' не может быть распределен из-за ограничений ввода/вывода, накладываемых DVM системой"
//1038
R69 = "Оператор PAUSE является запрещенным в параллельной программе"
R70 = "Оператор EQUIVALENCE не поддерживается на данный момент"
//1039
R71 = "Переменные '%s' и '%s' находятся в одной области ассоциации (common block '%s'), но имеют разные типы (файлы - %s:%d и %s:%d)"
//1040
R72 = "Первые %d измерений массива '%s' запрещены к распределению из-за передачи к функцию '%s'"
R73 = "Первое измерение массива '%s' запрещено к распределению из-за передачи в функцию '%s'"
//1041
R74 = "Область распараллеливания '%s'содержит строку, которая включена в другую область, необходимо применить проход Разрешение конфликтов областей"
//1042
R75 = "Распределенный массив '%s' состоящий в common блоке '%s' должен иметь описание в главной программной единице"
//1043
R76 = "Неверное выражение в директиве: ожидается список переменных"
R77 = "Неверное выражение в директиве: ожидается %d тесно-вложенных циклов на строке %d, но их всего %d"
R78 = "Неверное выражение в директиве: ожидается переменная '%s' на позиции %d"
//1044
R79 = "Поддерживаются функции только без побочных эффектов"
R80 = "Поддерживаются функции только без побочных эффектов"
//1045
R81 = "Аргумент '%s' процедуры '%s' имеет неизвестные нижнюю и/или верхнюю границы."
//1046
R82 = "Количество формальных и фактических параметров не одинаково для вызова данной функции '%s'"
R83 = "Количество формальных и фактических параметров не одинаково для вызова данной функции '%s'"
R84 = "Количество формальных и фактических параметров не одинаково для вызова данной функции '%s'"
//1047
R85 = "%d измерение массива '%s' не может быть распределено из-за различных отображений на циклы в операциях присваиваний"
R86 = "Массив '%s' не может быть распределен, так как все его измерения запрещены к распределению"
R87 = "Массив '%s' не может быть распределен"
R88 = "Массив '%s' не может быть распределен"
R89 = "Массив '%s' не может быть распределен"
R90 = "Массив '%s' не может быть распределен из-за использования RESHAPE"
R91 = "Массив '%s' не может быть распределен"
R164 = "Массив '%s' не может быть распределен из-за использования конструктора инициализации"
//1048
R92 = "Функция '%s' с одинаковым именем была объявлена в более, чем одном месте: в файле '%s':%d и '%s':%d"
//1049
R93 = "Функция не является чистой (без побочных эффектов) из-за наличия данного оператора"
//1050
R146 = "Найдена более, чем одна главная программная единица (PROGRAM)"
R147 = "Не найдена ни одна главная программная единица (PROGRAM)"
//1051
R148 = "Обнаружены вызовы MPI-функций, включен режим специальный режим распараллеливания MPI-программ"
//1052
R150 = "Ошибка в расстановке пользовательских интервалов - не удалось найти конец интервала"
//1053
R154 = "Ошибка в выражении SHRINK клаузы: переменная должна быть массивом в файле '%s'"
//1054
R155 = "Длина маски для массива '%s' должна быть равна %d, но указано только %d измерений в файле '%s'"
//1055
R156 = "Ошибка в выражении маски на %d позиции массива '%s': в качестве значения могут быть только 0 и 1 в файле '%s'"
//1056
R157 = "Массив '%s' в клаузе shrink также должен быть объявлен в клаузе private в файле '%s'"
//1057
R175 = "Переменная '%s' должна использоваться в следующем операторе."
//1058
R176 = "В левой части клаузы PARAMETER должна быть переменная."
//1059
R182 = "Редукционная операция по элементу массива '%s' на данный момент не поддерживается".
//1060
R183 = "Расположение операторов FORMAT не поддерживается, попробуйте применить проход Коррекция стиля кода".
//1061
R184 = "Область объявления массива '%s' конфликтует с предыдущей областью. Возможно, это вызвано использованием include-файлов. Попробуйте применить проход 'Подстановка заголовочных файлов'".
//1042
R205 = "Массив '%s' состоящий в common блоке '%s' должен иметь описание в главной программной единице для объявления в директиве DECLARE"
//2001
R94 = "Невозможно автоматически преобразовать данное присваивание к циклу"
R95 = "Невозможно автоматически преобразовать данное присваивание к циклу"
//2002
R96 = "Арифметический IF был преобразован в IF-ENDIF"
R97 = "Вычисляемый GOTO был преобразован в IF-ENDIF"
//2003
R98 = "Невозможно автоматически преобразовать цикл в END DO формат"
//2004
R99 = "Цикл был преобразован в END DO формат"
//2005
R100 = "Циклы в строке %d и в строке %d были объединены"
//2006
R101 = "Была выполнена подстановка макроса с именем '%s'"
//2007
R102 = "Возникла непредвиденная ситуация во время генерации выходного текста"
R103 = "Возникла непредвиденная ситуация во время генерации выходного текста"
//2008
// -- TODO
//2009
R104 = "Невозможно разделить данный цикл из-за следующей зависимости: %s"
//2010
R105 = "Данный цикл содержит косвенные подциклы, поэтому не может быть разделен"
R106 = "У данного цикла есть ограничение на распараллеливание (в строке %s"
R107 = "У данного цикла есть зависимости, которые нельзя проанализировать, поэтому он не может быть разделен (в строке %s"
//2011
R177 = "Подстановка функций разрешена только в исполняемой части кода."
//2012
R173 = "Операторы SAVE и DATA запрещены в дублируемых функциях"
//2013
R174 = "Операторы SAVE и DATA запрещены в дублируемых функциях: переменная '%s'"
//2014
R180 = "Невозможно выполнить подстановку функции '%s': разная размерность формального и фактического параметра '%s'"
//2015
R185 = "Не правильный синтаксис директивы"
R186 = "Не правильный синтаксис директивы - выражения в заголовке цикла должны быть вычисляемыми"
R187 = "Выражения в заголовке цикла должны быть вычисляемыми"
//2016
R188 = "Нельзя удалить приватную переменную '%s' - для неё не найдена маска фиксированных измерений"
//2017
R189 = "Нельзя удалить приватную переменную '%s' - она имеет рекурсивную зависимость"
R190 = "Нельзя удалить приватную переменную '%s' - она зависит от неинвариантной переменной цикла '%s'"
//2018
R191 = "Приватная переменная '%s' была удалена"
R201 = "Приватная переменная '%s' была частично удалена"
//2019
R192 = "Удаление приватной переменной '%s' было выполнено в предположении, что выражения '%s' и '%s' различны"
//2020
R193 = "Подстановка функций выполнилась с ошибкой"
//2021
R194 = "Нельзя удалить приватную переменную '%s' - не удалось найти достигающее определение для оператора"
//2022
R196 = "Невозможно выполнить преобразование циклов из-за зависимостей между операторами"
//2023
R197 = "Преобразование не может быть выполнено - не произошло никаких изменений в коде"
//2024
R198 = "Нельзя удалить приватную переменную '%s' - обращения к ней имеют разное выравнивание с циклом"
//2025
R203 = "Нельзя удалить приватную переменную '%s' - она используется в вызове функции %s"
//3001
R108 = "Добавлена across-зависимость к массиву '%s' в цикле"
//3002
R109 = "Добавлена приватная переменная '%s' к циклу на строке %d"
R200 = "Добавлена lastprivate переменная '%s' к циклу на строке %d"
//3003
R110 = "Добавлена редукционная переменная '%s' с типом операции '%s' к циклу на строке %d"
//3004
R111 = "Неизвестный тип редукционной операции по скаляру '%s'"
//3005
R112 = "Неизвестная зависимость по скалярной переменной '%s' (попробуйте вручную специфицировать ее тип)"
//3006
R113 = "Неизвестная зависимость по массиву препятствует распараллеливанию данного цикла"
R114 = "Неизвестная зависимость по скаляру препятствует распараллеливанию данного цикла"
R115 = "Внешние или внутренние операторы перехода (GOTO/EXIT) препятствуют распараллеливанию данного цикла"
R116 = "Операторы ввода/вывода препятствуют распараллеливанию данного цикла"
R117 = "Операторы STOP препятствуют распараллеливанию данного цикла"
R118 = "Обнаружены конфликтные присваивания, которые препятствуют распараллеливанию данного цикла"
R119 = "Невозможность сопоставить обращение к массиву на запись препятствует распараллеливанию данного цикла"
R120 = "Косвенная адресация по распределяемому массиву препятствует распараллеливанию данного цикла"
R121 = "Обращение к нераспределенному массиву на запись препятствует распараллеливанию данного цикла"
R122 = "Найдены различные правила выравнивания массивов, используемых на запись в данном цикле, препятствует распараллеливанию"
R123 = "Процедуры с побочным эффектном препятствуют распараллеливанию данного цикла"
R124 = "%s зависимость между %s (строка %d) и %s (строка %d) с неизвестным расстоянием препятствует распараллеливанию цикла на стрке %d"
R125 = "%s зависимость между %s (строка %d) и %s (строка %d) с неизвестным расстоянием препятствует распараллеливанию"
R144 = "Обнаружено не прямоугольное пространство итераций, что препятствует распараллеливанию данного цикла"
R145 = "Обнаружены DVM интервалы внутри цикла, что препятствует распараллеливанию данного цикла"
R199 = "Зависимость по скаляру с типом lastprivate препятствует распараллеливанию данного цикла"
//--TODO R124 R125 про неопределенную длину зависимости
//3007
R126 = "Невозможно создать с шаблоном для массива '%s': размерность массива '%d' и это не равно '%d'"
R127 = "Невозможно сопоставить выравнивания массивов, передаваемых в процедуру"
//3008
R128 = "Внутренняя ошибка анализа, распараллеливание не будет выполнено для данного файла"
//3009
R129 = "Добавленный REMOTE_ACCESS для обращения к массиву '%s' может привести к сильному замедлению"
//3010
R130 = "Не обнаружены массивы или свободные циклы для распределения в данном проекте"
R131 = "Не обнаружены массивы или свободные циклы для распределения в данной области распараллеливания"
//3011
R132 = "У массивов '%s' и '%s' разные правила выравнивания согласно обращению на запись в данном цикле"
//3012
R133 = "Области распараллеливания %sимеют общую используемую функцию '%s'"
//3013
R134 = "Области распараллеливания %sимеют общий используемый локальный массив '%s', необходимо применить проход Разрешение конфликтов областей"
R152 = "Области распараллеливания %sимеют общий используемый массив из модуля '%s', необходимо применить проход Разрешение конфликтов областей"
//3014
R135 = "Область распараллеливания '%s' содержит common-массив '%s', используемый в области и вне её, необходимо применить проход Разрешение конфликтов областей"
//3015
R136 = "Область распараллеливания '%s' не имеет DVM-интервала для фрагмента, необходимо применить проход Разрешение конфликтов областей"
//3016
R137 = "Невозможно считать DVM-статистику для получения времен"
//3017
R138 = "Область распараллеливания '%s' не содержит копирования массива '%s' в DVM-интервале, необходимо применить проход Разрешение конфликтов областей"
//3018
R139 = "Область распараллеливания '%s' не содержит копирования массива '%s' в DVM-интервале, необходимо применить проход Разрешение конфликтов областей"
//3019
//--- TODO предиктор
//3020
R140 = "Обнаружен массив '%s', являющийся параметром функции, в которую передаются как распределенные, так и не распределенные массивы. Возможно, стоит запретить к распределению обнаруженные массивы, либо продублировать соответствующую функцию."
R141 = "Обнаружен распределяемый массив '%s', передаваемый в качестве параметра в процедуру"
R153 = "Обнаружен не распределяемый массив '%s', передаваемый в качестве параметра в процедуру"
R142 = "Для массива '%s' не удается найти единого распределения, внутренняя ошибка системы."
//3021
R151 = "Пустые области распараллеливания недопускаются."
//3022
R171 = "Невозможно определить правила выравнивания для массива '%s'."
//3023
R202 = "Ссылка '%s' имеет отличный от оригинального массива размер"
//3024
R204 = "Пересечение памяти массивов препятствует распараллеливанию цикла"
//4001
//---TODO ошибки из SAGE
//4002
R143 = "Неверное объявление PURE функции - отсутствуют операторы INTENT"
//5001
R165 = "В клаузе 'INTERVAL' первый аргумент должен быть 'TIME' или 'ITER', а второй - типа integer"
//5002
R166 = "Директива %s с клаузой '%s' может располагаться только в исполняемой части кода"
//5003
R167 = "Директива CHECKPOINT с клаузой 'FILES' должна содержать одно значение типа integer"
//5004
R168 = "Перемення '%s' в клаузе '%s' должна быть объявлена в той же области видимости"
//5005
R169 = "Недопустимый параметр в клаузе TYPE директивы CHECKPOINT"
//5006
R170 = "Клауза '%s' может быть указана только один раз"
//5007
R172 = "Переменная '%s' не может быть указана одновременно в клаузах 'VARLIST' и 'EXCEPT'"

81
Sapfor/_src/Utils/types.h Normal file
View File

@@ -0,0 +1,81 @@
#pragma once
#include <vector>
#include <map>
#include <set>
enum REMOTE_TYPE : int { REMOTE_NONE = 0, REMOTE_TRUE = 1, REMOTE_FALSE = 3 };
inline REMOTE_TYPE operator|=(REMOTE_TYPE& lhs, const REMOTE_TYPE& rhs)
{
lhs = (REMOTE_TYPE)((std::underlying_type<REMOTE_TYPE>::type)lhs | (std::underlying_type<REMOTE_TYPE>::type)rhs);
return lhs;
}
class ArrayRefExp;
typedef std::pair<std::pair<int, int>, std::pair<int, int>> attrType;
struct ArrayOp
{
// stored ARRAY[A*x + B] -> (A, B) with weight
std::map<std::pair<int, int>, double> coefficients;
ArrayOp() { }
ArrayOp(const std::pair<std::pair<int, int>, double> &pair) { coefficients[pair.first] = pair.second; }
ArrayOp(const std::map<std::pair<int, int>, double> &coefficients) : coefficients(coefficients) { }
void printInfo() const
{
for (auto& elem : coefficients)
printf(" [%d ; %d]\n", elem.first.first, elem.first.second);
}
};
struct ArrayInfo
{
private:
int dimSize;
public:
std::vector<ArrayOp> writeOps;
std::vector<ArrayOp> readOps;
std::vector<bool> unrecReadOps;
//for remote in parallel
std::map<ArrayRefExp*, std::pair<int, std::vector<ArrayOp>>> arrayAccess;
//for remote
std::map<ArrayRefExp*, std::pair<int, std::vector<REMOTE_TYPE>>> arrayAccessUnrec;
ArrayInfo() : dimSize(0) { }
void setDimSize(int newSize)
{
if (dimSize < newSize)
{
dimSize = newSize;
writeOps.resize(newSize);
readOps.resize(newSize);
unrecReadOps.resize(newSize);
}
}
int getDimSize() const { return dimSize; }
void printInfo() const
{
if (dimSize == 0)
return;
printf(" writeOps:\n");
for (int z = 0; z < dimSize; ++z)
{
printf(" dim %d:\n", z);
writeOps[z].printInfo();
}
printf(" readOps:\n");
for (int z = 0; z < dimSize; ++z)
{
printf(" dim %d:\n", z);
readOps[z].printInfo();
}
}
};

1683
Sapfor/_src/Utils/utils.cpp Normal file

File diff suppressed because it is too large Load Diff

98
Sapfor/_src/Utils/utils.h Normal file
View File

@@ -0,0 +1,98 @@
#pragma once
#include <map>
#include <vector>
#include <set>
#include <string>
#include <cstdint>
struct DataDirective;
namespace Distribution
{
class Array;
class ArrayAccessInfo;
template<typename vType> class Arrays;
}
namespace DIST = Distribution;
std::string OnlyExt(const char *filename);
std::string OnlyName(const char *filename);
std::string FullNameWithExt(const char* filename);
void printHelp(const char **passNames, const int lastPass);
void convertToLower(std::string &str);
void convertToUpper(std::string &str);
void printVersion(const std::string = "");
const std::string printVersionAsFortranComm();
std::string convertFileName(const char *file);
void printBlanks(const int sizeOfBlank, const int countOfBlanks);
void addToGlobalBufferAndPrint(const std::string &toPrint);
void clearGlobalBuffer();
const std::string& getGlobalBuffer();
std::wstring to_wstring(const std::string);
void convertBuffers(short*& resultM, int*& resultSizeM, short*& result, int*& resultSize);
void clearGlobalMessagesBuffer();
std::string renameInclude(const std::string& inc);
void copyIncludes(const std::set<std::string> &allIncludeFiles, const std::map<std::string, std::map<int, std::set<std::string>>> &commentsToInclude, const std::map<std::string, std::map<int, std::set<std::string>>>& newCopyDeclToIncl, const char *folderName, bool keepSpfDirs, bool isFreeStyle, bool isRename, int removeDvmDirs = 0);
std::string splitDirective(const std::string &in);
std::string splitDirectiveFull(const std::string &in_);
void splitString(const std::string &strIn, const char delim, std::vector<std::string> &result, bool withQuotes = false);
void splitString(const std::wstring& strIn, const char delim, std::vector<std::wstring>& result, bool withQuotes = false);
bool isSPF_comment(const std::string& bufStr);
bool isDVM_comment(const std::string& bufStr);
void sortFilesBySize(const char *proj_name);
void uniteVectors(const std::vector<std::pair<std::pair<std::string, std::string>, std::vector<std::pair<int, int>>>> &first,
const std::vector<std::pair<std::pair<std::string, std::string>, std::vector<std::pair<int, int>>>> &second,
std::vector<std::pair<std::pair<std::string, std::string>, std::vector<std::pair<int, int>>>> &result);
void deletePointerAllocatedData(bool delLocal = false);
void startLocalColletion();
void finishLocalColletion();
void deleteLeaks();
unsigned getUniqArrayId();
bool isAllRulesEqualWithoutArray(const std::vector<std::vector<std::tuple<DIST::Array*, int, std::pair<int, int>>>> &allRules);
bool isAllRulesEqual(const std::vector<std::vector<std::tuple<DIST::Array*, int, std::pair<int, int>>>> &allRules);
bool isAllRulesEqual(const std::vector<std::vector<std::pair<int, int>>> &allRules);
bool isAllRulesEqual(const std::vector<std::vector<int>> &allRules);
int getNextNegativeLineNumber();
void findAndReplaceDimentions(std::vector<std::tuple<DIST::Array*, int, std::pair<int, int>>> &rule, const DIST::Arrays<int> &allArrays);
const std::set<std::string> getExcludedModules();
extern "C" void removeFromCollection(void *pointer);
extern "C" void addToCollection(const int line, const char *file, void *pointer, int type);
std::vector<int> findLinksBetweenArrays(DIST::Array *from, DIST::Array *to, const uint64_t regionId, bool withCheck = true);
#ifdef _WIN32
void printStackTrace();
#endif
template<typename objT>
objT& getObjectForFileFromMap(const char *fileName, std::map<std::string, objT> &mapObject);
bool isMpiFunction(const std::string& func);
std::map<DIST::Array*, DIST::ArrayAccessInfo*> createMapOfArrayAccess(const std::map<std::tuple<int, std::string, std::string>, std::pair<DIST::Array*, DIST::ArrayAccessInfo*>> &declaredArrays);
std::string readFileToStr(const std::string& name);
void writeFileFromStr(const std::string& name, const std::string& data);
std::pair<std::vector<std::string>, std::vector<std::string>> splitCommandLineForParse(char** argv, int argc, bool& isInline);
std::string getClearName(const std::string& in);
std::wstring fixedLongFormat(const wchar_t* old);
std::map<std::string, DIST::Array*> sortArraysByName(const std::set<DIST::Array*>& toSort);
bool createDirectory(const std::string& name);
std::vector<std::string> splitAndArgvCreate(const std::string& options);
std::set<DIST::Array*> fillDistributedArraysD(const DataDirective& dataDirectives, const std::map<DIST::Array*, std::tuple<int, std::string, std::string>>& tableOfUniqNamesByArray, const std::map<DIST::Array*, std::set<DIST::Array*>>& arrayLinksByFuncCalls, bool onlyCommon = false);
std::set<std::string> fillDistributedArrays(const DataDirective& dataDirectives, const std::map<DIST::Array*, std::tuple<int, std::string, std::string>>& tableOfUniqNamesByArray, const std::map<DIST::Array*, std::set<DIST::Array*>>& arrayLinksByFuncCalls, bool onlyCommon = false, bool shortName = false);

View File

@@ -0,0 +1,3 @@
#pragma once
#define VERSION_SPF "2396"