示例#1
0
int main(int argc, char *argv[])
{
        std::string filename;

    SgProject *project = frontend(argc, argv);
    EDefUse *edu=new EDefUse(project);
    if (edu->run(false)==1)
        {
              std::cerr<<"createFDG:: DFAnalysis failed!   -- edu->run(false)==0"<<endl;
              exit(0);
        }
                std::vector<InterproceduralInfo*> ip;

    list < SgNode * >functionDeclarations = NodeQuery::querySubTree(project, V_SgFunctionDeclaration);

    for (list < SgNode * >::iterator i = functionDeclarations.begin(); i != functionDeclarations.end(); i++)
    {
        ControlDependenceGraph *cdg;
        DataDependenceGraph *ddg;
        InterproceduralInfo *ipi;

        SgFunctionDeclaration *fD = isSgFunctionDeclaration(*i);

        // SGFunctionDefinition * fDef;
        ROSE_ASSERT(fD != NULL);

        // CI (01/08/2007): A missing function definition is an indicator to a 
        // 
        // 
        // librarycall. 
        // * An other possibility would be a programmer-mistake, which we
        // don't treat at this point.  // I assume librarycall
        if (fD->get_definition() == NULL)
        {
        }
        else
        {
            // get the control depenence for this function
                                                ipi=new InterproceduralInfo(fD);

            ROSE_ASSERT(ipi != NULL);
            
            ddg = new DataDependenceGraph(fD->get_definition(),edu);

            // get control dependence for this function defintion
            cdg = new ControlDependenceGraph(fD->get_definition(), ipi);
            cdg->computeAdditionalFunctioncallDepencencies();
                                                cdg->computeInterproceduralInformation(ipi);
//                                              cdg->debugCoutNodeList();
            FunctionDependenceGraph *fdg=new FunctionDependenceGraph(cdg,ddg,ipi);

            filename =
                                                                (fD->get_definition()->get_file_info()->get_filenameString ())
                 + "." +
                (fD->get_name().getString()) + ".fdg.dot";
            fdg->writeDot((char *)filename.c_str());
            
        }   
    }
}
示例#2
0
SgFunctionDeclaration* TestCodeBuilder::buildEventFunction(SgStatement* stmt, int idx)
{
#if 1
    if (SgBasicBlock* block = isSgBasicBlock(stmt))
        ;//return buildEventFunction(block->get_statements(), idx);

    SgFunctionDeclaration* decl = buildEventDeclaration(idx);
    //stmt = buildExprStatement(buildIntVal(0));
    appendStatement(stmt, isSgScopeStatement(decl->get_definition()->get_body()));

    //cout << fixStatement(stmt, isSgScopeStatement(decl->get_definition()->get_body())) << endl;

    //fixVariableReferences(decl->get_definition());
    //cout << fixVariableReferences(decl) << endl;
#else
    // For experiment
    pushScopeStack(isSgScopeStatement(decl->get_definition()->get_body()));
    appendStatement(buildVariableDeclaration("i", buildIntType()));
    appendStatement(
            buildExprStatement(
                buildBinaryExpression<SgAddOp>(
                    int_var_,
                    buildBinaryExpression<SgAssignOp>(
                        int_var_,
                        buildPlusPlusOp(
                            int_var_,
                            SgUnaryOp::prefix)))));
    popScopeStack();

#endif
    return decl;
}
示例#3
0
int main(int argc, char *argv[])
{
    std::string filename;

    SgProject *project = frontend(argc, argv);
    std::vector<InterproceduralInfo*> ip;

// list < SgNode * >functionDeclarations = NodeQuery::querySubTree(project, V_SgFunctionDeclaration);
    NodeQuerySynthesizedAttributeType functionDeclarations = NodeQuery::querySubTree(project, V_SgFunctionDeclaration);

// for (list < SgNode * >::iterator i = functionDeclarations.begin(); i != functionDeclarations.end(); i++)
    for (NodeQuerySynthesizedAttributeType::iterator i = functionDeclarations.begin(); i != functionDeclarations.end(); i++)
    {
        ControlDependenceGraph *cdg;
        InterproceduralInfo *ipi;

        SgFunctionDeclaration *fD = isSgFunctionDeclaration(*i);

        // SGFunctionDefinition * fDef;
        ROSE_ASSERT(fD != NULL);

        // CI (01/08/2007): A missing function definition is an indicator to a
        //
        //
        // librarycall.
        // * An other possibility would be a programmer-mistake, which we
        // don't treat at this point.  // I assume librarycall
        if (fD->get_definition() == NULL)
        {
        }
        else
        {
            // get the control depenence for this function
            ipi=new InterproceduralInfo(fD);

            ROSE_ASSERT(ipi != NULL);

            // get control dependence for this function defintion
            cdg = new ControlDependenceGraph(fD->get_definition(), ipi);
            cdg->computeAdditionalFunctioncallDepencencies();
//						cdg->computeInterproceduralInformation(ipi);
//						cdg->debugCoutNodeList();

// Liao, Feb. 7/2008,
//strip off absolute path to avoid polluting the source tree with generated .dot files
            filename = StringUtility::stripPathFromFileName((fD->get_definition()->get_file_info()->get_filenameString ()))
                       + "." +
                       (fD->get_name().getString()) + ".cdg.dot";
            cdg->writeDot((char *)filename.c_str());

        }
    }
}
int main(int argc, char *argv[]) {
  
  struct timeval t1, t2;
  SgProject* proj = frontend(argc,argv);
  ROSE_ASSERT (proj != NULL); 

  SgFunctionDeclaration* mainDefDecl = SageInterface::findMain(proj);

  SgFunctionDefinition* mainDef = mainDefDecl->get_definition(); 
   visitorTraversal* vis = new visitorTraversal();
    StaticCFG::CFG cfg(mainDef);
   //cfg.buildFullCFG();
    stringstream ss;
    string fileName= StringUtility::stripPathFromFileName(mainDef->get_file_info()->get_filenameString());
    string dotFileName1=fileName+"."+ mainDef->get_declaration()->get_name() +".dot";

    cfgToDot(mainDef,dotFileName1); 
    //cfg->buildFullCFG();
    SgIncidenceDirectedGraph* g = new SgIncidenceDirectedGraph();
    g = cfg.getGraph();
    myGraph* mg = new myGraph();
    mg = instantiateGraph(g, cfg);
    vis->tltnodes = 0;
    vis->paths = 0;
    //vis->firstPrepGraph(constcfg);
    t1 = getCPUTime();
    vis->constructPathAnalyzer(mg, true, 0, 0, true);
    t2 = getCPUTime();
    std::cout << "took: " << timeDifference(t2, t1) << std::endl;
    //cfg.clearNodesAndEdges();
    std::cout << "finished" << std::endl;
    std::cout << "tltnodes: " << vis->tltnodes << " paths: " << vis->paths << std::endl;
    delete vis;
}
示例#5
0
void visitorTraversal::analyzePath(vector<VertexID>& pth) {
    std::vector<VertexID> pathR = pth;
    std::vector<SgGraphNode*> path;
    for (unsigned int j = 0; j < pathR.size(); j++) {
        SgGraphNode* R = (*orig)[pathR[j]].sg;
        path.push_back(R);
    }
    for (unsigned int k = 0; k < path.size(); k++) {
        if (isSgFunctionRefExp(path[k]->get_SgNode())) {
            SgFunctionRefExp* sfrd = isSgFunctionRefExp(path[k]->get_SgNode());
            SgFunctionDeclaration* fd = sfrd->getAssociatedFunctionDeclaration();
            fd = isSgFunctionDeclaration(fd->get_definingDeclaration());
            assert(fd!=NULL);
            SgFunctionDefinition* fdd = fd->get_definition();
            SgName sname = fdd->get_mangled_name();
            string sn = sname.getString();
            if (find(defstr.begin(), defstr.end(), sn) == defstr.end()) {
                defstr.push_back(sn);
                defs.push_back(fdd);
                std::cout << "found new sn: " << sn << std::endl;
            }
            else {
                std::cout << "found old sn: " << sn << std::endl;
            }
        }
    }
#pragma omp atomic
    paths++;
}
示例#6
0
int main(int argc, char * argv[])
{
  SgProject *project = frontend (argc, argv);
  SgFunctionDeclaration* func = SageInterface::findMain(project);
  ROSE_ASSERT(func != NULL);

  SgBasicBlock* body = func->get_definition()->get_body();

  SgStatement* stmt = SageInterface::getFirstStatement(body);
  ROSE_ASSERT(stmt != NULL);

  SgInitializedName* ivar=NULL ;
  SgExpression *lb=NULL, *ub=NULL, *step=NULL;
  bool isIncremental; 
  SgStatement* lbody=NULL;
  if (SageInterface::isCanonicalForLoop(stmt,&ivar, &lb, &ub, &step, &lbody, &isIncremental))
  {
    cout<<"Found a canonical for loop: "<<endl;
    cout<<"loop index variable is:"<<ivar->unparseToString()
      <<"\n bound 1 is:"<<lb->unparseToString()
      <<"\n bound 2 is:"<<ub->unparseToString()
      <<"\n step is:"<<step->unparseToString()
      <<"\n body is:"<<lbody->unparseToString()
      <<"\n iteration is incremental:"<<isIncremental
      <<endl;
  }
  return backend(project);
}
示例#7
0
SgFunctionDeclaration* TestCodeBuilder::buildEventFunction(const vector<SgStatement*> stmts, int idx)
{
    SgFunctionDeclaration* decl = buildEventDeclaration(idx);
    pushScopeStack(isSgScopeStatement(decl->get_definition()->get_body()));
    foreach (SgStatement* stmt, stmts) appendStatement(stmt);
    popScopeStack();
    return decl;
}
示例#8
0
int main(int argc, char *argv[])
{
        std::string filename;

        SgProject *project = frontend(argc, argv);
        // Create the global def-use analysis
        DFAnalysis *defUseAnalysis=new DefUseAnalysis(project);
        if (defUseAnalysis->run(false)==1)
        {
                std::cerr<<"newDU:: DFAnalysis failed!  defUseAnalysis->run()==0"<<endl;
                exit(0);
        }
        std::vector<InterproceduralInfo*> ip;

        list < SgNode * >functionDeclarations = NodeQuery::querySubTree(project, V_SgFunctionDeclaration);

        for (list < SgNode * >::iterator i = functionDeclarations.begin(); i != functionDeclarations.end(); i++)
        {
                DataDependenceGraph *ddg;
                InterproceduralInfo *ipi;

                SgFunctionDeclaration *fD = isSgFunctionDeclaration(*i);

                // SGFunctionDefinition * fDef;
                ROSE_ASSERT(fD != NULL);

                // CI (01/08/2007): A missing function definition is an indicator to a 
                // 
                // 
                // librarycall. 
                // * An other possibility would be a programmer-mistake, which we
                // don't treat at this point.  // I assume librarycall
                if (fD->get_definition() == NULL)
                {
                }
                else
                {
                        cout <<"--------------------------------------------------------------"<<endl;
                        analyseFunction(fD->get_definition(),defUseAnalysis);

                }   
        }
        return 0;
}
int main(int argc, char** argv) {
	SgProject* proj = frontend(argc,argv);
	SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj);
	SgFunctionDefinition* mainDef = mainDecl->get_definition();
	std::vector<SgNode*> ifExps;
	ifExps = NodeQuery::querySubTree(mainDef, V_SgIfStmt);
	for (int i = 0; i < ifExps.size(); i++) {
		getIfConds(isSgIfStmt(ifExps[i]), isSgScopeStatement(mainDef));
	}
	
	std::vector<SgNode*> assignNodes = NodeQuery::querySubTree(mainDef, V_SgVariableDeclaration);
	std::cout << assignNodes.size() << " nodes found" << std::endl;
	std::vector<SgBinaryOp*> bin_ops;
	std::vector<SgUnaryOp*> un_ops;
	std::vector<SgNode*> other;
	std::vector<SgExpression*> results;
	for (std::vector<SgNode*>::iterator i = assignNodes.begin(); i != assignNodes.end(); i++) {
	
		SgVariableDeclaration* vdecl = isSgVariableDeclaration(*i);
		SgInitializedNamePtrList vlst = vdecl->get_variables();
		SgInitializedName* initName = isSgInitializedName((*(vlst.begin())));
		SgExpression* exp = isSgAssignInitializer(initName->get_initializer())->get_operand();
		std::cout << exp->class_name() << std::endl;
		if (!isSgFunctionCallExp(exp)) {
			getExps(exp, isSgInitializedName(*i), results, 0);
		
	
	std::cout << "prefixes" << std::endl;
	for (int j = 0; j < prefixes.size(); j++) {
	        SgExprStatement* expSt = SageBuilder::buildExprStatement_nfi(prefixes[j]);
		SageInterface::insertStatement(isSgVariableDeclaration(*i),expSt,true);
		
		std::cout << prefixes[j]->class_name() << std::endl;
	}
	std::cout << "results" << std::endl;
	for (int j = 0; j < results.size(); j++) {
		std::cout << results[j]->class_name() << std::endl;
	}
	std::cout << "postfixes" << std::endl;
	for (int j = 0; j < postfixes.size(); j++) {
		SgExprStatement* expSt = SageBuilder::buildExprStatement_nfi(postfixes[j]);
                SageInterface::insertStatement(isSgVariableDeclaration(*i),expSt,false);
		std::cout << postfixes[j]->class_name() << std::endl;
	}
	
	replaceExps(exp,vdecl);
	simplifyExps(exp);
	}
		
	}
			
	backend(proj);
	return 0;
}
示例#10
0
int
main ( int argc,  char * argv[] )
   {

     if (argc <= 1) {
         PrintUsage(argv[0]);
         return -1;
     }

     SgProject sageProject ( (int)argc,argv);

     SageInterface::changeAllBodiesToBlocks(&sageProject);

    CmdOptions::GetInstance()->SetOptions(argc, argv);

   int filenum = sageProject.numberOfFiles();
   for (int i = 0; i < filenum; ++i) {
      SgSourceFile* sageFile = isSgSourceFile(sageProject.get_fileList()[i]);
      ROSE_ASSERT(sageFile != NULL);

      TestCFGWrap::AnalysisDomain t = UseOA(argc, argv)? TestCFGWrap::OA : TestCFGWrap::ROSE;
      string filename = sageFile->getFileName();

#if 0 // Test harness uses stdout rather than a temporary file
      string txtname = filename.substr(filename.rfind('/')+1) + ".outx"; 
      TestCFGWrap_Text txtop(t,txtname);
#else
      TestCFGWrap_Stdout txtop(t);
#endif
      //string dotname = string(strrchr(sageFile.getFileName(),'/')+1) + ".dot";
      string dotname = filename.substr(filename.rfind('/')+1) + ".dot";
      TestCFGWrap_DOT dotop(t);
     SgGlobal *root = sageFile->get_globalScope();
     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;
          SgNode* stmts = defn;
          if (GenerateDOT(argc, argv)) {
             dotop(stmts, dotname);
          }
          else {
             txtop(stmts);
          }
     }
   }

  return 0;
}
void
Traversal::processNode(SgNode* n, SynthesizedAttribute& synthesizedAttribute )
  {
    // Look for names of functions
    SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(n);
    if (functionDeclaration != NULL)
    {
        string name = functionDeclaration->get_name().str();

        #if DEBUG > 3
          SgFunctionDefinition* functionDefinition =
              functionDeclaration->get_definition();
          if (functionDefinition != NULL)
              printf ("SgFunctionDefinition: %s \n",name.c_str());
          else
              printf ("SgFunctionDeclaration: %s \n",name.c_str());
        #endif

        synthesizedAttribute.nameList.push_back(
            NameStructureType(name,n));
        // nameSet.insert(name);
    }

    SgInitializedName* initializedName = isSgInitializedName(n);
    if (initializedName != NULL)
    {
        string name = initializedName->get_name().str();

        #if DEBUG > 3
          printf ("SgInitializedName: %s \n",name.c_str());
        #endif

        synthesizedAttribute.nameList.push_back(
            NameStructureType(name,n));
        // nameSet.insert(name);
    }

    SgNamespaceDeclarationStatement* namespaceDeclaration = isSgNamespaceDeclarationStatement(n);
    if (namespaceDeclaration != NULL)
    {
        string name = namespaceDeclaration->get_name().str();

        #if DEBUG > 3
          printf ("SgNamespaceDeclaration: %s \n",name.c_str());
        #endif

        synthesizedAttribute.nameList.push_back(
            NameStructureType(name,n));
        // nameSet.insert(name);
    }
  }
