コード例 #1
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;
   }
コード例 #2
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;
}
コード例 #3
0
ファイル: test2005_21.C プロジェクト: Federico2014/edg4x-rose
int main(int argc, char *argv[]){
  
  SgProject* sgproject = frontend(argc, argv);
  // SgProject *sgproject_copy = static_cast<SgProject*>(sgproject->copy(SgTREE_COPY)); 
  // This copy of the sgproject fails due to the copy function of the SgFile fails (aborts)
  
  SgFile &file = sgproject->get_file(0);
  // SgFile *file_copy = static_cast<SgFile*>(file.copy(SgTREE_COPY));
  // Calling the copy function of SgFile fails:
  // Before aborting the execution, the following error message is displayed:
  // "This is the default constructor, use SgFile (argc,argv) instead"
  
  SgGlobal *root = file.get_root();
  SgGlobal *root_copy = static_cast<SgGlobal*>(root->copy(SgTREE_COPY));
  // Copying the SgGlobal object is OK
  
  // removing the return statement...from the copy!
  list<SgNode*> returnstmt_list = NodeQuery::querySubTree(root_copy, V_SgReturnStmt);
  SgStatement* stmt = isSgStatement(*returnstmt_list.begin());
  LowLevelRewrite::remove(stmt);
  
  sgproject->unparse();  // should output unmodified sgproject and it does. The deep copy
                         // mechanism works for the SgGlobal object. 

  // moving the output file to a new file, so that we can unparse the sgproject again without
  // overwriting the results
  char *outputfile = file.get_unparse_output_filename();
  string move = "mv " + string(outputfile) + " orig_" + string(outputfile); 
  system(move.c_str());

  // want to output modified sgproject
  file.set_root(root_copy);
  //sgproject->set_file(file);
  sgproject->unparse(); // or use: file.unparse();?
  
  // Unparsing the sgproject after adding the root_copy to the file-object (I want
  // to unparse the modified copy...), gives me an error message:
  //  /home/hauge2/ROSE/src/backend/unparser/unparse_stmt.C:1047: void Unparser::unparseFuncDefnStmt(SgStatement*, SgUnparse_Info&): Assertion `funcdefn_stmt->get_declaration() != __null' failed.
  
  return 0;
}
コード例 #4
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;
}
コード例 #5
0
ファイル: printRoseAST.cpp プロジェクト: nchaimov/undwarf
int
main ( int argc, char* argv[] )
   {
	Rose_STL_Container<std::string> l = CommandlineProcessing::generateArgListFromArgcArgv(argc,argv);
	 if ( CommandlineProcessing::isOptionWithParameter(l, "-taurose:","(v|verbose)",verbose ,false)) {
		std::cerr << "Verbose logging enabled" << std::endl;
		verbose = 1;
		std::cerr << "Verbose: " << verbose << std::endl;
	}
     SgProject* project = frontend(l);
     ROSE_ASSERT (project != NULL);

     SgFile & localFile = project->get_file(0);
     localFile.get_file_info()->display("localFile information");

     InheritedAttribute inheritedAttribute(0);

     visitorTraversal exampleTraversal;

     exampleTraversal.traverse(project,inheritedAttribute);

     return 0;
   }
コード例 #6
0
ファイル: testWave.C プロジェクト: billhoffman/rose-develop
int main( int argc, char * argv[] ) 
   {

     std::vector<std::string> newArgv(argv,argv+argc);
     newArgv.push_back("-rose:wave");

     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include/g++_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include/gcc_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include-staging/g++_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include-staging/gcc_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/usr/include/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/tests/CompileTest/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("<builtin>");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("<built-in>");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("<builltin>");


  // Build the AST used by ROSE
     SgProject* project = frontend(newArgv);
     ROSE_ASSERT(project != NULL);


  // Run internal consistency tests on AST
     AstTests::runAllTests(project);


     // Assume that there is only one file
     std::string filename;
     for(int i = 0 ; i < project->numberOfFiles(); i++)
     {
       SgSourceFile* file = isSgSourceFile(&project->get_file(i));
       if( file != NULL)
         filename = file->getFileName();

     };

     ROSE_ASSERT(filename != "");

     filename+=".out";
     filename = StringUtility::stripPathFromFileName(filename);


     //Output the macro diretives to the file
     ofstream myfile;
     myfile.open (filename.c_str());

     ROSE_ASSERT(myfile.is_open());
     std::cout << "Outputing to the file " << filename << std::endl;



     backend(project);
     print_out_all_macros(myfile, project);
  // Insert your own manipulation of the AST here...

  // Generate source code from AST and call the vendor's compiler
     return backend(project);
   }
