int
main ( int argc, char* argv[] )
   {
     ROSE_INITIALIZE;

     if (SgProject::get_verbose() > 0)
          printf ("In preprocessor.C: main() \n");

     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT (project != NULL);

     Rose_STL_Container<SgNode*> nodeList;
     nodeList = NodeQuery::querySubTree (project,V_SgForStatement);
     printf ("\nnodeList.size() = %zu \n",nodeList.size());

     Rose_STL_Container<SgNode*>::iterator i = nodeList.begin();
     while (i != nodeList.end())
        {
          Sg_File_Info & fileInfo = *((*i)->get_file_info());
          printf ("Query node = %p = %s in %s \n ----- at line %d on column %d \n",
              *i,(*i)->sage_class_name(),fileInfo.get_filename(),
               fileInfo.get_line(), fileInfo.get_col());
          i++;
        }

     if (project->get_verbose() > 0)
          printf ("Calling the backend() \n");

     return 0;
   }
示例#2
0
文件: CG.C 项目: LindaLovelace/rose
int main(int argc, char **argv)
{
    std::vector<std::string> argvList(argv, argv + argc);

    //Read the comparison file
    std::string graphCompareOutput = "";
    CommandlineProcessing::isOptionWithParameter(argvList, "-compare:", "(graph)", graphCompareOutput, true);
    CommandlineProcessing::removeArgsWithParameters(argvList, "-compare:");
    
    //Run frontend
    SgProject* project = frontend(argvList);
    ROSE_ASSERT(project != NULL);

    // Build the callgraph 
    CallGraphBuilder cgb(project);
    cgb.buildCallGraph(OnlyCurrentDirectory());


     if (graphCompareOutput == "")
        graphCompareOutput = ((project->get_outputFileName()) + ".cg.dmp");

    cout << "Writing custom compare to: " << graphCompareOutput << endl;

    SgIncidenceDirectedGraph *newGraph = cgb.getGraph();
    sortedCallGraphDump(graphCompareOutput, newGraph);

    return 0;
}
示例#3
0
int
main(int argc, char* argv[])
   {
  // This program test the conversion of the ROSE AST to n ATerm and back to a ROSE AST.

  // Generate a ROSE AST as input.
  // printf ("Building the ROSE AST \n");
     SgProject* project = frontend(argc,argv);
  // printf ("Done: Building the ROSE AST \n");

  // Output an optional graph of the AST (just the tree, when active)
  // generateDOT(*project);

     SgFile* roseFile = project->operator[](0);
     ROSE_ASSERT(roseFile != NULL);
     SgSourceFile* sourceFile = isSgSourceFile(roseFile);
     ROSE_ASSERT(sourceFile != NULL);

  // printf ("Calling ATinit \n");
     ATerm bottom;
     ATinit(argc, argv, &bottom);

  // printf ("Calling convertAstNodeToRoseAterm \n");
  // ATerm term = convertNodeToAterm(project);
  // ATerm term = convertNodeToAterm(sourceFile);
  // ATerm term = convertAstNodeToRoseAterm(sourceFile);

  // Actually this implementation in convertNodeToAterm already adds the pointer value to the aterm, so we can just return this Aterm directly.
     ATerm term = convertNodeToAterm(sourceFile);

  // printf ("DONE: Calling convertAstNodeToRoseAterm term = %p \n",term);

     ROSE_ASSERT (term != NULL);

     string roseAST_filename = project->get_file(0).getFileName();
     char* s = strdup(roseAST_filename.c_str());
     string file_basename = basename(s);

  // ATerm_Graph::graph_aterm_ast(term,file_basename);

#if 1
  // DQ (9/17/2014): Adding test for conversion of Aterm back to AST.
     printf ("Testing the reverse process to generate the ROSE AST from the Aterm \n");
     SgNode* rootOfAST = convertAtermToNode(term);
     printf ("rootOfAST = %p = %s \n",rootOfAST,rootOfAST->class_name().c_str());
#endif

  // generateDOT(*project);
     generateDOTforMultipleFile(*project, "AFTER_ATERM");

  // Output an optional graph of the AST (the whole graph, of bounded complexity, when active)
     const int MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH = 5000;
     generateAstGraph(project,MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH,"AFTER_ATERM");

#if 0
     printf ("Program Terminated Normally \n");
#endif

     return 0;
   }
