//! A default builder function handles all details: file use name, others use numbering // Algorithm: // Go through all parent scopes until reach SgSourceFile. store them into a list // iterate on the list to generate all abstract handles, with optional the parent handle information abstract_handle * buildAbstractHandle(SgNode* snode) { ROSE_ASSERT (snode != NULL); // simple nodes if (isSgSourceFile (snode) || isSgProject(snode) ||isSgGlobal(snode)) return buildSingleAbstractHandle (snode); // all other nodes, trace back to SgGlobal, store all intermediate scope nodes std::vector<SgNode*> scope_list; SgScopeStatement* p_scope = SageInterface::getEnclosingScope(snode); while (!isSgGlobal(p_scope)) { scope_list.push_back(p_scope); p_scope = SageInterface::getEnclosingScope(p_scope); } ROSE_ASSERT (isSgGlobal(p_scope)); abstract_handle * p_handle = buildSingleAbstractHandle (p_scope); // Now go through the list to generate numbering handles std::vector<SgNode*>::reverse_iterator riter; for (riter = scope_list.rbegin(); riter!= scope_list.rend(); riter++) { SgNode* c_node = *riter; p_handle = buildSingleAbstractHandle (c_node, p_handle); } ROSE_ASSERT (p_handle != NULL); return buildSingleAbstractHandle (snode, p_handle); }
Driver<Sage>::Driver(SgProject * project_) : project(project_), file_id_counter(1), // 0 is reserved path_to_id_map(), id_to_file_map(), file_to_id_map(), file_id_to_accessible_file_id_map(), p_symbol_to_file_id_map(), p_valid_symbols(), p_parent_map(), p_namespace_symbols(), p_function_symbols(), p_class_symbols(), p_variable_symbols(), p_member_function_symbols() { assert(project != NULL); if (!CommandlineProcessing::isCppFileNameSuffix("hpp")) CommandlineProcessing::extraCppSourceFileSuffixes.push_back("hpp"); if (!CommandlineProcessing::isCppFileNameSuffix("h")) CommandlineProcessing::extraCppSourceFileSuffixes.push_back("h"); // Load existing files const std::vector<SgFile *> & files = project->get_fileList_ptr()->get_listOfFiles(); std::vector<SgFile *>::const_iterator it_file; for (it_file = files.begin(); it_file != files.end(); it_file++) { SgSourceFile * src_file = isSgSourceFile(*it_file); if (src_file != NULL) add(src_file); } }
void virtual visit (SgNode* n) { if (isSgProject(n)|| isSgSourceFile(n)||isSgInitializedName(n)||isSgLocatedNode(n)) { setId (n); } }
int main(int argc, char ** argv) { std::vector<std::string> args(argv, argv + argc); #if defined(TILEK_ACCELERATOR) # if defined(TILEK_TARGET_OPENCL) args.push_back("-DSKIP_OPENCL_SPECIFIC_DEFINITION"); # endif #endif SgProject * project = new SgProject(args); assert(project->numberOfFiles() == 1); SgSourceFile * source_file = isSgSourceFile(project->get_fileList()[0]); assert(source_file != NULL); std::string filename = source_file->get_sourceFileNameWithoutPath(); std::string basename = filename.substr(0, filename.find_last_of('.')); KLT::DLX::Compiler< ::DLX::TileK::language_t, ::KLT::TileK::Generator> compiler(project, KLT_PATH, TILEK_PATH, basename); // MFB::api_t * api = compiler.getDriver().getAPI(); // dump_api(api); compiler.compile(project); project->unparse(); return 0; }
//! A helper function to build a single abstract handle item static abstract_handle * buildSingleAbstractHandle(SgNode* snode, abstract_handle * p_handle = NULL) { abstract_handle * result = NULL; ROSE_ASSERT (snode != NULL); abstract_node * anode = buildroseNode(snode); ROSE_ASSERT (anode != NULL); // look up first result = handle_map[anode]; if (result != NULL) return result; //Create the single handle item if (isSgSourceFile (snode) || isSgProject(snode) ||isSgGlobal(snode)) result = new abstract_handle (anode); // default name or file location specifiers are used else { // any other types of AST node, use numbering or name within the parent handle ROSE_ASSERT (p_handle != NULL); if (isSgFunctionDefinition(snode)) result = new abstract_handle (anode, e_name, p_handle); else result = new abstract_handle (anode, e_numbering, p_handle); } ROSE_ASSERT (result != NULL); // cache the result handle_map[anode] = result; return result; }
int main( int argc, char * argv[] ) { // Introduces tracking of performance of ROSE at the top most level. TimingPerformance timer ("AST translation (main): time (sec) = ",true); // Build a vector of strings to represent the command line arguments. std::vector<std::string> sourceCommandline = std::vector<std::string>(argv, argv + argc); sourceCommandline.push_back("-rose:unparse_tokens"); SgProject* project = frontend(sourceCommandline); AstTests::runAllTests(project); // Evaluate the number of tokens generated for each file on the command line. SgFilePtrList & fileList = project->get_fileList(); for (size_t i=0; i < fileList.size(); i++) { SgSourceFile* sourceFile = isSgSourceFile(fileList[i]); if (sourceFile != NULL) { size_t numberOfTokens = sourceFile->get_token_list().size(); printf ("Number of tokens in file %s = %zu \n",sourceFile->get_sourceFileNameWithPath().c_str(),numberOfTokens); if (numberOfTokens == 0) { // We output an error, but since this test is only presently valid for fortran files it is not serious. if (sourceFile->get_Fortran_only() == true) { printf ("Warning: numberOfTokens in file equal zero (could be an error). \n"); } else { printf ("Warning: token evaluation only valid for Fortran files at present. \n"); } } } else { printf ("Warning, token evaluation only valid for source files. \n"); } } // Output statistics about how ROSE was used... if (project->get_verbose() > 1) { std::cout << AstNodeStatistics::traversalStatistics(project); std::cout << AstNodeStatistics::IRnodeUsageStatistics(); } // Just set the project, the report will be generated upon calling the destructor for "timer" // Use option "-rose:verbose 2" to see the report. timer.set_project(project); // Skip calling the typical backend for ROSE (not required for just testing analysis) // This backend calls the backend compiler using the original input source file list. return backendCompilesUsingOriginalInputFile(project); }
unsigned Driver<Sage>::getFileID(SgScopeStatement * scope) const { SgFile * enclosing_file = SageInterface::getEnclosingFileNode(scope); assert(enclosing_file != NULL); // FIXME Contingency : Scope Stack SgSourceFile * enclosing_source_file = isSgSourceFile(enclosing_file); assert(enclosing_source_file != NULL); return getFileID(enclosing_source_file); }
void SgSourceFile::fixupCopy_symbols(SgNode* copy, SgCopyHelp & help) const { #if DEBUG_FIXUP_COPY printf ("Inside of SgFile::fixupCopy_symbols() \n"); #endif SgSourceFile* file_copy = isSgSourceFile(copy); ROSE_ASSERT(file_copy != NULL); // Call fixup on the global scope ROSE_ASSERT(get_globalScope() != NULL); ROSE_ASSERT(file_copy->get_globalScope() != NULL); get_globalScope()->fixupCopy_symbols(file_copy->get_globalScope(),help); }
virtual void visit(SgNode * n) { switch (n->variantT()) { case V_SgFunctionDeclaration: { SgFunctionDeclaration * func_decl = isSgFunctionDeclaration(n); ROSE_ASSERT(func_decl != NULL); std::string func_name = func_decl->get_name().getString(); // std::cout << "Found SgFunctionDeclaration: " << func_name << std::endl; if (func_name == "caller") p_caller = func_decl; if (func_name == "kernel") p_kernel = func_decl; break; } case V_SgForStatement: { SgForStatement * for_stmt = isSgForStatement(n); ROSE_ASSERT(for_stmt != NULL); // std::cout << "Found SgForStatement." << std::endl; p_for_stmts.push_back(for_stmt); break; } case V_SgFunctionCallExp: { SgFunctionCallExp * func_call = isSgFunctionCallExp(n); ROSE_ASSERT(func_call != NULL); SgFunctionRefExp * func_ref = isSgFunctionRefExp(func_call->get_function()); ROSE_ASSERT(func_ref != NULL); // std::cout << "Found SgFunctionCallExp: " << func_ref->getAssociatedFunctionDeclaration ()->get_name().getString() << std::endl; if (func_ref->getAssociatedFunctionDeclaration()->get_name().getString() == "kernel") p_kernel_call_site = func_call; break; } case V_SgSourceFile: // fix the file suffix, Liao 12/29/2010 { SgSourceFile * sfile = isSgSourceFile (n); ROSE_ASSERT (sfile != NULL); sfile->set_Cuda_only(true); } default:{} } }
string roseNode::getFileName() const { string result; ROSE_ASSERT(mNode!=NULL); // no uniform way to get file name in ROSE SgLocatedNode* lnode = isSgLocatedNode(mNode); SgSourceFile* sfile = isSgSourceFile(mNode); if (lnode) result = lnode->getFilenameString(); else if (sfile) result = sfile->getFileName(); else { cerr<<"error: unrecognized sage node to get a file name:" <<mNode->class_name()<<endl; ROSE_ASSERT(false); } return result; }
unsigned Driver<Sage>::add(const boost::filesystem::path & path) { assert(boost::filesystem::exists(path)); assert(boost::filesystem::is_regular_file(path)); std::map<boost::filesystem::path, unsigned>::const_iterator it_file_id = path_to_id_map.find(path); if (it_file_id != path_to_id_map.end()) return it_file_id->second; else { SgSourceFile * file = isSgSourceFile(SageBuilder::buildFile(path.string(), path.string(), project)); assert(file != NULL); file->set_skip_unparse(true); file->set_skipfinalCompileStep(true); unsigned id = add(file); path_to_id_map.insert(std::pair<boost::filesystem::path, unsigned>(path, id)); return id; } }
unsigned Driver<Sage>::create(const boost::filesystem::path & path) { assert(path_to_id_map.find(path) == path_to_id_map.end()); if (boost::filesystem::exists(path)) boost::filesystem::remove(path); std::map<boost::filesystem::path, unsigned>::const_iterator it_file_id = path_to_id_map.find(path); assert(it_file_id == path_to_id_map.end()); SgSourceFile * file = isSgSourceFile(SageBuilder::buildFile(path.string(), path.string(), project)); assert(file != NULL); SageInterface::attachComment(file, "/* File generated by Driver<Model>::getFileID(\"" + path.string() + "\") */"); file->set_skipfinalCompileStep(true); unsigned id = file_id_counter++; id_to_file_map.insert(std::pair<unsigned, SgSourceFile *>(id, file)); file_to_id_map.insert(std::pair<SgSourceFile *, unsigned>(file, id)); path_to_id_map.insert(std::pair<boost::filesystem::path, unsigned>(path, id)); file_id_to_accessible_file_id_map.insert(std::pair<unsigned, std::set<unsigned> >(id, std::set<unsigned>())).first->second.insert(id); return id; }
int main ( int argc, char * argv[] ) { if (argc <= 1) { PrintUsage(argv[0]); return -1; } SgProject sageProject ( argc,argv); SageInterface::changeAllLoopBodiesToBlocks(&sageProject); CmdOptions::GetInstance()->SetOptions(argc, argv); TestPtrAnal op; int filenum = sageProject.numberOfFiles(); for (int i = 0; i < filenum; ++i) { SgSourceFile* sageFile = isSgSourceFile(sageProject.get_fileList()[i]); ROSE_ASSERT(sageFile != NULL); SgGlobal *root = sageFile->get_globalScope(); AstInterfaceImpl scope(root); AstInterface fa(&scope); SgDeclarationStatementPtrList& declList = root->get_declarations (); for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) { SgFunctionDeclaration *func = isSgFunctionDeclaration(*p); if (func == 0) continue; SgFunctionDefinition *defn = func->get_definition(); if (defn == 0) continue; op(fa, defn); } } return 0; }
int main( int argc, char* argv[] ) { // Initialize and check compatibility. See rose::initialize ROSE_INITIALIZE; SgProject* project = frontend(argc,argv); AstTests::runAllTests(project); #if 0 // Output the graph so that we can see the whole AST graph, for debugging. generateAstGraph(project, 4000); #endif #if 1 printf ("Generate the dot output of the SAGE III AST \n"); generateDOT ( *project ); printf ("DONE: Generate the dot output of the SAGE III AST \n"); #endif // There are lots of way to write this, this is one simple approach; get all the function calls. std::vector<SgNode*> functionCalls = NodeQuery::querySubTree (project,V_SgFunctionCallExp); // Find the SgFunctionSymbol for snprintf so that we can reset references to "sprintf" to "snprintf" instead. // SgGlobal* globalScope = (*project)[0]->get_globalScope(); SgSourceFile* sourceFile = isSgSourceFile(project->get_fileList()[0]); ROSE_ASSERT(sourceFile != NULL); SgGlobal* globalScope = sourceFile->get_globalScope(); SgFunctionSymbol* snprintf_functionSymbol = globalScope->lookup_function_symbol("snprintf"); ROSE_ASSERT(snprintf_functionSymbol != NULL); // Iterate over the function calls to find the calls to "sprintf" for (unsigned long i = 0; i < functionCalls.size(); i++) { SgFunctionCallExp* functionCallExp = isSgFunctionCallExp(functionCalls[i]); ROSE_ASSERT(functionCallExp != NULL); SgFunctionRefExp* functionRefExp = isSgFunctionRefExp(functionCallExp->get_function()); if (functionRefExp != NULL) { SgFunctionSymbol* functionSymbol = functionRefExp->get_symbol(); if (functionSymbol != NULL) { SgName functionName = functionSymbol->get_name(); // printf ("Function being called: %s \n",functionName.str()); if (functionName == "sprintf") { // Now we have something to do! functionRefExp->set_symbol(snprintf_functionSymbol); // Now add the "n" argument SgExprListExp* functionArguments = functionCallExp->get_args(); SgExpressionPtrList & functionArgumentList = functionArguments->get_expressions(); // "sprintf" shuld have exactly 2 arguments (I guess the "..." don't count) printf ("functionArgumentList.size() = %zu \n",functionArgumentList.size()); // ROSE_ASSERT(functionArgumentList.size() == 2); SgExpressionPtrList::iterator i = functionArgumentList.begin(); // printf ("(*i) = %p = %s = %s \n",*i,(*i)->class_name().c_str(),SageInterface::get_name(*i).c_str()); SgVarRefExp* variableRefExp = isSgVarRefExp(*i); ROSE_ASSERT(variableRefExp != NULL); // printf ("variableRefExp->get_type() = %p = %s = %s \n",variableRefExp->get_type(),variableRefExp->get_type()->class_name().c_str(),SageInterface::get_name(variableRefExp->get_type()).c_str()); SgType* bufferType = variableRefExp->get_type(); SgExpression* bufferLengthExpression = NULL; switch(bufferType->variantT()) { case V_SgArrayType: { SgArrayType* arrayType = isSgArrayType(bufferType); bufferLengthExpression = arrayType->get_index(); break; } case V_SgPointerType: { // SgPointerType* pointerType = isSgPointerType(bufferType); SgInitializedName* variableDeclaration = variableRefExp->get_symbol()->get_declaration(); ROSE_ASSERT(variableDeclaration != NULL); SgExpression* initializer = variableDeclaration->get_initializer(); if (initializer != NULL) { SgAssignInitializer* assignmentInitializer = isSgAssignInitializer(initializer); ROSE_ASSERT(assignmentInitializer != NULL); // This is the rhs of the initialization of the pointer (likely a malloc through a cast). // This assumes: buffer = (char*) malloc(bufferLengthExpression); SgExpression* initializationExpression = assignmentInitializer->get_operand(); ROSE_ASSERT(initializationExpression != NULL); SgCastExp* castExp = isSgCastExp(initializationExpression); ROSE_ASSERT(castExp != NULL); SgFunctionCallExp* functionCall = isSgFunctionCallExp(castExp->get_operand()); ROSE_ASSERT(functionCall != NULL); SgExprListExp* functionArguments = isSgExprListExp(functionCall->get_args()); bufferLengthExpression = functionArguments->get_expressions()[0]; ROSE_ASSERT(bufferLengthExpression != NULL); } else { printf ("Initializer not found, so no value for n in snprintf can be computed currently \n"); } break; } default: { printf ("Error: default reached in evaluation of buffer type = %p = %s \n",bufferType,bufferType->class_name().c_str()); ROSE_ASSERT(false); } } ROSE_ASSERT(bufferLengthExpression != NULL); // printf ("bufferLengthExpression = %p = %s = %s \n",bufferLengthExpression,bufferLengthExpression->class_name().c_str(),SageInterface::get_name(bufferLengthExpression).c_str()); // Jump over the first argument, the "n" is defined to be the 2nd argument (the rest are shifted one position). i++; // Build a deep copy of the expression used to define the static buffer (could be any complex expression). SgTreeCopy copy_help; SgExpression* bufferLengthExpression_copy = isSgExpression(bufferLengthExpression->copy(copy_help)); // Insert the "n" for the parameter list to work with "snprintf" instead of "sprintf" functionArgumentList.insert(i,bufferLengthExpression_copy); } } } } return backend(project); }
/* * The function: * buildTypedefTranslationTable() * takes as a parameter a SgProject*. It will return a map<SgTypedefDeclaration*, SgType*> * where the idea is that all SgTypedefDeclaration* are unique, and therefore it is * possible to create a map with it's corresponding type for easy access. */ map< SgTypedefDeclaration*, SgType*> typeInterpreter::buildTypedefTranslationTable(SgProject* project){ ROSE_ASSERT (project != NULL); const SgFilePtrList sageFilePtrList = project->get_fileList (); //Iterate over all global scopes in the all the files the project spans. for (unsigned int i = 0; i < sageFilePtrList.size (); i += 1) { const SgFile *sageFile = isSgFile (sageFilePtrList[i]); ROSE_ASSERT (sageFile != NULL); if(isSgSourceFile(sageFile) == NULL ) continue; SgGlobal *sageGlobal = isSgSourceFile(sageFile)->get_globalScope (); ROSE_ASSERT (sageGlobal != NULL); SgTypedefDeclaration* typedefDeclaration; //Find all TypedefdefDeclarations in current global scope. vector < SgNode * > typedefDeclarationList = NodeQuery::querySubTree (sageGlobal, NodeQuery::TypedefDeclarations); unique(typedefDeclarationList.begin(),typedefDeclarationList.end()); //Iterate over all SgTypedefDeclarations in current global scope, //and find corresponding SgType*. for (vector < SgNode * >::iterator typedefDeclarationElm = typedefDeclarationList.begin (); typedefDeclarationElm != typedefDeclarationList.end (); ++typedefDeclarationElm) { typedefDeclaration = isSgTypedefDeclaration (*typedefDeclarationElm); ROSE_ASSERT (typedefDeclaration != NULL); //We only register a typedef once ROSE_ASSERT (typedefTranslationTable.find (typedefDeclaration) == typedefTranslationTable.end ()); SgType* typedefBaseType = typedefDeclaration->get_base_type(); ROSE_ASSERT(typedefBaseType != NULL ); SgType* baseType = typedefBaseType->findBaseType(); //If the SgTypedefDeclarations has a base type which is of SgTypedefType, find a //SgType* which is not of type SgTypedefType. That is the corresponging SgType*. while(isSgTypedefType(baseType) != NULL) baseType = isSgTypedefType(baseType)->get_base_type(); /* cout << "The name of the typedef is:" << typedefDeclaration->get_name().str() ; string baseName = TransformationSupport::getTypeName(baseType); cout << " The correpsonding basetype is:" << baseName << endl; if(isSgClassType(baseType) == NULL) cout << "It is NOT a CLASS TYPE." << endl; */ ROSE_ASSERT( baseType != NULL ); typedefTranslationTable[typedefDeclaration] = baseType; } } return typedefTranslationTable; } /* End method: buildTypedefTranslationTable */
/* * The function * findScope() * takes as a parameter a SgNode* which is a SgStatement*. It returns a SgNodePtrVector of all * preceding scopes the SgStatement is in. * */ SgNodePtrVector findScopes (SgNode * astNode) { ROSE_ASSERT (isSgStatement (astNode)); SgNodePtrVector returnVector; SgScopeStatement *currentScope; if (isSgScopeStatement (astNode)) { currentScope = isSgScopeStatement (astNode); ROSE_ASSERT (currentScope != NULL); returnVector.push_back (astNode); } else { SgStatement *sageStatement = isSgStatement (astNode); ROSE_ASSERT (sageStatement != NULL); currentScope = sageStatement->get_scope (); ROSE_ASSERT (currentScope != NULL); returnVector.push_back (currentScope); } while (currentScope->variantT () != V_SgGlobal) { currentScope = currentScope->get_scope (); ROSE_ASSERT (currentScope != NULL); returnVector.push_back (currentScope); } //Must also include the Global Scopes of the other files in the project if (currentScope->variantT () == V_SgGlobal) { SgFile *sageFile = isSgFile ((currentScope)->get_parent ()); ROSE_ASSERT (sageFile != NULL); SgProject *sageProject = isSgProject (sageFile->get_parent ()); ROSE_ASSERT (sageProject != NULL); //Get a list of all files in the current project const SgFilePtrList sageFilePtrList = sageProject->get_fileList (); //Iterate over the list of files to find all Global Scopes SgNodePtrVector globalScopes; for (unsigned int i = 0; i < sageFilePtrList.size (); i += 1) { const SgFile *sageFile = isSgFile (sageFilePtrList[i]); ROSE_ASSERT (sageFile != NULL); if( isSgSourceFile(sageFile) != NULL ) { SgGlobal *sageGlobal = isSgSourceFile(sageFile)->get_globalScope (); ROSE_ASSERT (sageGlobal != NULL); returnVector.push_back (sageGlobal); } } } return returnVector; };
POETCode* POETAstInterface::Ast2POET(const Ast& n) { static SgTemplateInstantiationFunctionDecl* tmp=0; SgNode* input = (SgNode*) n; if (input == 0) return EMPTY; POETCode* res = POETAstInterface::find_Ast2POET(input); if (res != 0) return res; { SgProject* sageProject=isSgProject(input); if (sageProject != 0) { int filenum = sageProject->numberOfFiles(); for (int i = 0; i < filenum; ++i) { SgSourceFile* sageFile = isSgSourceFile(sageProject->get_fileList()[i]); SgGlobal *root = sageFile->get_globalScope(); SgDeclarationStatementPtrList declList = root->get_declarations (); POETCode* curfile = ROSE_2_POET_list(declList, 0, tmp); curfile = new POETCode_ext(sageFile, curfile); POETAstInterface::set_Ast2POET(sageFile, curfile); res=LIST(curfile, res); } POETAstInterface::set_Ast2POET(sageProject,res); return res; } } { SgBasicBlock* block = isSgBasicBlock(input); if (block != 0) { res=ROSE_2_POET_list(block->get_statements(), res, tmp); POETAstInterface::set_Ast2POET(block, res); return res; } } { SgExprListExp* block = isSgExprListExp(input); if (block != 0) { res=ROSE_2_POET_list(block->get_expressions(), 0, tmp); POETAstInterface::set_Ast2POET(block, res); return res; } } { SgForStatement *f = isSgForStatement(input); if (f != 0) { POETCode* init = ROSE_2_POET_list(f->get_for_init_stmt()->get_init_stmt(),0, tmp); POETCode* ctrl = new POETCode_ext(f, TUPLE3(init,Ast2POET(f->get_test_expr()), Ast2POET(f->get_increment()))); res = CODE_ACC("Nest", PAIR(ctrl,Ast2POET(f->get_loop_body()))); POETAstInterface::set_Ast2POET(input, res); return res; } } { SgVarRefExp * v = isSgVarRefExp(input); if (v != 0) { res = STRING(v->get_symbol()->get_name().str()); POETAstInterface::set_Ast2POET(input, res); return res; } } { SgMemberFunctionRefExp * v = isSgMemberFunctionRefExp(input); if (v != 0) { res = STRING(v->get_symbol()->get_name().str()); POETAstInterface::set_Ast2POET(input, res); return res; } } { SgIntVal * v = isSgIntVal(input); if (v != 0) { res = ICONST(v->get_value()); POETAstInterface::set_Ast2POET(input, res); return res; } } { SgInitializedName* var = isSgInitializedName(input); if (var != 0) { POETCode* name = STRING(var->get_name().str()); POETCode* init = Ast2POET(var->get_initializer()); res = new POETCode_ext(var, PAIR(name,init)); POETAstInterface::set_Ast2POET(input, res); return res; } } /* { std::string fname; AstInterface::AstList params; AstNodeType returnType; AstNodePtr body; if (AstInterface :: IsFunctionDefinition( input, &fname, ¶ms, (AstInterface::AstList*)0, &body, (AstInterface::AstTypeList*)0, &returnType)) { if (body != AST_NULL) std::cerr << "body not empty:" << fname << "\n"; POETCode* c = TUPLE4(STRING(fname), ROSE_2_POET_list(0,params,0), STRING(AstInterface::GetTypeName(returnType)), Ast2POET(body.get_ptr())); res = new POETCode_ext(input, c); POETAstInterface::set_Ast2POET(input,res); return res; } } */ AstInterface::AstList c = AstInterface::GetChildrenList(input); switch (input->variantT()) { case V_SgCastExp: case V_SgAssignInitializer: res = Ast2POET(c[0]); POETAstInterface::set_Ast2POET(input, res); return res; case V_SgDotExp: { POETCode* v1 = Ast2POET(c[1]); if (dynamic_cast<POETString*>(v1)->get_content() == "operator()") return Ast2POET(c[0]); res = CODE_ACC("Bop",TUPLE3(STRING("."), Ast2POET(c[0]), v1)); return res; } case V_SgLessThanOp: res = CODE_ACC("Bop",TUPLE3(STRING("<"),Ast2POET(c[0]), Ast2POET(c[1]))); POETAstInterface::set_Ast2POET(input, res); return res; case V_SgSubtractOp: res = CODE_ACC("Bop",TUPLE3(STRING("-"),Ast2POET(c[0]), Ast2POET(c[1]))); POETAstInterface::set_Ast2POET(input, res); return res; case V_SgAddOp: res = CODE_ACC("Bop",TUPLE3(STRING("+"),Ast2POET(c[0]), Ast2POET(c[1]))); POETAstInterface::set_Ast2POET(input, res); return res; case V_SgMultiplyOp: res = CODE_ACC("Bop",TUPLE3(STRING("*"),Ast2POET(c[0]), Ast2POET(c[1]))); POETAstInterface::set_Ast2POET(input, res); return res; case V_SgDivideOp: res = CODE_ACC("Bop",TUPLE3(STRING("/"),Ast2POET(c[0]), Ast2POET(c[1]))); POETAstInterface::set_Ast2POET(input, res); return res; case V_SgAssignOp: res = CODE_ACC("Assign",PAIR(Ast2POET(c[0]), Ast2POET(c[1]))); POETAstInterface::set_Ast2POET(input, res); return res; case V_SgFunctionCallExp: res = CODE_ACC("FunctionCall",PAIR(Ast2POET(c[0]), Ast2POET(c[1]))); POETAstInterface::set_Ast2POET(input, res); return res; } POETCode * c2 = 0; if (tmp == 0) tmp=isSgTemplateInstantiationFunctionDecl(input); switch (c.size()) { case 0: break; case 1: c2 = Ast2POET(c[0]); break; case 2: c2 = PAIR(Ast2POET(c[0]),Ast2POET(c[1])); break; case 3: c2 = TUPLE3(Ast2POET(c[0]),Ast2POET(c[1]),Ast2POET(c[2])); break; case 4: c2 = TUPLE4(Ast2POET(c[0]),Ast2POET(c[1]),Ast2POET(c[2]),Ast2POET(c[3])); break; default: //std::cerr << "too many children: " << c.size() << ":" << input->unparseToString() << "\n"; c2 = EMPTY; } if (tmp == input) tmp = 0; res = new POETCode_ext(input, c2); POETAstInterface::set_Ast2POET(input,res); return res; }
void POETAstInterface::unparse(POETCode_ext* n, std::ostream& out, int align) { static SgUnparse_Info info; static Unparser* roseUnparser = 0; static POETCode* linebreak=ASTFactory::inst()->new_string("\n"); static POETCode* comma=ASTFactory::inst()->new_string(","); static bool template_only=false; static POETCode* left_over = 0; SgNode * input = (SgNode*)n->get_content(); POETCode* res = POETAstInterface::find_Ast2POET(input); if (res == n) { if (template_only && input->variantT() == V_SgFunctionDeclaration) { left_over = LIST(n,left_over); } else { std::string res = input->unparseToCompleteString(); out << res; } } else { if (roseUnparser == 0) { /* QY/2013: copied from the global unparseFile to use a different ostream and delegate*/ bool UseAutoKeyword = false; bool generateLineDirectives = true; bool useOverloadedOperators = false; bool num = false; bool _this = true; bool caststring = false; bool _debug = false; bool _class = false; bool _forced_transformation_format = false; bool _unparse_includes = false; Unparser_Opt roseOptions( UseAutoKeyword, generateLineDirectives, useOverloadedOperators, num, _this, caststring, _debug, _class, _forced_transformation_format, _unparse_includes ); roseUnparser = new Unparser(&out, "", roseOptions); } switch (input->variantT()) { case V_SgSourceFile: { SgSourceFile* f = isSgSourceFile(input); info.set_current_scope(f->get_globalScope()); template_only = true; code_gen(out, n->get_children(), 0, 0, align); template_only = false; if (left_over != 0) { code_gen(out, left_over, 0, 0, align); left_over = 0; } break; } case V_SgFunctionDeclaration: if (template_only) { left_over = LIST(n, left_over); break; } case V_SgTemplateInstantiationFunctionDecl: { SgFunctionDeclaration* d = isSgFunctionDeclaration(input); roseUnparser->u_exprStmt->unparseAttachedPreprocessingInfo(d,info,PreprocessingInfo::before); POETCode_ext_delegate repl(n, out); roseUnparser->repl = &repl; roseUnparser->u_exprStmt->unparseFuncDeclStmt(d, info); break; } case V_SgFunctionDefinition: { SgStatement* d = isSgStatement(input); POETCode_ext_delegate repl(n, out); roseUnparser->repl = &repl; roseUnparser->u_exprStmt->unparseStatement(d, info); assert(n->get_children() != n); out << "{"; code_gen(out, linebreak, 0, 0, align + 2); code_gen(out, n->get_children(), 0, linebreak, align+2); code_gen(out, linebreak, 0, 0, align); out << "}"; break; } case V_SgPragmaDeclaration: { out << "#pragma "; POETTuple* c = dynamic_cast<POETTuple*>(n->get_children()); assert(c != 0); code_gen(out, c->get_entry(0)); roseUnparser->cur << " "; roseUnparser->cur.insert_newline(1,align); code_gen(out, c->get_entry(1), 0, 0, align); break; } case V_SgForStatement: { out << "for (" ; POETTuple* c = dynamic_cast<POETTuple*>(n->get_children()); assert(c != 0); code_gen(out, c->get_entry(0)); code_gen(out, c->get_entry(1)); out << ";"; code_gen(out, c->get_entry(2)); out << ")"; break; } case V_SgExprStatement: code_gen(out, n->get_children(), 0, 0, align); out << ";"; break; case V_SgTemplateInstantiationMemberFunctionDecl: break; default: std::cerr << "Unsupported unparsing for : " << input->class_name() << input->unparseToString() << "\n"; //assert(0); } } }
int main(int argc, char** argv) { // DQ (9/1/2006): Introduce tracking of performance of ROSE at the top most level. TimingPerformance timer_main ("Compass performance (main): time (sec) = ",true); std::ios::sync_with_stdio(); // Syncs C++ and C I/O subsystems! if (SgProject::get_verbose() > 0) printf ("In compassMain.C: main() \n"); Rose_STL_Container<std::string> commandLineArray = CommandlineProcessing::generateArgListFromArgcArgv (argc,argv); Compass::commandLineProcessing(commandLineArray); // Read the Compass parameter file (contains input data for all checkers) // This has been moved ahead of the parsing of the AST so that it is more // obvious when it is a problem. Compass::Parameters params(Compass::findParameterFile()); #ifdef ROSE_MPI // Initialize MPI if needed... // need to do this to make test cases pass with MPI. /* setup MPI */ MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &Compass::my_rank); MPI_Comm_size(MPI_COMM_WORLD, &Compass::processes); #endif // Use a modified commandline that inserts specific additional options // to the ROSE frontend to make use with Compass more appropriate. // SgProject* project = frontend(argc,argv); SgProject* project = frontend(commandLineArray); #ifdef HAVE_SQLITE3 std::vector<bool> was_modified; //Determine if any file has been modified since the last run. If so, rerun //the compass checkers. The first run will always run the compass checkers. for (int i = 0; i < project->numberOfFiles(); ++i) { // In each file find all declarations in global scope SgSourceFile* sageFile = isSgSourceFile(project->get_fileList()[i]); std::string filename = sageFile->getFileName(); struct stat file_info; if ( stat(filename.c_str(), &file_info) != 0 ) { std::cerr << "Error: Can not determine last modification time of file " << filename << std::endl; }else{ std::string last_modified = boost::lexical_cast<std::string>(file_info.st_mtime); try { /* Read in from database here */ sqlite3x::sqlite3_command cmd(Compass::con, "SELECT last_modified from file_last_modified where filename=\""+filename+ "\"" ); sqlite3x::sqlite3_reader r = cmd.executereader(); while (r.read()) { std::string last_modified_in_db = r.getstring(0); was_modified.push_back( (last_modified_in_db == last_modified) ? false : true ); } } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;} //Update last modified time in database try{ sqlite3x::sqlite3_command cmd(Compass::con,"DELETE from file_last_modified where filename=\""+filename+ "\""); cmd.executenonquery(); } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;} try{ sqlite3x::sqlite3_command cmd(Compass::con,"INSERT into file_last_modified(filename, last_modified) VALUES(?,?)"); cmd.bind(1,filename); cmd.bind(2,last_modified); cmd.executenonquery(); } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;} }; } //Continue processign iff at least one file was modified if( ( find(was_modified.begin(), was_modified.end(), true) != was_modified.end() ) || (was_modified.size() == 0) ) { //Delete violation entries that correspond to this file for (int i = 0; i < project->numberOfFiles(); ++i) { // In each file find all declarations in global scope SgSourceFile* sageFile = isSgSourceFile(project->get_fileList()[i]); std::string filename = sageFile->getFileName(); try{ sqlite3x::sqlite3_command cmd(Compass::con,"DELETE from violations where filename=\""+filename+ "\""); cmd.executenonquery(); } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;} } //continue processing }else exit(0); #endif #if 0 project->display("In Compass"); #endif std::vector<const Compass::Checker*> traversals; #ifdef USE_QROSE // This is part of incomplete GUI interface for Compass using QRose from Imperial. // Both of these output object work, but one is more useful for QRose. QRoseOutputObject* output = new QRoseOutputObject(); #endif Compass::PrintingOutputObject output(std::cerr); { // Make this in a nested scope so that we can time the buildCheckers function TimingPerformance timer_build ("Compass performance (build checkers and run prerequisites): time (sec) = ",false); buildCheckers(traversals,params,output, project); for ( std::vector<const Compass::Checker*>::iterator itr = traversals.begin(); itr != traversals.end(); itr++ ) { ROSE_ASSERT (*itr); Compass::runPrereqs(*itr, project); } } TimingPerformance timer_checkers ("Compass performance (checkers only): time (sec) = ",false); std::vector<std::pair<std::string, std::string> > errors; for ( std::vector<const Compass::Checker*>::iterator itr = traversals.begin(); itr != traversals.end(); itr++ ) { if ( (*itr) != NULL ) { if (Compass::verboseSetting >= 0) printf ("Running checker %s \n",(*itr)->checkerName.c_str()); try { int spaceAvailable = 40; std::string name = (*itr)->checkerName + ":"; int n = spaceAvailable - name.length(); //Liao, 4/3/2008, bug 82, negative value if (n<0) n=0; std::string spaces(n,' '); TimingPerformance timer (name + spaces + " time (sec) = ",false); (*itr)->run(params, &output); } catch (const std::exception& e) { std::cerr << "error running checker : " << (*itr)->checkerName << " - reason: " << e.what() << std::endl; errors.push_back(std::make_pair((*itr)->checkerName, e.what())); } } // if( (*itr) != NULL ) else { std::cerr << "Error: Traversal failed to initialize" << std::endl; return 1; } // else } // for() // Support for ToolGear if (Compass::UseToolGear == true) { Compass::outputTgui( Compass::tguiXML, traversals, &output ); } #ifdef HAVE_SQLITE3 if (Compass::UseDbOutput == true) { Compass::outputDb( Compass::outputDbName, traversals, &output ); } #endif // Output errors specific to any checkers that didn't initialize properly if (!errors.empty()) { std::cerr << "The following checkers failed due to internal errors:" << std::endl; std::vector<std::pair<std::string, std::string> >::iterator e_itr; for (e_itr = errors.begin(); e_itr != errors.end(); ++e_itr) { std::cerr << e_itr->first << ": " << e_itr->second << std::endl; } } // Just set the project, the report will be generated upon calling the destructor for "timer" timer_main.set_project(project); #ifdef ROSE_MPI MPI_Finalize(); #endif #if 1 // Liao, 2/26/2009, add this backend support to be more friendly to build systems // return backend(project); #else return 0; #endif }
int main ( int argc, char* argv[] ) { if (argc != 3) { std::cerr << "Usage: generate-all-schedule file.c directory" << std::endl; ROSE_ASSERT(false); } SgSourceFile * source_file = isSgSourceFile(SageBuilder::buildFile(argv[1], argv[1])); Rose_STL_Container<SgNode*> pragma_decls = NodeQuery::querySubTree(source_file, V_SgPragmaDeclaration); if (pragma_decls.size() == 1) { SgPragmaDeclaration * pragma_decl = isSgPragmaDeclaration(pragma_decls[0]); try { // Generate polyhedric modelisation PolyhedricAnnotation::parse(pragma_decl); PolyhedricAnnotation::PragmaPolyhedralProgram & polyhedral_program = PolyhedricAnnotation::getPolyhedralProgram<SgPragmaDeclaration, SgExprStatement, RoseVariable>(pragma_decl); // Compute dependency from the generated modelisation std::vector<PolyhedricDependency::PragmaDependency *> * deps = PolyhedricDependency::ComputeRaW<SgPragmaDeclaration, SgExprStatement, RoseVariable>(polyhedral_program); // Generate the space containing all valid schedules for the previously compute dependencies Scheduling::PragmaScheduleSpace schedule_space(polyhedral_program, *deps, Scheduling::PBCC); // Traverse the schedule's space to list the schedules std::vector<Scheduling::PragmaSchedule> * schedules = schedule_space.generateScheduleList(-1, 1, -1, 1, -1, 1); // ********** SgStatement * next_statement = SageInterface::getNextStatement(pragma_decl); SageInterface::removeStatement(next_statement); SgStatement * statement_to_replace = pragma_decl; size_t cnt = 0; std::vector<Scheduling::PragmaSchedule>::iterator it; for (it = schedules->begin(); it != schedules->end(); it++) { std::ostringstream oss; oss << cnt; std::string file_name(argv[1]); size_t point = file_name.find_last_of("."); file_name.insert(point, oss.str()); size_t slash = file_name.find_last_of("/"); source_file->set_unparse_output_filename(std::string(argv[2]) + std::string("/") + file_name.substr(slash+1)); SgBasicBlock * generated_block = CodeGeneration::generateBasicBlockFor(*it); SageInterface::replaceStatement(statement_to_replace, generated_block); statement_to_replace = generated_block; source_file->unparse(); cnt++; } } catch (Exception::ExceptionBase & e) { e.print(std::cerr); } } else { std::cerr << "Need to have one and only one pragma in the program for this." << std::endl; } return 0; }