コード例 #7
0
int main( int argc, char * argv[] ) {
    
    if(argc < 3){
        Usage(argc, argv);
    }
    
    char * roseTraceFile = argv[1];
    FILE * roseTraceFilePtr;
    
    if(!(roseTraceFilePtr = fopen(roseTraceFile, "rb"))){
        fprintf(stderr, "\n Failed to read TraceFile %s",roseTraceFile);
        exit(-1);
    }

    FILE * roseProjectDBFilePtr;
    const char * roseProjectDBFile = argv[2];
    // Open the DB file... Don't need lock for reading.
    if(!(roseProjectDBFilePtr = fopen(roseProjectDBFile, "r"))){
        fprintf(stderr, "\n Failed to read roseDBFile %s", roseProjectDBFile);
        exit(-1);
    }
    
    char fileName[PATH_MAX];
    // Read DB file and assign file Ids
    while(fgets(fileName, PATH_MAX, roseProjectDBFilePtr)){
        // kill \n
        fileName[strlen(fileName)-1] = '\0';
        idToFile.push_back(string(fileName));
    }
    fclose(roseProjectDBFilePtr);
    
    
    
    // Read all trace records from the trace
    uint64_t traceId;
    boost::unordered_map<uint64_t, SgNode*>::iterator it;
    std::set<uint64_t> fileSet;
    
    vector<uint64_t> traceRecordVector;
    
    
    while(fread(&traceId, sizeof(uint64_t), 1, roseTraceFilePtr)){
        uint32_t fileId = traceId >> 32;
        if (fileId > idToFile.size()) {
            cout<<"\n"<< std::hex << traceId << " MISSING FILE!!!! id" << std::hex << fileId;
            traceRecordVector.push_back(NULL);
        } else {
            // If we have not seen this file, add it to teh set of files we want to open
            if(fileSet.find(fileId) == fileSet.end()){
                fileSet.insert(fileId);
            }
            traceRecordVector.push_back(traceId);
        }
    }
    fclose(roseTraceFilePtr);
    
    // Now build AST for each file in the set.
    
    
    for(std::set<uint64_t>::iterator it = fileSet.begin(), e = fileSet.end(); it != e; it++) {
        // prepare args.
        
        uint32_t fileId = *it;
        int numArgs = argc - 2 + 1; // -2 becoz we remove the trace and DB file. +1 because we add the source file.
        char * arguments[numArgs];
        for(int i = 3 ; i < numArgs - 1; i++){
            arguments[i] = argv[i];
        }
        arguments[0] = argv[0];
        arguments[numArgs-1] = (char *) idToFile[fileId].c_str();
        
        // Generate the ROSE AST.
        SgProject* project = frontend(numArgs, arguments);
        // AST consistency tests (optional for users, but this enforces more of our tests)
        AstTests::runAllTests(project);
        
        // Build node to trace id map.
        for(int i = 0 ; i < project->numberOfFiles(); i++) {
            SgFile & file = project->get_file(i);
            IdToNodeMapper mapper(&file, string(roseProjectDBFile));
        }
    }
    
    // Now, print the mapping from trace id to its SgNode
    
    for( vector<uint64_t>::iterator it = traceRecordVector.begin(), e = traceRecordVector.end(); it != e; it++){
        uint64_t traceId = *it;
        uint32_t fileId = traceId >> 32;
        SgNode * curSgNode = idToNodeMap[traceId];
        if(idToNodeMap.find(traceId) != idToNodeMap.end())
            cout <<"\n" << std::hex << traceId << idToFile[fileId] << ":" << std::hex << curSgNode << ":" << curSgNode->class_name();
        else
            cout <<"\n" << std::hex << traceId << "HAS NO MAPPING!!!";
    }
    
    return 0;
    
}
コード例 #8
0
int main( int argc, char * argv[] ) {
    
    if(argc < 4){
        Usage(argc, argv);
    }
    
    int numTraces = 0;
    
    try
    {
        numTraces = boost::lexical_cast<int>(argv[1]); 
    }
    catch(...) {
        Usage(argc, argv);
    }
    
    
    FILE * roseTraceFilePtrs[numTraces];
    char * roseTraceFiles[numTraces];
    FILE * roseProjectDBFilePtr;
    const char * roseProjectDBFile;

    
    for(int i = 0 ; i < numTraces; i++) {
        roseTraceFiles[i] = argv[i+2];
        if(!(roseTraceFilePtrs[i] = fopen(roseTraceFiles[i], "rb"))){
            fprintf(stderr, "\n Failed to read TraceFile %s",roseTraceFiles[i]);
            exit(-1);
        }
    }
    
    // patch argv
    for(int i = numTraces + 2 ; i < argc; i++){
        argv[i - 1 - numTraces] = argv[i];
    }
    int patchedArgc = argc - (numTraces + 1);
    
    
    // Generate the ROSE AST.
    
    SgProject* project = frontend(patchedArgc ,argv);
    // AST consistency tests (optional for users, but this enforces more of our tests)
    AstTests::runAllTests(project);
    
    
    // Open the DB file... DOn't need lock for reading.
    roseProjectDBFile = project->get_projectSpecificDatabaseFile().c_str();
    if(!(roseProjectDBFilePtr = fopen(roseProjectDBFile, "r"))){
        fprintf(stderr, "\n Failed to read roseDBFile %s", roseProjectDBFile);
        exit(-1);
    }
    
    char fileName[PATH_MAX];
    // Read DB file and assign file Ids
    while(fgets(fileName, PATH_MAX, roseProjectDBFilePtr)){
        // kill \n
        fileName[strlen(fileName)-1] = '\0';
        idToFile.push_back(string(fileName));
    }
    fclose(roseProjectDBFilePtr);
    
    // Build node to trace id map.
    for(int i = 0 ; i < project->numberOfFiles(); i++) {
        SgFile & file = project->get_file(i);
        IdToNodeMapper mapper(&file, project->get_projectSpecificDatabaseFile());
    }
    
    // Read all trace records from all traces
    uint64_t traceId;
    boost::unordered_map<uint64_t, SgNode*>::iterator it;
    
    vector<SgNode *> traceRecordVector[numTraces];
    
    for(int curTraceNo = 0 ; curTraceNo < numTraces ; curTraceNo++) {
        while(fread(&traceId, sizeof(uint64_t), 1, roseTraceFilePtrs[curTraceNo])){
            uint32_t fileId = traceId >> 32;
            uint32_t nodeId = (traceId & 0xffffffff);
            
            if (fileId > idToFile.size()) {
                cout<<"\n"<< std::hex << traceId << " MISSING FILE!!!! id" << std::hex << fileId;
                traceRecordVector[curTraceNo].push_back(NULL);
            } else {
                it = idToNodeMap.find(traceId);
                if(it == idToNodeMap.end()){
                    cout<<"\n"<< std::hex << traceId << " can't map back!!!" << std::hex << fileId << std::hex << nodeId;
                    traceRecordVector[curTraceNo].push_back(NULL);
                } else {
                    cout<<"\n"<< std::hex << traceId << ":"<< idToFile[fileId] << ":" << std::hex << (*it).second << ":" << ((*it).second)->class_name();
                    traceRecordVector[curTraceNo].push_back((*it).second);
                }
            }
        }
        fclose(roseTraceFilePtrs[curTraceNo]);
    }
    
    
    // Now, compare traces till they start to diverge and populate them in a vector so that one can iterate over them.
    
    vector<SgNode *> commonPrefix;
    uint64_t minTraceSize = -1;
    uint64_t maxTraceSize = 0;

    for( int i = 0 ; i < numTraces; i++){
        if( traceRecordVector[i].size() < minTraceSize) {
            minTraceSize = traceRecordVector[i].size();
        }
        if( traceRecordVector[i].size() > maxTraceSize) {
            maxTraceSize = traceRecordVector[i].size();
        }
    }

    uint64_t commonPrefixLength = 0;
    for( ; commonPrefixLength < minTraceSize; commonPrefixLength++){
        SgNode * curSgNode = traceRecordVector[0][commonPrefixLength];
        for(int traceNo = 1 ; traceNo < numTraces ; traceNo++){
            if(traceRecordVector[traceNo][commonPrefixLength] != curSgNode){
                // Paths diverged
                cout<<"\n Paths diverge, common prefix length = " << commonPrefixLength;
                goto DONE;
            }
        }
        commonPrefix.push_back(curSgNode);
    }
    
    if(maxTraceSize == minTraceSize)
        cout<<"\n Paths match perfectly, length = " << commonPrefixLength;

    
DONE:
    // Print the common prefix nodes
    cout<<"\n Common prefix is:";
    for( uint64_t i = 0; i < commonPrefixLength ; i++){
        SgNode * node = commonPrefix[i];
        cout<<"\n"<< std::hex << node << ":" << node->class_name();
    }
    return 0;
    
}
コード例 #9
0
ファイル: unparser.C プロジェクト: 8l/rose
string globalUnparseToString ( SgNode* astNode, SgUnparse_Info* inputUnparseInfoPointer )
{
  // This global function permits any SgNode (including it's subtree) to be turned into a string

  // DQ (3/2/2006): Let's make sure we have a valid IR node!
     ROSE_ASSERT(astNode != NULL);

     string returnString;

  // all options are now defined to be false. When these options can be passed in
  // from the prompt, these options will be set accordingly.
     bool _auto                         = false;
     bool linefile                      = false;
     bool useOverloadedOperators        = false;
     bool num                           = false;

  // It is an error to have this always turned off (e.g. pointer = this; will not unparse correctly)
     bool _this                         = true;

     bool caststring                    = false;
     bool _debug                        = false;
     bool _class                        = false;
     bool _forced_transformation_format = false;
     bool _unparse_includes             = false;

  // printf ("In globalUnparseToString(): astNode->sage_class_name() = %s \n",astNode->sage_class_name());

     Unparser_Opt roseOptions( _auto,
                               linefile,
                               useOverloadedOperators,
                               num,
                               _this,
                               caststring,
                               _debug,
                               _class,
                               _forced_transformation_format,
                               _unparse_includes );

     int lineNumber = 0;  // Zero indicates that ALL lines should be unparsed

     // Initialize the Unparser using a special string stream inplace of the usual file stream 
     ostringstream outputString;

     SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
     string fileNameOfStatementsToUnparse;
     if (locatedNode == NULL)
        {
       // printf ("WARNING: applying AST -> string for non expression/statement AST objects \n");
          fileNameOfStatementsToUnparse = "defaultFileNameInGlobalUnparseToString";
        }
       else
        {
          ROSE_ASSERT (locatedNode != NULL);

       // DQ (5/31/2005): Get the filename from a traversal back through the parents to the SgFile
       // fileNameOfStatementsToUnparse = locatedNode->getFileName();
       // fileNameOfStatementsToUnparse = rose::getFileNameByTraversalBackToFileNode(locatedNode);
          if (locatedNode->get_parent() == NULL)
             {
            // DQ (7/29/2005):
            // Allow this function to be called with disconnected AST fragments not connected to 
            // a previously generated AST.  This happens in Qing's interface where AST fragements 
            // are built and meant to be unparsed.  Only the parent of the root of the AST 
            // fragement is expected to be NULL.
               fileNameOfStatementsToUnparse = locatedNode->getFileName();
             }
            else
             {
               fileNameOfStatementsToUnparse = rose::getFileNameByTraversalBackToFileNode(locatedNode);
             }
          
        }
     ROSE_ASSERT (fileNameOfStatementsToUnparse.size() > 0);

     Unparser roseUnparser ( &outputString, fileNameOfStatementsToUnparse, roseOptions, lineNumber );

  // Information that is passed down through the tree (inherited attribute)
  // Use the input SgUnparse_Info object if it is available.
     SgUnparse_Info* inheritedAttributeInfoPointer = NULL;
     if (inputUnparseInfoPointer != NULL)
        {
       // printf ("Using the input inputUnparseInfoPointer object \n");

       // Use the user provided SgUnparse_Info object
          inheritedAttributeInfoPointer = inputUnparseInfoPointer;
        }
       else
        {
       // DEFINE DEFAULT BEHAVIOUR FOR THE CASE WHEN NO inputUnparseInfoPointer (== NULL) IS 
       // PASSED AS ARGUMENT TO THE FUNCTION
       // printf ("Building a new Unparse_Info object \n");

       // If no input parameter has been specified then allocate one
       // inheritedAttributeInfoPointer = new SgUnparse_Info (NO_UNPARSE_INFO);
          inheritedAttributeInfoPointer = new SgUnparse_Info();
          ROSE_ASSERT (inheritedAttributeInfoPointer != NULL);

       // MS: 09/30/2003: comments de-activated in unparsing
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipComments() == false);

       // Skip all comments in unparsing
          inheritedAttributeInfoPointer->set_SkipComments();
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipComments() == true);
       // Skip all whitespace in unparsing (removed in generated string)
          inheritedAttributeInfoPointer->set_SkipWhitespaces();
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipWhitespaces() == true);

       // Skip all directives (macros are already substituted by the front-end, so this has no effect on those)
          inheritedAttributeInfoPointer->set_SkipCPPDirectives();
          ROSE_ASSERT (inheritedAttributeInfoPointer->SkipCPPDirectives() == true);
        }

     ROSE_ASSERT (inheritedAttributeInfoPointer != NULL);
     SgUnparse_Info & inheritedAttributeInfo = *inheritedAttributeInfoPointer;

  // Turn ON the error checking which triggers an error if the default SgUnparse_Info constructor is called
  // SgUnparse_Info::forceDefaultConstructorToTriggerError = true;