示例#4
0
int main ( int argc, char* argv[] ) {
	SgProject * project = frontend ( argc , argv ) ;
	
	Rose_STL_Container<SgNode*> pragma_decls = NodeQuery::querySubTree(project, V_SgPragmaDeclaration);
	Rose_STL_Container<SgNode*>::iterator it;
	for (it = pragma_decls.begin(); it != pragma_decls.end(); it++) {
		SgPragmaDeclaration * pragma_decl = isSgPragmaDeclaration(*it);
		
		try {
			PolyhedricAnnotation::parse(pragma_decl);
		}
		catch (Exception::ExceptionBase & e) {
			e.print(std::cerr);
			continue;
		}
		
		PolyhedricAnnotation::PragmaPolyhedralProgram & polyhedral_program =
				PolyhedricAnnotation::getPolyhedralProgram<SgPragmaDeclaration, SgExprStatement, RoseVariable>(pragma_decl);
		
		Scheduling::PragmaSchedule schedule(polyhedral_program, 0);
		CodeGeneration::generateAndReplace(schedule);
	}
	
	project->unparse();
	
	return 0;
}
示例#5
0
int
main ( int argc, char * argv[] )
   {
  // Main Function for default example ROSE Preprocessor
  // This is an example of a preprocessor that can be built with ROSE
  // This example tests the ROSE infrastructure

     ios::sync_with_stdio();     // Syncs C++ and C I/O subsystems!

  // Declare usage (if incorrect number of inputs):
     if (argc == 1)
        {
       // Print usage and exit with exit status == 1
          Rose::usage (1);
        }

  // Build the project object which we will fill up with multiple files and use as a
  // handle for all processing of the AST(s) associated with one or more source files.
     SgProject sageProject (argc,argv);

  // Warnings from EDG processing are OK but not errors
  //   ROSE_ASSERT (EDG_FrontEndErrorCode <= 3);

  // cout << "EDG/SAGE Processing DONE! (manipulate AST with ROSE ...) " << endl;

  // DQ (10/17/2004): Added internal testing of AST
     AstTests::runAllTests(&sageProject);

     SIDL_TreeTraversal treeTraversal(chooseConstructor(&sageProject));

     MethodSearchVisitor treeVisitor(&sageProject);
     treeVisitor.traverseInputFiles(&sageProject, preorder);

  // Ignore the return value since we don't need it
     treeTraversal.traverseInputFiles(&sageProject);
     AstDOTGeneration dotgen;
     dotgen.generateInputFiles(&sageProject, AstDOTGeneration::PREORDER);

     cout << "ROSE Processing DONE! (no need to call unparse or backend C++ compiler ...) " << endl;

#if 0
  // DQ (10/17/2004): This seems to be a problem, some sort of infinit loop is generated in the unparser!
  // the test code has been transfrered to another location for internal testing.  for now this should
  // be commented out.  It is not required for Babel Processing. This is now fixed!

  // Generate the final C++ source code from the potentially modified SAGE AST
  // sageProject.set_verbose(true);
     sageProject.unparse();
#endif

  // Later we want to call babel to process the generated SIDL file and generate the imple files which 
  // we will process as part of the next phase of work to completely automate the process.
     int finalCombinedExitStatus = 0;

     printf ("Program Compiled Normally (exit status = %d)! \n\n\n\n",finalCombinedExitStatus);

  // either of these will work similarly
  // exit (finalCombinedExitStatus);
     return finalCombinedExitStatus;
   }