示例#12
0
void Jovial_to_C::translateProgramHeaderStatement(SgProgramHeaderStatement* programHeaderStatement)
{
// Get scopeStatement from SgProgramHeaderStatement
   SgScopeStatement* scopeStatement = programHeaderStatement->get_scope();
   ROSE_ASSERT(scopeStatement);
  
// Get ParameterList and DecoratorList
   SgFunctionParameterList* functionParameterList = buildFunctionParameterList(); 
   SgExprListExp* decoratorList = deepCopy(programHeaderStatement->get_decoratorList());
  
// Reuse FunctionDefinition from Fortran programHeaderStatement
   SgFunctionDefinition* functionDefinition = programHeaderStatement->get_definition();
  
// Get basicBlock from SgProgramHeaderStatement
   SgBasicBlock* basicBlock = functionDefinition->get_body();
   ROSE_ASSERT(basicBlock);

   SgSymbolTable* symbolTable = basicBlock->get_symbol_table();
   ROSE_ASSERT(symbolTable);
  
// The main function return type is int
   SgType* mainType = SgTypeInt::createType();
  
// Remove original function symbol.  Keep the new function symbol with name of "main"
   SgFunctionSymbol* functionSymbol = isSgFunctionSymbol(scopeStatement->lookup_symbol(programHeaderStatement->get_name()));
   SgSymbolTable* globalSymbolTable = isSgSymbolTable(functionSymbol->get_parent());
   globalSymbolTable->remove(functionSymbol);
   functionSymbol->set_parent(NULL);
   delete(functionSymbol);
  
// Create SgFunctionDeclaration for C main function. Name must be "main".
   SgFunctionDeclaration* cFunctionDeclaration = buildDefiningFunctionDeclaration("main",
                                                                                  mainType,
                                                                                  functionParameterList,
                                                                                  scopeStatement);
  
// Setup the C function declaration.
   removeList.push_back(cFunctionDeclaration->get_definition());
   functionDefinition->set_parent(cFunctionDeclaration);
   cFunctionDeclaration->set_definition(functionDefinition);
   programHeaderStatement->set_definition(NULL);
 
// Replace the SgProgramHeaderStatement with SgFunctionDeclaration.
   replaceStatement(programHeaderStatement,cFunctionDeclaration,true);
   cFunctionDeclaration->set_decoratorList(decoratorList);
// cFunctionDeclaration->set_startOfConstruct(functionDefinition->get_startOfConstruct());
// cFunctionDeclaration->set_endOfConstruct(functionDefinition->get_endOfConstruct());
// cFunctionDeclaration->get_file_info()->set_physical_filename(cFunctionDeclaration->get_file_info()->get_filenameString()); 
  
   programHeaderStatement->set_parent(NULL);
}  // End of Jovial_to_C::translateProgramHeaderStatement
示例#13
0
int
main ( int argc,  char * argv[] )
   {

     if (argc <= 1) {
         PrintUsage(argv[0]);
         return -1;
     }

     SgProject sageProject ( (int)argc,argv);
     SageInterface::changeAllBodiesToBlocks(&sageProject);
    CmdOptions::GetInstance()->SetOptions(argc, argv);


   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();
     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;
          SgBasicBlock *stmts = defn->get_body();  
          AstInterfaceImpl scope(stmts);
          AstInterface fa(&scope);
          StmtVarAliasCollect alias;
          alias(fa, AstNodePtrImpl(defn));
          if (GenerateDOT(argc, argv)) {
             string name = string(strrchr(sageFile->getFileName().c_str(),'/')+1) + ".dot";
             TestDUWrap_DOT op(alias);
             op(fa, defn, name);
          }
          else {
             string name = string(strrchr(sageFile->getFileName().c_str(),'/')+1) + ".outx";
#if 0   // Test harness uses stdout now rather than a temporary file [Robb P. Matzke 2013-02-25]
             TestDUWrap_Text op(alias,name);
#else
             TestDUWrap_Stdout op(alias);
#endif
             op(fa, defn);
          }
     }
   }

  return 0;
}
示例#14
0
文件: interp_extcall.C 项目: 8l/rose
ValueP ExternalCallingStackFrame::evalFunctionRefExp(SgFunctionSymbol *sym)
   {
     SgFunctionDeclaration *decl = sym->get_declaration();
     SgFunctionDeclaration *defDecl = isSgFunctionDeclaration(decl->get_definingDeclaration());
     if (defDecl == NULL)
        {
          return externEvalFunctionRefExp(sym);
        }
     SgFunctionDefinition *def = defDecl->get_definition();
     if (def == NULL)
        {
          return externEvalFunctionRefExp(sym);
        }

     return StackFrame::evalFunctionRefExp(sym);
   }