#if 1
  // DQ (10/19/2004): Cleaned up this code, remove this dead code after we are sure that this worked properly
  // Actually, this code is required to be this way, since after this branch the current function returns and
  // some data must be cleaned up differently!  So put this back and leave it this way, and remove the
  // "Implementation Note".

  // Both SgProject and SgFile are handled via recursive calls
     if ( (isSgProject(astNode) != NULL) || (isSgFile(astNode) != NULL) )
        {
       // printf ("Implementation Note: Put these cases (unparsing the SgProject and SgFile into the cases for nodes derived from SgSupport below! \n");

       // Handle recursive call for SgProject
          if (isSgProject(astNode) != NULL)
             {
               SgProject* project = isSgProject(astNode);
               ROSE_ASSERT(project != NULL);
               for (int i = 0; i < project->numberOfFiles(); i++)
                  {
                    SgFile* file = &(project->get_file(i));
                    ROSE_ASSERT(file != NULL);
                    string unparsedFileString = globalUnparseToString(file,inputUnparseInfoPointer);
                    string prefixString       = string("/* TOP:")      + string(rose::getFileName(file)) + string(" */ \n");
                    string suffixString       = string("\n/* BOTTOM:") + string(rose::getFileName(file)) + string(" */ \n\n");
                    returnString += prefixString + unparsedFileString + suffixString;
                  }
             }

       // Handle recursive call for SgFile
          if (isSgFile(astNode) != NULL)
             {
               SgFile* file = isSgFile(astNode);
               ROSE_ASSERT(file != NULL);
               SgGlobal* globalScope = file->get_root();
               ROSE_ASSERT(globalScope != NULL);
               returnString = globalUnparseToString(globalScope,inputUnparseInfoPointer);
             }
        }
       else