示例#6
0
void ProjectManager::storeProjectState()
{
    QSettings s;

    s.remove("LoadedProjects");


    s.beginGroup("LoadedProjects");

    s.beginWriteArray("Projects");

    for(int p=0; p<rootNode->childrenCount(); p++)
    {
        ProjectNode * projNode =  dynamic_cast<ProjectNode*>(rootNode->child(p));

        s.setArrayIndex(p);
        s.setValue("Name",projNode->getName());

        SgProject * sgProj =  projNode->getSgProject();

        s.beginWriteArray("files");
        for(int i=0; i < sgProj->numberOfFiles(); i++)
        {
            QString name = (*sgProj)[i]->getFileName().c_str();
            s.setArrayIndex(i);
            s.setValue("name",name);
        }
        s.endArray();
    }

    s.endArray(); //Projects


    s.endGroup();
}
示例#7
0
int main (int argc, char* argv[])
   {
  // Main Function for default example ROSE Preprocessor
  // This is an example of a preprocessor that can be built with ROSE

  // Build the project object (AST) which we will fill up with multiple files and use as a
  // handle for all processing of the AST(s) associated with one or more source files.
     vector<string> argvList(argv, argv + argc);
     VectorCmdOptions::GetInstance()->SetOptions(argvList);
     SgProject* sageProject = frontend(argvList);
  // FixSgProject(sageProject);

  // AstTests::runAllTests(const_cast<SgProject*>(project));
     AstTests::runAllTests(sageProject);

     PRE::partialRedundancyElimination(sageProject);

  // AstPDFGeneration().generateInputFiles(sageProject);

     AstTests::runAllTests(sageProject);

  // AstPDFGeneration().generateInputFiles(sageProject);

  // Generate the final C++ source code from the potentially modified SAGE AST
     sageProject->unparse();

  // What remains is to run the specified compiler (typically the C++ compiler) using 
  // the generated output file (unparsed and transformed application code) to generate
  // an object file.
  // int finalCombinedExitStatus = sageProject.compileOutput();

  // return exit code from complilation of generated (unparsed) code
     return 0;
   }
示例#8
0
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);

     SgProject* project = frontend(argc,argv);

     AstTests::runAllTests(project);

  // 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);
   }
示例#9
0
//! A test main program 
int main ( int argc, char * argv[] )
{
  std::vector <std::string> argvList (argv, argv + argc);
 
  // turn on OpenMP parsing support for device() map (a[][] dist_data()) 
  argvList.push_back("-rose:openmp:parse_only");

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

  // Assuming single input file for this prototype
  ROSE_ASSERT (project->get_fileList().size() ==1);
  SgFile * cur_file = project->get_fileList()[0];

  SgSourceFile* sfile = isSgSourceFile(cur_file);
  
  setupMPIInit (sfile);
  setupMPIFinalize (sfile);

#if 0 
   // old V 0.1
  std::vector <MPI_PragmaAttribute*> pragma_attribute_list;
  // Parsing all relevant pragmas, generate MPI_Pragma_Attribute_List.
  parsePragmas (sfile, pragma_attribute_list);
  translatePragmas (pragma_attribute_list);
#else
  // newer V 0.2 
  lower_xomp (sfile);
#endif

  AstTests::runAllTests(project);
  return backend(project);

//  return 0;
}
int main (int argc, char* argv[]) {
  // Main Function for default example ROSE Preprocessor
  // This is an example of a preprocessor that can be built with ROSE

  // Build the project object (AST) which we will fill up with multiple files and use as a
  // handle for all processing of the AST(s) associated with one or more source files.
  SgProject* sageProject = frontend(argc,argv);

  simpleIndexFiniteDifferencing(sageProject);

  FixSgProject(*sageProject);

  // partialRedundancyElimination(sageProject);

  // AstPDFGeneration().generateInputFiles(sageProject);

  // Generate the final C++ source code from the potentially modified SAGE AST
  sageProject->unparse();

  // What remains is to run the specified compiler (typically the C++ compiler) using 
  // the generated output file (unparsed and transformed application code) to generate
  // an object file.
  // int finalCombinedExitStatus = sageProject->compileOutput();

  // return exit code from complilation of generated (unparsed) code
  return 0;
}
示例#11
0
文件: tilek.cpp 项目: 8l/rose
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;
}
示例#12
0
int
main ( int argc, char* argv[] )
   {
  // Main Function for default example ROSE Preprocessor
  // This is an example of a preprocessor that can be built with ROSE
  // This example can be used to test the ROSE infrastructure

     ios::sync_with_stdio();     // Syncs C++ and C I/O subsystems!

     if (SgProject::get_verbose() > 0)
          printf ("In preprocessor.C: main() \n");

     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT (project != NULL);

#if 0
  // This fails for test2005_63.C but Rich has fixed this
  // by updating the pdf library we are using within ROSE.
     printf ("Generate the pdf output of the SAGE III AST \n");
     generatePDF ( *project );
#endif

#if 0
     printf ("Generate the dot output of the SAGE III AST \n");
     generateDOT ( *project );
#endif

#if 1
  // DQ (2/6/2004): These tests fail in Coco for test2004_14.C
     AstTests::runAllTests(const_cast<SgProject*>(project));
#else
     printf ("Skipped agressive (slow) internal consistancy tests! \n");
#endif

     if (project->get_verbose() > 0)
          printf ("Calling the AST copy mechanism \n");

  // Demonstrate the copying of the whole AST
     SgProject* newProject = static_cast<SgProject*>(copyAST(project));
     ROSE_ASSERT(newProject != NULL);

     printf ("Running tests on copy of AST \n");
     AstTests::runAllTests(newProject);

     if (project->get_verbose() > 0)
          printf ("Calling the backend() \n");

     int errorCode = 0;
     errorCode = backend(project);

  // DQ (7/7/2005): Only output the performance report if verbose is set (greater than zero)
     if (project->get_verbose() > 0)
        {
       // Output any saved performance data (see ROSE/src/astDiagnostics/AstPerformance.h)
          AstPerformance::generateReport();
        }

  // printf ("Exiting with errorCode = %d \n",errorCode);
     return errorCode;
   }