示例#15
0
/*
 * Main Function
 */
int main(int argc, char * argv[]) {
	// Build the AST used by ROSE
	SgProject* sageProject = frontend(argc, argv);

	// For each source file in the project
	SgFilePtrList & ptr_list = sageProject->get_fileList();
	for (SgFilePtrList::iterator iter = ptr_list.begin(); iter
			!= ptr_list.end(); iter++) {
		SgFile* sageFile = (*iter);
		SgSourceFile * sfile = isSgSourceFile(sageFile);
		ROSE_ASSERT(sfile);
		SgGlobal *root = sfile->get_globalScope();
		SgDeclarationStatementPtrList& declList = root->get_declarations();

		// Insert header file
		insertHeader(sfile);

		//For each function body in the scope
		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;
			//ignore functions in system headers, Can keep them to test robustness
			if (defn->get_file_info()->get_filename()
					!= sageFile->get_file_info()->get_filename())
				continue;
			SgBasicBlock *body = defn->get_body();
			ROSE_ASSERT(body);

			vector<SgForStatement*> loops = querySubTree<SgForStatement> (defn,
					V_SgForStatement);
			if (loops.size() == 0)
				continue;

			visitLoops(loops);
		}

		// Generate source code from AST and call the vendor's compiler
		return backend(sageProject);
	}

}
int main(int argc, char* argv[]) {
	std::vector<std::string> pragma_values;
	SgProject* proj = frontend(argc,argv);
	ROSE_ASSERT(proj != NULL);
	SgFunctionDeclaration* mainDefDecl = SageInterface::findMain(proj);
	SgFunctionDefinition* mainDef = mainDefDecl->get_definition();
	
	Rose_STL_Container<SgNode*> pragmaList = NodeQuery::querySubTree(proj,V_SgPragmaDeclaration);
	for (Rose_STL_Container<SgNode*>::iterator i = pragmaList.begin(); i != pragmaList.end(); i++) {
		SgPragmaDeclaration* prg = isSgPragmaDeclaration(*i);
		std::string prag_string = get_pragma_string(prg);
		if (isSMTGeneral(prag_string)) {
			std::string parsed = parseSMTGeneral(prag_string);
			std::cout << ";;SMTGeneral command found: " << parsed << std::endl;
			//continue;
		}
		else {
		//std::cout << "SMTGeneral command not found" << std::endl;
		std::string pos;
		pos = get_position(prag_string);
		if (pos == "define") {
			std::cout << "define:\n";
			std::vector<std::pair<std::string, std::string> > pragma_values = get_vars(prag_string);
			for (std::vector<std::pair<std::string,std::string> >::iterator j = pragma_values.begin(); j != pragma_values.end(); j++) {
				std::cout << (*j).first << " " << (*j).second << std::endl;
			}
			
		}
		else if (pos == "assume") {
			std::cout << "assume:\n";
			std::vector<std::string> assumptions = get_assumptions(prag_string);
			for (std::vector<std::string>::iterator i = assumptions.begin(); i != assumptions.end(); i++) {
				std::cout << (*i) << std::endl;
			}	
		}
		else if (pos == "begin" || pos == "end") {
			std::cout << "position: " << pos << std::endl;
		}
		else {
			ROSE_ASSERT(false);
		}
		}
	}
	return 0;
}	
int
main ( int argc, char * argv[] )
   {
     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT(project != NULL);
     SgGlobal *globalScope = getFirstGlobalScope (project);

 //push global scope into stack
     pushScopeStack (isSgScopeStatement (globalScope));

 // Create a parameter list with a parameter
    SgName var1_name = "var_name";
    SgReferenceType *ref_type = buildReferenceType(buildIntType());
    SgInitializedName *var1_init_name = buildInitializedName(var1_name, ref_type);
    SgFunctionParameterList* parameterList = buildFunctionParameterList();
    appendArg(parameterList,var1_init_name);

 // Create a defining functionDeclaration (with a function body)
    SgName func_name                    = "my_function";
    SgFunctionDeclaration * func        = buildDefiningFunctionDeclaration 
                  (func_name, buildIntType(), parameterList);
    SgBasicBlock*  func_body    = func->get_definition()->get_body();

 // push function body scope into stack
    pushScopeStack(isSgScopeStatement(func_body));

 // build a statement in the function body
    SgVarRefExp *var_ref = buildVarRefExp(var1_name);
    SgPlusPlusOp *pp_expression = buildPlusPlusOp(var_ref);
    SgExprStatement* new_stmt = buildExprStatement(pp_expression);
                     
 // insert a statement into the function body
    appendStatement(new_stmt);
//  pop function body off the stack
    popScopeStack();
    
//  insert the function declaration into the scope at the top of the scope stack    
    prependStatement(func);
    popScopeStack();

    AstTests::runAllTests(project);
    return backend(project);
 }