#endif
        {
       // DQ (1/12/2003): Only now try to trap use of SgUnparse_Info default constructor
       // Turn ON the error checking which triggers an error if the default SgUnparse_Info constructor is called
          SgUnparse_Info::set_forceDefaultConstructorToTriggerError(true);

          if (isSgStatement(astNode) != NULL)
             {
               SgStatement* stmt = isSgStatement(astNode);
               roseUnparser.unparseStatement ( stmt, inheritedAttributeInfo );
             }

          if (isSgExpression(astNode) != NULL)
             {
               SgExpression* expr = isSgExpression(astNode);
               roseUnparser.unparseExpression ( expr, inheritedAttributeInfo );
             }

          if (isSgType(astNode) != NULL)
             {
               SgType* type = isSgType(astNode);
               roseUnparser.unparseType ( type, inheritedAttributeInfo );
             }

          if (isSgSymbol(astNode) != NULL)
             {
               SgSymbol* symbol = isSgSymbol(astNode);
               roseUnparser.unparseSymbol ( symbol, inheritedAttributeInfo );
             }

          if (isSgSupport(astNode) != NULL)
             {
            // Handle different specific cases derived from SgSupport 
            // (e.g. template parameters and template arguments).
               switch (astNode->variantT())
                  {
#if 0
                    case V_SgProject:
                       {
                         SgProject* project = isSgProject(astNode);
                         ROSE_ASSERT(project != NULL);
                         for (int i = 0; i < project->numberOfFiles(); i++)
                            {
                              SgFile* file = &(project->get_file(i));
                              ROSE_ASSERT(file != NULL);
                              string unparsedFileString = globalUnparseToString(file,inputUnparseInfoPointer);
                              string prefixString       = string("/* TOP:")      + string(rose::getFileName(file)) + string(" */ \n");
                              string suffixString       = string("\n/* BOTTOM:") + string(rose::getFileName(file)) + string(" */ \n\n");
                              returnString += prefixString + unparsedFileString + suffixString;
                            }
                         break;
                       }
                    case V_SgFile:
                       {
                         SgFile* file = isSgFile(astNode);
                         ROSE_ASSERT(file != NULL);
                         SgGlobal* globalScope = file->get_root();
                         ROSE_ASSERT(globalScope != NULL);
                         returnString = globalUnparseToString(globalScope,inputUnparseInfoPointer);
                         break;
                       }
#endif
                    case V_SgTemplateParameter:
                       {
                         SgTemplateParameter* templateParameter = isSgTemplateParameter(astNode);
                         roseUnparser.unparseTemplateParameter(templateParameter,inheritedAttributeInfo);
                         break;
                       }
                    case V_SgTemplateArgument:
                       {
                         SgTemplateArgument* templateArgument = isSgTemplateArgument(astNode);
                         roseUnparser.unparseTemplateArgument(templateArgument,inheritedAttributeInfo);
                         break;
                       }
                    case V_SgInitializedName:
                       {
                      // QY: not sure how to implement this
                      // DQ (7/23/2004): This should unparse as a declaration 
                      // (type and name with initializer).
                         break;
                       }

                    case V_Sg_File_Info:
                       {
                      // DQ (5/11/2006): Not sure how or if we shoul implement this
                         break;
                       }

                 // Perhaps the support for SgFile and SgProject shoud be moved to this location?
                    default:
                         printf ("Error: default reached in node derived from SgSupport astNode = %s \n",astNode->sage_class_name());
                         ROSE_ABORT();
                }
             }

       // Turn OFF the error checking which triggers an if the default SgUnparse_Info constructor is called
          SgUnparse_Info::set_forceDefaultConstructorToTriggerError(false);

       // MS: following is the rewritten code of the above outcommented 
       //     code to support ostringstream instead of ostrstream.
          returnString = outputString.str();

       // Call function to tighten up the code to make it more dense
          if (inheritedAttributeInfo.SkipWhitespaces() == true)
             {
               returnString = roseUnparser.removeUnwantedWhiteSpace ( returnString );
             }

       // delete the allocated SgUnparse_Info object
          if (inputUnparseInfoPointer == NULL)
               delete inheritedAttributeInfoPointer;
        }

     return returnString;
   }