示例#13
0
int main(int argc, char * argv[])
{
  // This flag can skip insertion of XOMP_init() and XOMP_terminate(), both of which are defined in libxomp.a
  // But somehow nvcc cannot link the entire libxomp.a with the cuda object file
  // TODO: ultimate solution is to outline all CUDA code into a separate file and keep the original file type intact
  OmpSupport::enable_accelerator = true;

  SgProject *project = frontend (argc, argv);


  //TODO: turn this back on once blockDim.x * blockIdx.x + threadIdx.x is built properly in omp_lowering.cpp
  //  AstTests::runAllTests(project);

  // change .c suffix to .cu suffix
  // We only process one single input file at a time
  ROSE_ASSERT (project->get_fileList().size() ==1);
  SgFile * cur_file = project->get_fileList()[0];

  string orig_name = cur_file->get_file_info()->get_filenameString();
  string file_suffix = StringUtility::fileNameSuffix(orig_name);
  // We only allow C file to be compatible with nvcc CUDA compiler
  ROSE_ASSERT (CommandlineProcessing::isCFileNameSuffix(file_suffix));
  orig_name = StringUtility::stripPathFromFileName(orig_name);
  string naked_name = StringUtility::stripFileSuffixFromFileName(orig_name);
  cur_file->set_unparse_output_filename("rose_"+naked_name+".cu");

  return backend(project);
}
int
main ( int argc, char* argv[] )
   {
  // DQ (7/7/2005): Introduce tracking of performance of ROSE.
     TimingPerformance timer ("AST check Main:");

     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT (project != NULL);

     findSwitchWithoutDefault(project);

  // if (project->get_verbose() > 0)
  //      printf ("Calling the backend() \n");

     int errorCode = 0;
  // errorCode = backend(project);

  // Just set the project, the report will be generated upon calling the destructor for "timer"
     timer.set_project(project);

     if (project->get_verbose() > 0)
        {
       // Output any saved performance data (see ROSE/src/astDiagnostics/AstPerformance.h)
          AstPerformance::generateReport();
        }

  // return 0;
  // printf ("Exiting with errorCode = %d \n",errorCode);
     return errorCode;
   }