示例#18
0
文件: get_struct.cpp 项目: 8l/rose
int main(int argc, char* argv[]) {
	SgProject* proj = frontend(argc,argv);
	SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj);
	SgFunctionDefinition* mainDef = mainDecl->get_definition();
//	std::vector<SgNode*> dotExps = NodeQuery::querySubTree(mainDef, V_SgDotExp);
	std::vector<SgNode*> varRefs = NodeQuery::querySubTree(mainDef,V_SgVarRefExp);
	int classExps = 0;
	for (unsigned int i = 0; i < varRefs.size(); i++) {
		if (isSgClassType(isSgVarRefExp(varRefs[i])->get_type())) {
			SgClassType* ct = isSgClassType(isSgVarRefExp(varRefs[i])->get_type());
			std::cout << "name of ref: " << isSgVarRefExp(varRefs[i])->get_symbol()->get_name().getString() << std::endl;
			if (SageInterface::isStructType(ct)) {
			SgDeclarationStatement* decl = isSgType(ct)->getAssociatedDeclaration();
			SgDeclarationStatement* defining_decl = decl->get_definingDeclaration();
			if (!(defining_decl->isNameOnly())) {	
				if (isSgClassDeclaration(defining_decl)) {
				if (isSgClassDeclaration(defining_decl)->get_definition()) {
				SgDeclarationStatementPtrList member_stats = isSgClassDeclaration(defining_decl)->get_definition()->get_members();
				SgDeclarationStatementPtrList::iterator j = member_stats.begin();
				for (; j != member_stats.end(); j++) {
					SgDeclarationStatement* d = isSgDeclarationStatement(*j);
					std::cout << "decl stat name: " << d->class_name() << std::endl;
					SgInitializedNamePtrList init_lst = isSgVariableDeclaration(d)->get_variables();
					SgInitializedNamePtrList::iterator k = init_lst.begin();
					std::cout << "variables in initialized name ptr list..." << std::endl;
					for (; k != init_lst.end(); k++) {
						std::cout << isSgInitializedName(*k)->get_name().getString() << std::endl;
						std::cout << isSgInitializedName(*k)->get_type()->class_name() << std::endl;
					}
				}
					
				classExps+=1;
				}
				}
			}
			
			
			}
		}
	}	
	std::cout << "num class_exp: " << classExps << std::endl;
	return 0;
}	
示例#19
0
int main(int argc, char** argv) {
	SgProject* proj = frontend(argc,argv);
	SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj);
	SgFunctionDefinition* mainDef = mainDecl->get_definition();
	std::vector<SgNode*> unaryOpNodes = NodeQuery::querySubTree(mainDef,V_SgUnaryOp);
	for (int i = 0; i < unaryOpNodes.size(); i++) {
		std::cout << unaryOpNodes[i]->class_name() << std::endl;
		SgUnaryOp::Sgop_mode m  = isSgUnaryOp(unaryOpNodes[i])->get_mode();	
			
		if (m == 0) {
			std::cout << "prefix" << std::endl;
		}
		else if (m == 1) { 
			std::cout << "postfix" << std::endl;
		}
		else {
			std::cout << "Neither post nor prefix" << std::endl; 
		}
	}
	return 0;
}		
示例#20
0
int
main ( int argc,  char * argv[] )
   {
int a;
     if (argc <= 1) {
         PrintUsage(argv[0]);
         return -1;
     }
	DEBUG_ICFG = 1;
	DEBUG_STMT = 0;

    SgProject sageProject ( argc,argv);
    SageInterface::changeAllBodiesToBlocks(&sageProject);
    CmdOptions::GetInstance()->SetOptions(argc, argv);


  // TestPtrAnal op;
  //
   ptr_Anal_ICFG_Creator op;
   int filenum = sageProject.numberOfFiles();
   for (int i = 0; i < filenum; ++i) {
     SgFile &sageFile = sageProject.get_file(i);
     SgGlobal *root = sageFile.get_root();
     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);
     }
   }
   op.draw("out.jpg");
  return 0;
}
int main(int argc, char *argv[]) 
{
  // Build the AST used by ROSE
  SgProject* proj = frontend(argc,argv);
  ROSE_ASSERT (proj != NULL); 

  SgFunctionDeclaration* mainDefDecl = SageInterface::findMain(proj);
  ROSE_ASSERT (mainDefDecl != NULL); 

  SgFunctionDefinition* mainDef = mainDefDecl->get_definition();
  ROSE_ASSERT (mainDef != NULL); 

  string fileName= StringUtility::stripPathFromFileName(mainDef->get_file_info()->get_filenameString());
  string dotFileName1=fileName+"."+ mainDef->get_declaration()->get_name() +".IPCFG.dot";

  StaticCFG::InterproceduralCFG cfg(mainDef);

  // Dump out the full CFG, including bookkeeping nodes
  cfg.cfgToDot(mainDef, dotFileName1);

  return 0;
}
示例#22
0
void visitorTraversal::visit(SgNode* n)
   {
     SgFunctionDeclaration* functionDeclaration = isSgFunctionDeclaration(n);
     if (functionDeclaration != NULL)
        {
          SgFunctionDefinition* functionDefinition = functionDeclaration->get_definition();
          if (functionDefinition != NULL)
             {
               SgBasicBlock* functionBody = functionDefinition->get_body();
               ROSE_ASSERT(functionBody != NULL);

               ControlFlowGraph controlflow;

            // The CFG can only be called on a function definition (at present)
               makeCfg(functionDefinition,controlflow);
               string fileName = functionDeclaration->get_name().str();
               fileName += ".dot";
               ofstream dotfile(fileName.c_str());
               printCfgAsDot(dotfile, controlflow);
             }
        }
   }