コード例 #10
0
ファイル: options.C プロジェクト: 8l/rose
void
TransformationSupport::getTransformationOptions ( SgNode* astNode, list<OptionDeclaration> & generatedList, string identifingTypeName )
   {
  // This function searches for variables of type ScopeBasedTransformationOptimization.  Variables
  // of type ScopeBasedTransformationOptimization are used to communicate optimizations from the
  // application to the preprocessor. If called from a project or file object it traverses down to
  // the global scope of the file and searches only the global scope, if called from and other
  // location within the AST it searches the current scope and then traverses the parent nodes to
  // find all enclosing scopes until in reaches the global scope.  At each scope it searches for
  // variables of type ScopeBasedTransformationOptimization.

  // printf ("######################### START OF TRANSFORMATION OPTION QUERY ######################## \n");

     ROSE_ASSERT (astNode != NULL);
     ROSE_ASSERT (identifingTypeName.c_str() != NULL);

#if 0
     printf ("In getTransformationOptions(): astNode->sage_class_name() = %s generatedList.size() = %d \n",
          astNode->sage_class_name(),generatedList.size());
     SgLocatedNode* locatedNode = isSgLocatedNode(astNode);
     if (locatedNode != NULL)
        {
          printf ("          locatedNode->get_file_info()->get_filename() = %s \n",locatedNode->get_file_info()->get_filename());
          printf ("          locatedNode->get_file_info()->get_line() = %d \n",locatedNode->get_file_info()->get_line());
        }
#endif

     switch (astNode->variant())
        {
          case ProjectTag:
             {
               SgProject* project = isSgProject(astNode);
               ROSE_ASSERT (project != NULL);

           //! Loop through all the files in the project and call the mainTransform function for each file
               int i = 0;
               for (i=0; i < project->numberOfFiles(); i++)
                  {
                    SgFile* file = &(project->get_file(i));

                 // printf ("Calling Query::traverse(SgFile,QueryFunctionType,QueryAssemblyFunctionType) \n");
                    getTransformationOptions ( file, generatedList, identifingTypeName );
                  }
               break;
             }

          case SourceFileTag:
             {
               SgSourceFile* file = isSgSourceFile(astNode);
               ROSE_ASSERT (file != NULL);
               SgGlobal* globalScope = file->get_globalScope();
               ROSE_ASSERT (globalScope != NULL);
               ROSE_ASSERT (isSgGlobal(globalScope) != NULL);
               getTransformationOptions ( globalScope, generatedList, identifingTypeName );
               break;
             }

       // Global Scope
          case GLOBAL_STMT:
             {
               SgGlobal* globalScope = isSgGlobal(astNode);
               ROSE_ASSERT (globalScope != NULL);

               SgSymbolTable* symbolTable = globalScope->get_symbol_table();
               ROSE_ASSERT (symbolTable != NULL);
               getTransformationOptions ( symbolTable, generatedList, identifingTypeName );

            // printf ("Processed global scope, exiting .. \n");
            // ROSE_ABORT();
               break;
             }

          case SymbolTableTag:
             {
            // List the variable in each scope
            // printf ("List all the variables in this symbol table! \n");
               SgSymbolTable* symbolTable = isSgSymbolTable(astNode);
               ROSE_ASSERT (symbolTable != NULL);

               bool foundTransformationOptimizationSpecifier = false;

            // printf ("Now print out the information in the symbol table for this scope: \n");
            // symbolTable->print();

#if 0
            // I don't know when a SymbolTable is given a name!
               printf ("SymbolTable has a name = %s \n",
                    (symbolTable->get_no_name()) ? "NO: it has no name" : "YES: it does have a name");
               if (!symbolTable->get_no_name())
                    printf ("SymbolTable name = %s \n",symbolTable->get_name().str());
                 else
                    ROSE_ASSERT (symbolTable->get_name().str() == NULL);
#endif

               if (symbolTable->get_table() != NULL)
                  {
                    SgSymbolTable::hash_iterator i = symbolTable->get_table()->begin();
                    int counter = 0;
                    while (i != symbolTable->get_table()->end())
                       {
                         ROSE_ASSERT ( isSgSymbol( (*i).second ) != NULL );

                      // printf ("Initial info: number: %d pair.first (SgName) = %s pair.second (SgSymbol) sage_class_name() = %s \n",
                      //      counter,(*i).first.str(),(*i).second->sage_class_name());

                         SgSymbol* symbol = isSgSymbol((*i).second);
                         ROSE_ASSERT ( symbol != NULL );
                         SgType* type = symbol->get_type();
                         ROSE_ASSERT ( type != NULL );

                         SgNamedType* namedType = isSgNamedType(type);
                         string typeName;
                         if (namedType != NULL)
                            {
                              SgName n = namedType->get_name();
                              typeName = namedType->get_name().str();
                           // char* nameString = namedType->get_name().str();
                           // printf ("Type is: (named type) = %s \n",nameString);
                              ROSE_ASSERT (identifingTypeName.c_str() != NULL);
                           // ROSE_ASSERT (typeName != NULL);
                           // printf ("In getTransformationOptions(): typeName = %s identifingTypeName = %s \n",typeName.c_str(),identifingTypeName.c_str());
                           // if ( (typeName != NULL) && ( typeName == identifingTypeName) )
                              if ( typeName == identifingTypeName )
                                 {
                                // Now look at the parameter list to the constructor and save the
                                // values into the list.

                                // printf ("Now save the constructor arguments! \n");

                                   SgVariableSymbol* variableSymbol = isSgVariableSymbol(symbol);

                                   if ( variableSymbol != NULL )
                                      {
                                        SgInitializedName* initializedNameDeclaration = variableSymbol->get_declaration();
                                        ROSE_ASSERT (initializedNameDeclaration != NULL);

                                        SgDeclarationStatement* declarationStatement = initializedNameDeclaration->get_declaration();
                                        ROSE_ASSERT (declarationStatement != NULL);

                                        SgVariableDeclaration* variableDeclaration = isSgVariableDeclaration(declarationStatement);
                                        ROSE_ASSERT (variableDeclaration != NULL);

                                        getTransformationOptionsFromVariableDeclarationConstructorArguments(variableDeclaration,generatedList);

                                        foundTransformationOptimizationSpecifier = true;

                                     // printf ("Exiting after saving the constructor arguments! \n");
                                     // ROSE_ABORT();
                                      }
                                     else
                                      {
#if 0
                                        printf ("Not a SgVariableSymbol: symbol->sage_class_name() = %s \n",
                                             symbol->sage_class_name());
#endif
                                      }
                                 }
                                else
                                 {
#if 0
                                   printf ("typeName != identifingTypeName : symbol->sage_class_name() = %s \n",
                                        symbol->sage_class_name());
#endif
#if 0
                                // I don't think this should ever be NULL (but it is sometimes)
                                   if (typeName != NULL)
                                        printf ("typeName == NULL \n");
#endif
                                 }
                            }
                           else
                            {
                              typeName = (char *)type->sage_class_name();
                            }

                      // printf ("In while loop at the base: counter = %d \n",counter);
                         i++;
                         counter++;
                       }
                  }
                 else
                  {
                 // printf ("Pointer to symbol table is NULL \n");
                  }

            // printf ("foundTransformationOptimizationSpecifier = %s \n",foundTransformationOptimizationSpecifier ? "true" : "false");

            // SgSymbolTable objects don't have a parent node (specifically they lack a get_parent
            // member function in the interface)!
               break;
             }

          case BASIC_BLOCK_STMT:
             {
            // List the variable in each scope
            // printf ("List all the variables in this scope! \n");
               SgBasicBlock* basicBlock = isSgBasicBlock(astNode);
               ROSE_ASSERT (basicBlock != NULL);

               SgSymbolTable* symbolTable = basicBlock->get_symbol_table();
               ROSE_ASSERT (symbolTable != NULL);
               getTransformationOptions ( symbolTable, generatedList, identifingTypeName );

            // Next go (fall through this case) to the default case so that we traverse the parent
            // of the SgBasicBlock.
            // break;
             }

          default:
            // Most cases will be the default (this is by design)
            // printf ("default in switch found in globalQueryGetListOperandStringFunction() (sage_class_name = %s) \n",astNode->sage_class_name());

            // Need to recursively backtrack through the parents until we reach the SgGlobal (global scope)
               SgStatement* statement = isSgStatement(astNode);
               if (statement != NULL)
                  {
                    SgNode* parentNode = statement->get_parent();
                    ROSE_ASSERT (parentNode != NULL);
//                  printf ("parent = %p parentNode->sage_class_name() = %s \n",parentNode,parentNode->sage_class_name());
                    SgStatement* parentStatement = isSgStatement(parentNode);
                    if (parentStatement == NULL)
                       {
                         printf ("parentStatement == NULL: statement (%p) is a %s \n",statement,statement->sage_class_name());
                         printf ("parentStatement == NULL: statement->get_file_info()->get_filename() = %s \n",statement->get_file_info()->get_filename());
                         printf ("parentStatement == NULL: statement->get_file_info()->get_line() = %d \n",statement->get_file_info()->get_line());
                       }
                    ROSE_ASSERT (parentStatement != NULL);

                 // Call this function recursively (directly rather than through the query mechanism)
                    getTransformationOptions ( parentStatement, generatedList, identifingTypeName );
                  }
                 else
                  {
                 // printf ("astNode is not a SgStatement! \n");
                  }

               break;
        }

#if 0
     printf ("At BASE of getTransformationOptions(): astNode->sage_class_name() = %s size of generatedList = %d \n",
          astNode->sage_class_name(),generatedList.size());
#endif

  // printf ("######################### END OF TRANSFORMATION OPTION QUERY ######################## \n");
   }