示例#15
0
int main(int argc, char * argv[])
{
  SgProject *project = frontend (argc, argv);

  // Generate a file handle from the first file of the project
  abstract_node* file_node= buildroseNode((project->get_fileList())[0]);
  abstract_handle* handle0 = new abstract_handle(file_node);
  cout<<"Created a file handle:\n"<<handle0->toString()<<endl<<endl;;

  //Create a handle to a namespace given its name and parent handle 
  string input1="NamespaceDeclarationStatement<name,space1>";
  abstract_handle* handle1 = new abstract_handle(handle0,input1);
  cout<<"Created a handle:\n"<<handle1->toString()<<endl<<endl;
  cout<<"It points to:\n"<<handle1->getNode()->toString()<<endl<<endl;

  // Create a handle within the file, given a string specifying  
  // its construct type (class declaration) and source position 
  string input="ClassDeclaration<position,4.3-9.2>";
  abstract_handle* handle2 = new abstract_handle(handle0,input);

  cout<<"Created a handle:\n"<<handle2->toString()<<endl<<endl;
  cout<<"It points to:\n"<<handle2->getNode()->toString()<<endl<<endl;;

  // find the second function declaration within handle2
  abstract_handle handle3(handle2,"FunctionDeclaration<numbering,2>");

  cout<<"Created a handle:\n"<<handle3.toString()<<endl<<endl;
  cout<<"It points to:\n"<<handle3.getNode()->toString()<<endl;

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

     vector<string> argvList(argv, argv + argc);

     SgProject* project = NULL;

     bool removeCommandOption = true;
     string pathToSkip;

  // The specified path string will be put into "skipPathString" and then the option will be removed
     if ( CommandlineProcessing::isOptionWithParameter(argvList,"-skipFile:","(path)",pathToSkip,removeCommandOption) )
        {
          printf ("Skip file containing path = %s \n",pathToSkip.c_str());

       // Builds SgProject with valid but empty SgFile objects, but with all command line processing
       // done. The frontend can then be invoked conditionally for each SgFile object.
          project = frontendShell(argvList);

       // Loop over all files in the SgProject (and call the frontend on a selected subset)
          SgFilePtrList::iterator fileIterator = project->get_fileList().begin();
          while (fileIterator != project->get_fileList().end())
             {
               string filename = (*fileIterator)->get_sourceFileNameWithPath();

            // Skip processing of files from a specific directory
            // If there is a match between the path and any part of the filename then skip processing this file
               if (filename.find(pathToSkip) != string::npos)
                  {
                    printf ("Skipping call to the frontend for this file (%s) \n",filename.c_str());
                  }
                 else
                  {
                 // Call the front-end (which will internally call EDG).
                 // Note: The commandline can be reset by using set_originalCommandLineArgumentList().
                    int EDG_FrontEndErrorCode = (*fileIterator)->callFrontEnd();

                 // Warnings from EDG processing are OK, but not errors (EDG detail)
                    ROSE_ASSERT (EDG_FrontEndErrorCode <= 3);
                  }

            // increment the file list iterator
               fileIterator++;
             }
        }
       else
        {
       // This call the frontend automatically for all source files on the command line
          project = frontend(argvList);
        }

  // Call the backend, where files were not processed the original file will be compiled
  // directly by the backend (vendor) compiler. The SgFile objects here would also be 
  // looped over and unparsed and or compiled separately.
     return backend(project);
   }
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);
   }
int
main ( int argc, char* argv[] )
   {
     ios::sync_with_stdio();     // Syncs C++ and C I/O subsystems!

     ofstream datfile ( "ProblemVariableDeclarations.data" , ios::out | ios::app );
     if ( datfile.good() == false )
        {
          printf ("File failed to open \n");
        }

  // datfile << "This is a test!" << std::endl;

#if 1
     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT (project != NULL);

     Traversal traversal(&datfile);
     traversal.traverse(project,preorder);
#endif

     datfile.close();

#if 1
  // Run AST consistancy tests (so that we can test them while we analize KULL
     AstTests::runAllTests(const_cast<SgProject*>(project));
#else
     printf ("Skipped agressive (slow) internal consistancy tests! \n");
#endif



#if 0
     return 0;
#else
  // Output the source code and generate the object file so that 
  // we can test these parts of KULL processing as well
     if (project->get_verbose() > 0)
          printf ("Calling the backend() \n");

     int errorCode = 0;
     errorCode = backend(project);

  // DQ (12/3/2004): Test use of AST delete
  // DeleteSgTree(project);
     project = NULL;

  // DQ (7/7/2005): Only output the performance report if verbose is set (greater than zero)
     if (project->get_verbose() > 0)
        {
       // Output any saved performance data (see ROSE/src/astDiagnostics/AstPerformance.h)
          AstPerformance::generateReport();
        }
     return errorCode;
#endif

   }