示例#23
0
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[])

{
  SgProject *project = frontend (argc, argv);
  SgFunctionDeclaration* func = SageInterface::findMain(project);
  ROSE_ASSERT(func != NULL);
  SgBasicBlock* body = func->get_definition()->get_body();
  ROSE_ASSERT(body!= NULL);
  Rose_STL_Container<SgNode*> loops = NodeQuery::querySubTree(body,V_SgFortranDo);

  for (size_t i=0; i< loops.size(); i++)
  {
    SgFortranDo* cloop = isSgFortranDo(loops[i]);
    ROSE_ASSERT(cloop != NULL);
    bool result=false;
    result = SageInterface::doLoopNormalization(cloop);
    ROSE_ASSERT(result != false);
  }
  // run all tests
  AstTests::runAllTests(project);

  // Generate source code from AST and call the vendor's compiler
  return backend(project);
}
示例#25
0
int
main ( int argc,  char * argv[] )
{
  // Initialize and check compatibility. See rose::initialize
  ROSE_INITIALIZE;

  if (argc <= 1) {
      PrintUsage(argv[0]);
      return -1;
  }
  vector<string> argvList(argv, argv + argc);
  CmdOptions::GetInstance()->SetOptions(argvList);
  AssumeNoAlias aliasInfo;
  LoopTransformInterface::cmdline_configure(argvList);
  LoopTransformInterface::set_aliasInfo(&aliasInfo);

#ifdef USE_OMEGA
  DepStats.SetFileName(buffer.str());
#endif

  OperatorSideEffectAnnotation *funcInfo = 
         OperatorSideEffectAnnotation::get_inst();
  funcInfo->register_annot();
  ReadAnnotation::get_inst()->read();
  if (DebugAnnot())
     funcInfo->Dump();
  LoopTransformInterface::set_sideEffectInfo(funcInfo);
  SgProject *project = new SgProject ( argvList);

   int filenum = project->numberOfFiles();
   for (int i = 0; i < filenum; ++i) {
  // SgFile &sageFile = sageProject->get_file(i);
  // SgGlobal *root = sageFile.get_root();
     SgSourceFile* file = isSgSourceFile(project->get_fileList()[i]);
     SgGlobal *root = file->get_globalScope();
     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;
          SgBasicBlock *stmts = defn->get_body();  
          AstInterfaceImpl faImpl = AstInterfaceImpl(stmts);
          LoopTransformInterface::TransformTraverse(faImpl, AstNodePtrImpl(stmts));

       // JJW 10-29-2007 Adjust for iterator invalidation and possible changes to declList
          p = std::find(declList.begin(), declList.end(), func);
          assert (p != declList.end());
     }
   }

   if (CmdOptions::GetInstance()->HasOption("-fd")) {
       simpleIndexFiniteDifferencing(project);
   }

   if (CmdOptions::GetInstance()->HasOption("-pre")) {
       PRE::partialRedundancyElimination(project);
   }
#ifdef USE_OMEGA
     DepStats.SetDepChoice(0x1 | 0x2 | 0x4);
     DepStats.PrintResults();