コード例 #11
0
ファイル: slicemain.cpp プロジェクト: Federico2014/edg4x-rose
int main(int argc, char *argv[])
{
   SgProject *sgproject = frontend(argc,argv);
 
  //copying the sgproject so that the code isn't destructive
   // OBS: THIS COPYING HAS NO EFFECT!!!
   // SgProject *sgproject = sgproject_original;  
  ROSE_ASSERT(sgproject != NULL);

  char* filename = sgproject->get_file(0).getFileName(); 
  char* outputname = sgproject->get_file(0).get_unparse_output_filename();
  char* interface;
  if(argv[2] == NULL){
    cout << "Please choose an interface number (1, (2) or 3)." << endl;
    cout << "usage: ./slice inputfile interface_number\n\n" << endl;
    return 0;
  }
  else{
    interface = argv[2];
    //cout << "interface = " << interface << endl; 

    // COMPLETE SLICE
    if(*interface == '1'){  
      //slice the code
      Slicing::completeSlice(sgproject);
      cout << "RESULT OF SLICING:" << endl;
      printf("Slicing of %s went OK. The result is in the file %s.\n\n",filename,outputname);
    }

    // This slicing is slightly meaningless
    else if(*interface == '2'){
      set<SgNode*> stmt;
      Slicing::sliceOnlyStmtWithControl(sgproject, stmt);
      cout << "RESULT OF SLICING;" << endl;
      // meaningless output...? includes return statements...
      set<SgNode*>::const_iterator s;
      for(s=stmt.begin();s!=stmt.end();++s){
        cout <<"    - " << (*s)->unparseToString() << endl;
      }  
      cout << "\n(No rose_filename written. Only the above list is the output.)\n\n" <<endl;
    }

    // ONLY STATEMENTS
    else if(*interface == '3'){
      set<SgNode*> stmt_in_slice;
      Slicing::sliceOnlyStmts(sgproject, stmt_in_slice);
      
      cout << "RESULT OF SLICING:" << endl;
      set<SgNode*>::const_iterator s;
      for(s=stmt_in_slice.begin();s!=stmt_in_slice.end();++s){
        cout <<"    - " << (*s)->unparseToString() << endl;
      }  
      cout << "\n(No rose_filename written. Only the above list is the output.)\n\n" <<endl;
    }
  }



  //  backend(sgproject);  
  /* The reason for not calling backend:
     
  Calling prelink utility ...
  sh: line 1: edg_prelink: command not found
sl  slice: /home/hauge2/ROSE/src/roseSupport/templateSupport.C:236: void instantiateTemplates(SgProject*): Assertion `errorCode == 0' failed.
  */
  //delete sgproject;
  
  return 0;
}
コード例 #12
0
ファイル: testPruning.C プロジェクト: 8l/rose
int main( int argc, char * argv[] )
   {

     {
       std::vector<std::string> newArgv(argv,argv+argc);
       newArgv.push_back("-rose:skip_rose");
       SgProject* project = frontend(newArgv);
       backend(project);

     }
     std::vector<std::string> newArgv(argv,argv+argc);
     newArgv.push_back("-rose:wave");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include/g++_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include/gcc_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include-staging/g++_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/include-staging/gcc_HEADERS/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/usr/include/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("/tests/CompileTest/");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("<builtin>");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("<built-in>");
     newArgv.push_back("-rose:excludePath");
     newArgv.push_back("<builltin>");



  // Build the AST used by ROSE
     SgProject* project = frontend(newArgv);
     ROSE_ASSERT(project != NULL);

  // Build a list of functions within the AST
     AnalyzeMacroCalls* macroCalls = new AnalyzeMacroCalls(project, false, std::cerr);

  // Assume that there is only one file
     std::string filename;
     for(int i = 0 ; i < project->numberOfFiles(); i++)
     {
       SgSourceFile* file = isSgSourceFile(&project->get_file(i));
       if( file != NULL)
         filename = file->getFileName();

     };

     ROSE_ASSERT(filename != "");

     filename+=".out";
     filename = StringUtility::stripPathFromFileName(filename);

     ofstream myfile;
     myfile.open (filename.c_str());

     ROSE_ASSERT(myfile.is_open());
     std::cout << "Outputing to the file " << filename << std::endl;


     macroCalls->print_out_all_macros(myfile);
     //     return backend(project);
     myfile.close();

   }