示例#19
0
文件: helpFunctions.C 项目: 8l/rose
/*
 *  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 SgSourceFile *sageFile = isSgSourceFile (sageFilePtrList[i]);
	  ROSE_ASSERT (sageFile != NULL);
	  SgGlobal *sageGlobal = sageFile->get_globalScope();
	  ROSE_ASSERT (sageGlobal != NULL);

	  returnVector.push_back (sageGlobal);
	}
    }


  return returnVector;
};
int
main( int argc, char * argv[] )
   {
  // This test code demonstrates the differences between an ordinary 
  // SgTopDownBottomUpProcessing traversal and a traversal using the 
  // AST Rewrite Mechanism.

  // DQ (4/6/2017): This will not fail if we skip calling ROSE_INITIALIZE (but
  // any warning message using the message looging feature in ROSE will fail).
     ROSE_INITIALIZE;

     ios::sync_with_stdio();     // Syncs C++ and C I/O subsystems!
     if (argc == 1)
        {
       // Print usage and exit with exit status == 1
          rose::usage (1);
        }

  // Build the project object which we will fill up with multiple files and use as a
  // handle for all processing of the AST(s) associated with one or more source files.
     int EDG_FrontEndErrorCode = 0;
     SgProject* sageProject = new SgProject(argc,argv,EDG_FrontEndErrorCode); 

  // Warnings from EDG processing are OK but not errors
     ROSE_ASSERT (EDG_FrontEndErrorCode <= 3);

     cout << "EDG/SAGE Processing DONE! (manipulate with ROSE ...) " << endl;

  // Output the source code file (as represented by the SAGE AST) as a PDF file (with bookmarks)
     AstPDFGeneration pdftest;
     pdftest.generateInputFiles(sageProject);

  // Build the inherited attribute
     MyInheritedAttribute inheritedAttribute;

  // The traversal uses the AST rewrite mechanism which requires the SgProject object to retrive the
  // command line for compilation of the intermeditate files (from strings to AST fragments) before
  // patching them into the application's AST.
     MyTraversal myTraversal(*sageProject);

  // Call the traversal starting at the sageProject node of the AST
     myTraversal.traverseInputFiles(sageProject,inheritedAttribute);

  // Generate the final C++ source code from the potentially modified SAGE AST
     sageProject->unparse();

     cout << "Generation of final source code (unparsing) DONE! (compile ...) " << endl;

  // What remains is to run the specified compiler (typically the C++ compiler) using 
  // the generated output file (unparsed and transformed application code) to generate
  // an object file.
     int finalCombinedExitStatus = sageProject->compileOutput();
     printf ("Program Compiled Normally (exit status = %d)! \n\n\n\n",finalCombinedExitStatus);
     return finalCombinedExitStatus;
   }
示例#21
0
int main ( unsigned argc,  char * argv[] )
{
    string sInputFile, sOutputFile;
    ofstream outputFile;

    // for debugging only switch between persistentand "pointer" handles
    // (pointers are faster, persistent are easier to debug
    bool p_h=FALSE; 
    //    p_h = TRUE;

    // read in command line arguments
    // usage: CtoOA inputFile
    if(argc < 2) { usage(argv[0]); return 1; }
    sInputFile  = argv[1];
    //sOutputFile = argv[2];

    // load the Sage project, open the output file, and construct the
    // code generator (which outputs .oa notation to the file)
    SgProject * sageProject = frontend((int)argc, &argv[0]);
    //outputFile.open(sOutputFile.c_str());

    // debug output
    //AstPDFGeneration pdftest;
    //pdftest.generateInputFiles(sageProject);
    //AstDOTGeneration dottest;
    //dottest.generateInputFiles(sageProject);
    
    // Loop over every file.   BW 4/13/06
    int filenum = sageProject->numberOfFiles();
    for (int i = 0; i < filenum; ++i) 
    {

        SgFile &sageFile = sageProject->get_file(i);
        SgGlobal *root = sageFile.get_root();

        // Loop through every function in the file of this project.
        std::vector<SgNode*> nodeArray;
        OA::OA_ptr<SageIRInterface> irInterface; 
        irInterface = new SageIRInterface(sageProject, &nodeArray, p_h);
        OA::OA_ptr<SageIRProcIterator> procIter;
	// Do not process include files, e.g., iostream.h.
	bool excludeInputFiles = true;
        procIter = new SageIRProcIterator(sageProject, irInterface, excludeInputFiles);

        for (; procIter->isValid(); ++(*procIter) ) 
	{
            // output notation for this function
	    outputNotation(procIter->current(), irInterface, std::cout);
	}
    }     

    return 0;
}
示例#22
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;
}
示例#23
0
int main(int argc, char **argv)
{
    // Initialize and check compatibility. See rose::initialize
    ROSE_INITIALIZE;

    SgProject *project = frontend(argc, argv);

    std::string fileName = project->get_outputFileName();
    AST_FILE_IO::startUp(project);
    AST_FILE_IO::writeASTToFile(fileName += ".binary");

    std::cout << "done writing AST to " << fileName << "!" << std::endl;
}
示例#24
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;
}
示例#25
0
void
WalrusGraph::generateWalrusGraph( SgNode* node, string outputFilename )
   {
// Notes: The generated file in the Walrus format typically requies some editing by hand.
// For large files the "comma" always has to be remove at the end of the edge list and the node list.
// For Binary files the first edge which points to itself ("source=0 distination=0") has to be removed.
// Then the last entry for the node list has to be removed.
// Then is can often work.


     SgProject* project = isSgProject(node);
     if (project != NULL)
        {
          printf ("Found the SgProject \n");

          SgFile* fileNode = project->get_fileList()[0];
          if (isSgBinaryComposite(fileNode) != NULL)
             {
               if (project->get_binary_only() == false)
                    printf ("This should have been set already, what is wrong here! \n");

               project->set_binary_only(true);
             }

          if (project->get_binary_only() == true)
             {
               printf ("Found a binary file \n");
               WalrusGraph::isBinary = true;
             }
        }

     Counter traversal;
     traversal.traverse(node,preorder);

     printf ("node_to_index_map.size() = %zu \n",node_to_index_map.size());

     filebuf fb;
     fb.open (outputFilename.c_str(),ios::out);
     ostream os(&fb);

     ostream outputFile(&fb);
     outputFilePtr = &outputFile;
     ROSE_ASSERT(outputFilePtr != NULL);

     generateEdges(node);
     generateNodes(node);

     outputFile.flush();
   }
示例#26
0
int main(int argc, char *argv[])
{
        SgProject *project = frontend(argc, argv);
        SlicingInfo si=SlicingInfo();
        si.traverse(project, preorder);

        SystemDependenceGraph * sdg=new SystemDependenceGraph();
        sdg->parseProject(project);

        CreateSliceSet sliceSet(sdg,si.getSlicingTargets());
        CreateSlice cs(sliceSet.computeSliceSet());

        cs.traverse(project);
        project->unparse();     
}
示例#27
0
文件: testParser10.C 项目: 8l/rose
int main( int argc, char * argv[] ) 
   {
     CommandlineProcessing::addCppSourceFileSuffix("docs")
     CommandlineProcessing::addCppSourceFileSuffix("h");

  // Build the AST used by ROSE
     SgProject* sageProject = frontend(argc,argv);

     Doxygen::annotate(sageProject);

     OrganizeAllComments oac;
     oac.traverse(sageProject, preorder);

  // Generate source code from AST and call the vendor's compiler
     sageProject->unparse();
   }
示例#28
0
int main(int argc, char * argv[])
{
  // This flag can skip insertion of XOMP_init() and XOMP_terminate(), both of which are defined in libxomp.a
  // But somehow nvcc cannot link the entire libxomp.a with the cuda object file
  // TODO: ultimate solution is to outline all CUDA code into a separate file and keep the original file type intact
  OmpSupport::enable_accelerator = true;
  OmpSupport::useDDE = true; // using Device Data Environment to manage data on GPUs

  vector<string> argvList(argv, argv + argc);

   // -rose:openmp:nodde to turn off the use of DDE runtime
   // This option does not work with collapse() now. It is only for debugging and seeing old code only
  if(CommandlineProcessing::isOption (argvList,
        "-rose:openmp:",
        "nodde",
        true) ||
  CommandlineProcessing::isOption (argvList,
        "--rose:openmp:",
        "nodde",
        true))
 
  {
    OmpSupport::useDDE = false;
    cout<<"OpenMP Lowering is set to turn off the use of DDE (Device Data Environment) functions ..."<<endl;
  }

  SgProject *project = frontend (argvList);


  //TODO: turn this back on once blockDim.x * blockIdx.x + threadIdx.x is built properly in omp_lowering.cpp
  //  AstTests::runAllTests(project);

  // change .c suffix to .cu suffix
  // We only process one single input file at a time
  ROSE_ASSERT (project->get_fileList().size() ==1);
  SgFile * cur_file = project->get_fileList()[0];

  string orig_name = cur_file->get_file_info()->get_filenameString();
  string file_suffix = StringUtility::fileNameSuffix(orig_name);
  // We only allow C file to be compatible with nvcc CUDA compiler
  //ROSE_ASSERT (CommandlineProcessing::isCFileNameSuffix(file_suffix));
  orig_name = StringUtility::stripPathFromFileName(orig_name);
  string naked_name = StringUtility::stripFileSuffixFromFileName(orig_name);
  cur_file->set_unparse_output_filename("rose_"+naked_name+".cu");

  return backend(project);
}
示例#29
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);
	}

}
void processTemplateHandlingOptions( SgNode* node )
   {
  // DQ (7/7/2005): Introduce tracking of performance of ROSE.
     TimingPerformance timer ("Fixup templateHandlingOptions:");

     ROSE_ASSERT(node != NULL);
     SgFile* file = TransformationSupport::getFile(node);

     if (file == NULL)
        {
       // printf ("Detected AST fragement not associated with primary AST, ignore template handling ... \n");

          SgProject *project = isSgProject(node);
          if (project != NULL)
             {
            // GB (9/4/2009): Added this case for handling SgProject nodes. We do
            // this simply by iterating over the list of files in the project and
            // calling this function recursively. This is only one level of
            // recursion since files are not nested.
               SgFilePtrList &files = project->get_fileList();
               SgFilePtrList::iterator fIterator;
               for (fIterator = files.begin(); fIterator != files.end(); ++fIterator)
                  {
                    SgFile *file = *fIterator;
                    ROSE_ASSERT(file != NULL);
                    markTemplateInstantiationsForOutput(file);
                  }
             }
        }
       else
        {
          bool buildImplicitTemplates       = (file != NULL) && (file->get_no_implicit_templates() == false);
          bool buildImplicitInlineTemplates = (file != NULL) && (file->get_no_implicit_inline_templates() == false);
#if 0
          printf ("buildImplicitTemplates       = %s \n",buildImplicitTemplates ? "true" : "false");
          printf ("buildImplicitInlineTemplates = %s \n",buildImplicitInlineTemplates ? "true" : "false");
#endif
       // This simplifies how the traversal is called!
          ProcessTemplateHandlingOptions astFixupTraversal(file,buildImplicitTemplates,buildImplicitInlineTemplates);

       // I think the default should be preorder so that the interfaces would be more uniform
          astFixupTraversal.traverse(node,preorder);
        }
   }