#endif
  //Qing's loop transformations are not robust enough to pass all tests.
   //AstTests::runAllTests(sageProject);
   unparseProject(project);
   if (GenerateObj())
      return project->compileOutput();
   return 0;
}
示例#26
0
文件: traceCPU.C 项目: 8l/rose
int main (int argc, char *argv[])
{
   /* indicate whether include files need to be added */
   bool loopTransformApplied = false ;

   /* more bools at top of file... */
   bool withPAPI = false ;
   bool showStats = false ;
   bool enablePostProcessing = false ;

   /***********************************************/
   /* Process command line options                */
   /***********************************************/

   Rose_STL_Container<string> cmdLineArgs =
     CommandlineProcessing::generateArgListFromArgcArgv(argc,argv) ;

   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "(s|stats)", true) )
   {
     showStats = true ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "(p|papi)", true) )
   {
     withPAPI = true ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "(l|loops)", true) )
   {
     emitSeqSeg = false ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "noiter", true) )
   {
     countIters = false ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "fast", true) )
   {
     fullLoopStat = false ;
     emitSeqSeg   = false ;
     countIters   = false ;
     withPAPI     = false ;
     enablePostProcessing = true ;
   }

   dumpFunc = (showStats ? "ET_LogStats" : "ET_Dump") ;

   /***********************************************/
   /*               Invoke ROSE                   */
   /***********************************************/

   /* build AST */
   SgProject* project = frontend(argc, argv);
   ROSE_ASSERT(project);

   if (project->get_fileList().empty() == false) {

     /* make sure AST is well formed */
     AstTests::runAllTests(project);

     /* set up some needed typedefs for runtime support */

     SgGlobal *globalScope = SageInterface::getFirstGlobalScope(project) ;
     ETtype = buildTypedefDeclaration("ET_Idx_t", buildShortType(), globalScope)->get_type() ;

     /* insert probes into each function in this file */

     Rose_STL_Container<SgNode*> funcDefs =
         NodeQuery::querySubTree(project, V_SgFunctionDefinition) ;

     for (Rose_STL_Container<SgNode*>::iterator f_itr = funcDefs.begin();
                f_itr != funcDefs.end(); ++f_itr)
     {
        SgFunctionDefinition *funcDef = isSgFunctionDefinition(*f_itr) ;
        ROSE_ASSERT(funcDef);

#ifdef ET_DEBUG 
        printf("--- %s ---\n", funcDef->get_qualified_name().str()) ;
#endif

        SgBasicBlock *funcBody = funcDef->get_body() ;
        if (funcBody == NULL)
           continue ;  /* should be impossible to get here... */

        SgFunctionDeclaration *funcDecl = funcDef->get_declaration() ;
        ROSE_ASSERT(funcDecl);

        /* don't transform header file code  */
        if (strstr(funcDecl->get_name().str(), "operator"))
           continue ;

#ifdef ET_DEBUG
        printf("--- %s ---\n", funcDecl->get_name().str()) ;
#endif

        int loopCount = 0 ;  /* used to create local variable names */
        int segCount = 0 ;

        TransformFunction(funcDecl, funcBody, funcBody, &loopCount, &segCount) ;

        if (loopCount != 0)
        {
           loopTransformApplied = true ;
        }
     }

     SgFunctionDeclaration *mainFunc = SageInterface::findMain(project) ;
     if (countIters == false && (loopTransformApplied || mainFunc != NULL)) {
        SageInterface::attachArbitraryText(globalScope,
           std::string("#define ET_NO_COUNT_ITERS 1\n")) ;
     }

     /* files containing at least one loop require run-time support */

     if (loopTransformApplied)
     {
        SageInterface::attachArbitraryText(globalScope,
           std::string("#include \"ETrt.h\"\n")) ;
     }

     /* fold run-time support code into file containing main() */

     if (mainFunc != NULL)
     {

        SgFunctionDefinition *mainFuncDef = mainFunc->get_definition() ;

        /* include ETrt.c just before main() in this file */
        if (!fullLoopStat) {
          SageInterface::attachArbitraryText(globalScope,
             std::string("#define ET_SIMPLE_LOOP_STATS 1\n") );
        }
        if (enablePostProcessing) {
          SageInterface::attachArbitraryText(globalScope,
             std::string("#define ET_POST_PROCESS_SEQ_TO_LOOP 1\n") );
        }
        if (withPAPI) {
          SageInterface::attachArbitraryText(globalScope,
             std::string("#define ET_PAPI 1\n\n") );
        }
        SageInterface::attachArbitraryText(globalScope,
           std::string("#include \"ETrt.c\"\n") );

        if (withPAPI) {
           /* Insert PAPI initialization code at top of main */
           SgBasicBlock *mainBody = mainFuncDef->get_body() ;

           Rose_STL_Container<SgNode*> blockStmts =
               NodeQuery::querySubTree(mainBody, V_SgStatement,
                                       AstQueryNamespace::ChildrenOnly) ;

           for (Rose_STL_Container<SgNode*>::iterator s_itr = blockStmts.begin();
                   s_itr != blockStmts.end(); ++s_itr)
           {
              SgStatement *stmt = isSgStatement(*s_itr) ;
              ROSE_ASSERT(stmt);

              /* skip variable declarations */
              if (isSgDeclarationStatement(stmt))
                 continue ;

              SgExprStatement *initCall = buildFunctionCallStmt(
                 SgName("ET_Init"), buildVoidType(), buildExprListExp(),
                 mainFuncDef->get_body()) ;
              stmt->get_scope()->insert_statement(stmt, initCall) ;

              break ;
           }
        }

        /* insert finalization code at end of main() */
        Rose_STL_Container<SgNode*> retStmts =
            NodeQuery::querySubTree(mainFunc, V_SgReturnStmt) ;

        if (retStmts.size() > 0)
        {
           for (Rose_STL_Container<SgNode*>::iterator r_itr = retStmts.begin();
                   r_itr != retStmts.end(); ++r_itr)
           {
              SgReturnStmt *ret = isSgReturnStmt(*r_itr) ;
              ROSE_ASSERT(ret);

              SgExprStatement *sanityCall = buildFunctionCallStmt(
                 SgName("ET_SanityCheck"), buildVoidType(), buildExprListExp(),
                 mainFuncDef->get_body()) ;
              ret->get_scope()->insert_statement(ret, sanityCall) ;

              SgExprStatement *logStatCall = buildFunctionCallStmt(
                 SgName(dumpFunc), buildVoidType(), buildExprListExp(),
                 mainFuncDef->get_body()) ;
              ret->get_scope()->insert_statement(ret, logStatCall) ;
           }
        }
        else
        {
           SgExprStatement *sanityCall = buildFunctionCallStmt(
              SgName("ET_SanityCheck"), buildVoidType(), buildExprListExp(),
              mainFuncDef->get_body()) ;
           mainFuncDef->get_body()->append_statement(sanityCall) ;

           SgExprStatement *logStatCall = buildFunctionCallStmt(
              SgName(dumpFunc), buildVoidType(), buildExprListExp(),
              mainFuncDef->get_body()) ;
           mainFuncDef->get_body()->append_statement(logStatCall) ;
        }
     }
   }

   /* make sure AST is well formed */
   AstTests::runAllTests(project);

   // generateDOT (*project);

   return backend(project);
}
示例#27
0
int main( int argc, char * argv[] )
   {
  // Build the AST used by ROSE
     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT(project != NULL);

  // Build a list of functions within the AST and find all access functions 
  // (function name starts with "get_" or "set_")

  // Build list using a query of the whole AST
     Rose_STL_Container<SgNode*> functionDefinitionList = NodeQuery::querySubTree (project,V_SgFunctionDefinition);

  // Build list using nested Queries (operating on return result of previous query)
  //   Rose_STL_Container<SgNode*> accessFunctionsList;
  //   accessFunctionsList = NodeQuery::queryNodeList (functionDeclarationList,&querySolverAccessFunctions);
  //   printFunctionDeclarationList(accessFunctionsList);

  // Alternative form of same query building the list using a query of the whole AST
   //  accessFunctionsList = NodeQuery::querySubTree (project,&querySolverAccessFunctions);
   //  printFunctionDeclarationList(accessFunctionsList);
int counter = 0;
for (Rose_STL_Container<SgNode*>::iterator i = functionDefinitionList.begin(); i != functionDefinitionList.end(); i++) {
   SgFunctionDefinition* fnc = isSgFunctionDefinition(*i);
  stringstream ss; 
  SgFunctionDeclaration* functionDeclaration = fnc->get_declaration();
  string fileName= functionDeclaration->get_name().str();//StringUtility::stripPathFromFileName(mainDef->get_file_info()->get_filenameString());
    string dotFileName1;
ss << fileName << "." << counter << ".dot";
    counter++;
    dotFileName1 = ss.str();
    //SgFunctionDefinition* fnc = functionDeclaration->get_definition();
    if (fnc != NULL) {
    StaticCFG::CFG* cfg = new StaticCFG::CFG(fnc);
    SgIncidenceDirectedGraph* g = new SgIncidenceDirectedGraph();
     visitorTraversal* vis = new visitorTraversal();
    g = cfg->getGraph();
    myGraph* mg = new myGraph();
    mg = instantiateGraph(g, (*cfg));
    vis->tltnodes = 0;
    vis->paths = 0;
 std::cout << dotFileName1 << std::endl;
 cfgToDot(fnc,dotFileName1);
    //vis->firstPrepGraph(constcfg);
    //t1 = getCPUTime();
    vis->constructPathAnalyzer(mg, true, 0, 0, true);
    
    //t2 = getCPUTim
    std::cout << "function: " << fileName << std::endl;
    std::cout << "paths: " << vis->paths << std::endl;
    delete vis;
    delete cfg;
    delete g;
    delete mg;
    //std::cout << "took: " << timeDifference(t2, t1) << std::endl;
    }
    }
   SgProject* proj = project; 
   SgFunctionDeclaration* mainDefDecl = SageInterface::findMain(proj);
   if (mainDefDecl != NULL) {
  SgFunctionDefinition* mainDef = mainDefDecl->get_definition();
   visitorTraversal* vis = new visitorTraversal();
    StaticCFG::CFG cfg(mainDef);
   //cfg.buildFullCFG();
    stringstream ss;
    string fileName= StringUtility::stripPathFromFileName(mainDef->get_file_info()->get_filenameString());
    string dotFileName1=fileName+"."+ mainDef->get_declaration()->get_name() +".dot";

    cfgToDot(mainDef,dotFileName1);
    //cfg->buildFullCFG();
    SgIncidenceDirectedGraph* g = new SgIncidenceDirectedGraph();
    g = cfg.getGraph();
    myGraph* mg = new myGraph();
    mg = instantiateGraph(g, cfg);
    vis->tltnodes = 0;
    vis->paths = 0;
    //vis->firstPrepGraph(constcfg);
    vis->constructPathAnalyzer(mg, true, 0, 0, true);
    //std::cout << "took: " << timeDifference(t2, t1) << std::endl;
    //cfg.clearNodesAndEdges();
    std::cout << "finished" << std::endl;
    std::cout << "tltnodes: " << vis->tltnodes << " paths: " << vis->paths << std::endl;
    //std::cout << "ipaths: " << ipaths << std::endl;
    delete vis;

    }

// Another way to query for collections of IR nodes
     VariantVector vv1 = V_SgClassDefinition;
     std::cout << "Number of class definitions in the memory pool is: " << NodeQuery::queryMemoryPool(vv1).size() << std::endl;

  // Another way to query for collections of multiple IR nodes.
  // VariantVector(V_SgType) is internally expanded to all IR nodes derived from SgType.
     VariantVector vv2 = VariantVector(V_SgClassDefinition) + VariantVector(V_SgType);
     std::cout << "Number of class definitions AND types in the memory pool is: " << NodeQuery::queryMemoryPool(vv2).size() << std::endl;

  // Note: Show composition of AST queries

     return 0;
   }
示例#28
0
int main( int argc, char *argv[] )
{
	if( argc < 2 ) {
		cout << "./amos: no input files                               " << endl;
		cout << "                                                     " << endl;
		cout << "Hi, this is Amos!                                    " << endl;
		cout << "It's my pleasure to serve you.                       " << endl;
		cout << "                                                     " << endl;
		cout << "Please type option '--help' to see guide             " << endl;
		cout << "                                                     " << endl;

		return 0;
	}

	cout << "*************************************************************" << endl;
	cout << "**                                                         **" << endl;
	cout << "**      Welcome to use OpenMP task validation system!      **" << endl;
	cout << "**                                                         **" << endl;
	cout << "**                                      editor: Amos Wang  **" << endl;
	cout << "*************************************************************\n" << endl;

	vector<string> argvList( argv, argv+argc );
	vector<string> argvList0( argv, argv+argc ); // keep original argv and argc

	command_processing( argvList );

	if( !parse_OmpTask( argvList ) ) {

		cout << "\nAmos says: I am sorry that I could not find any OpenMP task !" << endl << endl;
		return 0;
	}

	// for time counter
	long t_start;
	long t_end;
	double time_program = 0.0;

	t_start = usecs(); 
	// for time counter

	transform_Task2Loop( argvList );

	SgProject *project = frontend(argvList);
	ROSE_ASSERT( project != NULL );

#if 1
	VariantVector vv( V_SgForStatement );
	Rose_STL_Container<SgNode*> loops = NodeQuery::queryMemoryPool(vv);
	for( Rose_STL_Container<SgNode*>::iterator iter = loops.begin(); iter!= loops.end(); iter++ ) {
		SgForStatement* cur_loop = isSgForStatement(*iter);
		ROSE_ASSERT(cur_loop);
		SageInterface::normalizeForLoopInitDeclaration(cur_loop);
	}
#endif

	//initialize_analysis( project, false );
	initialize_analysis( project, false );

	//For each source file in the project
	SgFilePtrList &ptr_list = project->get_fileList();

	cout << "\n**** Amos' validation system running ****\n" << endl;

	for( SgFilePtrList::iterator iter = ptr_list.begin(); iter != ptr_list.end(); iter++ ) {

		cout << "temp source code: " << (*iter)->get_file_info()->get_filename() << endl << endl;
		SgFile *sageFile = (*iter);
		SgSourceFile *sfile = isSgSourceFile(sageFile);
		ROSE_ASSERT(sfile);
		SgGlobal *root = sfile->get_globalScope();
		SgDeclarationStatementPtrList& declList = root->get_declarations ();

		//cout << "Check point 2" << endl;
		//For each function body in the scope
		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;

			//ignore functions in system headers, Can keep them to test robustness
			if ( defn->get_file_info()->get_filename() != sageFile->get_file_info()->get_filename() )
				continue;

			SgBasicBlock *body = defn->get_body();

			// For each loop
			Rose_STL_Container<SgNode*> loops = NodeQuery::querySubTree( defn, V_SgForStatement ); 

			if( loops.size() == 0 ) continue;

			// X. Replace operators with their equivalent counterparts defined 
			// in "inline" annotations
			AstInterfaceImpl faImpl_1( body );
			CPPAstInterface fa_body( &faImpl_1 );
			OperatorInlineRewrite()( fa_body, AstNodePtrImpl(body) );

			// Pass annotations to arrayInterface and use them to collect 
			// alias info. function info etc.  
			ArrayAnnotation* annot = ArrayAnnotation::get_inst(); 
			ArrayInterface array_interface( *annot );
			array_interface.initialize( fa_body, AstNodePtrImpl(defn) );
			array_interface.observe( fa_body );

			// X. Loop normalization for all loops within body
			NormalizeForLoop(fa_body, AstNodePtrImpl(body));

			//cout << "Check point 3" << endl;
			for ( Rose_STL_Container<SgNode*>::iterator iter = loops.begin(); iter!= loops.end(); iter++ ) {

				SgNode* current_loop = *iter;
				SgInitializedName* invarname = getLoopInvariant( current_loop );

				if( invarname != NULL ) {

					if( invarname->get_name().getString().compare("__Amos_Wang__") == 0 ) {

						//cout << "It's __Amos_Wang__." << endl;
						//replace "for(__Amos_Wang__ = 0;__Amos_Wang__ <= 1 - 1;__Amos_Wang__ += 1)" 
						//to "#pragma omp task"
						std::string strtemp = current_loop->unparseToString();
						strtemp.replace( 0, 64, "#pragma omp task" );

						cout << "task position at: " << current_loop->get_file_info()->get_line()
							<< ", " << current_loop->get_file_info()->get_col() << endl;

						cout << "context: " << strtemp.c_str() << endl; 

						TaskValidation( current_loop );

						cout << "TaskValidation done...\n" << endl;
					}
					else continue;

				}

			}// end for loops

		}//end loop for each function body
		cout << "--------------------------------------------" << endl;

	}//end loop for each source file

	release_analysis();

	//generateDOT( *project );
	backend( project );

	//generate final file with correct directive
	amos_filter( argvList0 );

	// for time counter
	t_end = usecs();
	time_program = ((double)(t_end - t_start))/1000000;
	cout << "analysis time: " << time_program << " sec" << endl;
	//

	cout << endl << "***** Thank you for using Amos' compiler ! *****\n" << endl;

	return 0;
}
示例#29
0
int main(int argc, char *argv[])
{
	std::string filename;

	SgProject *project = frontend(argc, argv);
	std::vector<InterproceduralInfo*> ip;
#ifdef NEWDU
	// Create the global def-use analysis
	EDefUse *defUseAnalysis=new EDefUse(project);
	if (defUseAnalysis->run(false)==0)
	{
		std::cerr<<"DFAnalysis failed!"<<endl;
	}
#endif
	string outputFileName=project->get_fileList().front()->get_sourceFileNameWithoutPath ();


	SystemDependenceGraph *sdg = new SystemDependenceGraph;
	// for all function-declarations in the AST
	NodeQuerySynthesizedAttributeType functionDeclarations = NodeQuery::querySubTree(project, V_SgFunctionDeclaration);

	for (NodeQuerySynthesizedAttributeType::iterator i = functionDeclarations.begin(); i != functionDeclarations.end(); i++)
	{
		ControlDependenceGraph *cdg;
		DataDependenceGraph *ddg;
	//	FunctionDependenceGraph * pdg;
		InterproceduralInfo *ipi;

		SgFunctionDeclaration *fDec = isSgFunctionDeclaration(*i);

		ROSE_ASSERT(fDec != NULL);

		// CI (01/08/2007): A missing function definition is an indicator to a 
		// 
		// 
		// librarycall. 
		// * An other possibility would be a programmer-mistake, which we
		// don't treat at this point.  // I assume librarycall
		if (fDec->get_definition() == NULL)
		{/*
//			if (fDec->get_file_info()->isCompilerGenerated()) continue;
			// treat librarycall -> iterprocedualInfo must be created...
			// make all call-parameters used and create a function stub for
			// the graph
			ipi=new InterproceduralInfo(fDec);
			ipi->addExitNode(fDec);
			sdg->addInterproceduralInformation(ipi);
			if (sdg->isKnownLibraryFunction(fDec))
			{
				sdg->createConnectionsForLibaryFunction(fDec);
			}
			else
			{
				sdg->createSafeConfiguration(fDec);
			}
			ip.push_back(ipi);*/

			// This is somewhat a waste of memory and a more efficient approach might generate this when needed, but at the momenent everything is created...
		}
		else
		{
			// get the control depenence for this function
			ipi=new InterproceduralInfo(fDec);

			ROSE_ASSERT(ipi != NULL);

			// get control dependence for this function defintion
			cdg = new ControlDependenceGraph(fDec->get_definition(), ipi);
                        cdg->computeAdditionalFunctioncallDepencencies();
			cdg->computeInterproceduralInformation(ipi);

			// get the data dependence for this function
			ddg = new DataDependenceGraph(fDec->get_definition(), defUseAnalysis,ipi);
			
			sdg->addFunction(cdg,ddg);
			sdg->addInterproceduralInformation(ipi);
			ip.push_back(ipi);
		}   
		// else if (fD->get_definition() == NULL)

	}
	// now all function-declarations have been process as well have all function-definitions
	filename = (outputFileName) + ".no_ii.sdg.dot";
	sdg->writeDot((char *)filename.c_str());
	
	// perform interproceduralAnalysys
	sdg->performInterproceduralAnalysis();

	filename = (outputFileName)+".deadEnds.sdg.dot";
	sdg->writeDot((char *)filename.c_str());			
	set<SgNode*> preserve;
	if (sdg->getMainFunction()!=NULL) {
	preserve.insert(sdg->getMainFunction());
	sdg->cleanUp(preserve);
	}
	filename = (outputFileName)+".final.sdg.dot";
	sdg->writeDot((char *)filename.c_str());			
}
示例#30
0
int
main ( int argc,  char * argv[] )
{
  //init_poet();  // initialize poet

  if (argc <= 1) {
      PrintUsage(argv[0]);
      return -1;
  }

#ifdef USE_OMEGA
  std::stringstream buffer;
  buffer << argv[argc-1] << std::endl;
  DepStats.SetFileName(buffer.str());
#endif

  vector<string> argvList(argv, argv + argc);
  CmdOptions::GetInstance()->SetOptions(argvList);

  ArrayAnnotation* array_annot = ArrayAnnotation::get_inst();
  array_annot->register_annot();

  //OperatorSideEffectAnnotation* funcAnnot=OperatorSideEffectAnnotation::get_inst();
  //funcAnnot->register_annot();
  LoopTransformInterface::set_sideEffectInfo(array_annot);

  ArrayInterface anal(*array_annot);
  LoopTransformInterface::set_arrayInfo(&anal);

  ReadAnnotation::get_inst()->read();
  if (DebugAnnot()) {
   // funcAnnot->Dump();
    array_annot->Dump();
  }

  AssumeNoAlias aliasInfo;
  LoopTransformInterface::set_aliasInfo(&aliasInfo);

  LoopTransformInterface::cmdline_configure(argvList);

  SgProject *sageProject = new SgProject ( argvList);
  FixFileInfo(sageProject);

  // DQ (11/19/2013): Added AST consistency tests.
     AstTests::runAllTests(sageProject);

  int filenum = sageProject->numberOfFiles();
  for (int i = 0; i < filenum; ++i) {

  // DQ (11/19/2013): Added AST consistency tests.
     AstTests::runAllTests(sageProject);

    SgSourceFile* sageFile = isSgSourceFile(sageProject->get_fileList()[i]);
    ROSE_ASSERT(sageFile != NULL);

    std::string fname = sageFile->get_file_info()->get_raw_filename();
    fname=fname.substr(fname.find_last_of('/')+1);

    AutoTuningInterface tuning(fname);

    LoopTransformInterface::set_tuningInterface(&tuning);
    SgGlobal *root = sageFile->get_globalScope();
    ROSE_ASSERT(root != NULL);

    SgDeclarationStatementPtrList declList = root->get_declarations ();

 // DQ (11/19/2013): Added AST consistency tests.
    AstTests::runAllTests(sageProject);

    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;
      SgBasicBlock *stmts = defn->get_body();  
      AstInterfaceImpl scope(stmts);

   // DQ (11/19/2013): Added AST consistency tests.
      AstTests::runAllTests(sageProject);

   // DQ (11/19/2013): Added AST consistency tests.
      AstTests::runAllTests(sageProject);

      LoopTransformInterface::TransformTraverse(scope,AstNodePtrImpl(stmts));

#if 0
   // DQ (11/19/2013): Added AST consistency tests (this fails).
      AstTests::runAllTests(sageProject);
#endif
    }
    tuning.GenOutput();

#if 0
  // DQ (11/19/2013): Added AST consistency tests (this fails).
     AstTests::runAllTests(sageProject);
#endif
  }

//   if (CmdOptions::GetInstance()->HasOption("-fd")) {
//       simpleIndexFiniteDifferencing(sageProject);
//   }
//   if (CmdOptions::GetInstance()->HasOption("-pre")) {
//       partialRedundancyElimination(sageProject);
//   }

#if 0
  // DQ (11/19/2013): Added AST consistency tests (this fails).
     AstTests::runAllTests(sageProject);
#endif

     unparseProject(sageProject);
   //backend(sageProject);

#ifdef USE_OMEGA
     DepStats.SetDepChoice(0x1 | 0x2 | 0x4);
     DepStats.PrintResults();
#endif

  return 0;
}