/** * handling error occured due to failed assertion * this error handler only works during parser phase since it uses * Token_t to know the line number * TODO: we need to make this function more general **/ void fortran_error_handler(int signum) { // get the current filename std::string sFilename = getCurrentFilename(); if (sFilename.size()==0) { fprintf(stderr, "ERROR while parsing the source code\n"); } else { SgScopeStatement* scope = astScopeStack.front(); SgStatement* lastStatement = scope; SgStatementPtrList statementList = scope->generateStatementList(); if (statementList.empty() == false) { lastStatement = statementList.back(); } int lineNumberOfLastStatement = (astScopeStack.empty() == false) ? lastStatement->get_file_info()->get_line() : 0; // get the latest token parsed if (lineNumberOfLastStatement > 0) std::cerr <<"FATAL ERROR in file "<<sFilename<<":"<<lineNumberOfLastStatement<<std::endl; else std::cerr <<"FATAL ERROR while parsing "<<sFilename<<std::endl; } fflush(NULL); // flush all stdio fortran_error_handler_end(); exit(-1); }
void CompassAnalyses::DefaultCase::Traversal:: visit(SgNode* node) { SgSwitchStatement* theSwitch = isSgSwitchStatement(node); if (!theSwitch) return; bool has_default = false; if (isSgBasicBlock(theSwitch->get_body())) { SgBasicBlock* BBlock = isSgBasicBlock(theSwitch->get_body()); //I should maybe do more sanity checking for nulls here SgStatementPtrList BBlockStmts = BBlock->get_statements(); for (Rose_STL_Container<SgStatement*>::iterator j = BBlockStmts.begin(); j != BBlockStmts.end(); j++) { if (isSgDefaultOptionStmt(*j)){ has_default = true; break; } } } else { if (isSgDefaultOptionStmt(theSwitch->get_body())) { has_default = true; } } if (!has_default){ output->addOutput(new CheckerOutput(node)); } // Implement your traversal here. } //End of the visit function.
void forOnceThrough(SgForStatement* forStat) { SgStatementPtrList ptr = forStat->get_init_stmt(); for (SgStatementPtrList::iterator i = ptr.begin(); i != ptr.end(); i++) { std::string statement_out = getSgStatement(*i); std::cout << ";;statement out:\n" << statement_out << std::endl; } std::string body_stat = getSgStatement(forStat->get_loop_body()); std::cout << ";;body:\n" << body_stat << std::endl; return; }
void resetTargetStatementAndLocation ( SgStatement* & target, const SgStatementPtrList & statementList, MidLevelCollectionTypedefs::PlacementPositionEnum & locationInScope ) { if (statementList.size() > 0) { // Get the first statement if (locationInScope == MidLevelCollectionTypedefs::TopOfCurrentScope) { // printf ("Case of StatementScope and TopOfCurrentScope \n"); target = returnFirstOrLastStatementFromCurrentFile(target,statementList,true); locationInScope = MidLevelCollectionTypedefs::BeforeCurrentPosition; } // Get the last statement if (locationInScope == MidLevelCollectionTypedefs::BottomOfCurrentScope) { // printf ("Case of StatementScope and BottomOfCurrentScope \n"); // declarationStatement = *(declarationList.rbegin()); target = returnFirstOrLastStatementFromCurrentFile(target,statementList,false); locationInScope = MidLevelCollectionTypedefs::AfterCurrentPosition; } } else { printf ("Sorry, not implemented: insertion into empty scope \n"); ROSE_ASSERT (1 == 2); } }
void getSgBasicBlock(SgBasicBlock* basicBlock) { std::string basicBlockString; std::vector<std::string> basicBlockStrings; SgStatementPtrList statements = basicBlock->get_statements(); for (SgStatementPtrList::iterator i = statements.begin(); i != statements.end(); i++) { std::string ithStatement = getSgStatement(*i); basicBlockStrings.push_back(ithStatement); } if (basicBlockStrings.size() == 0) { basicBlockString = ""; } else if (basicBlockStrings.size() == 1) { basicBlockString = "\n" + basicBlockStrings[0]; } else { basicBlockString = "\n"; } return; }
ForLoop::ForLoop( SgForStatement * l ) : BasicNode(LOOPHEAD), myLoop(l), myLoopType(UNDEFINED), start(NULL), end(NULL), body(NULL), back_edge(NULL), out(NULL), Iter(false) { /* STEP 1 : Get initialization expression and symbol */ SgStatementPtrList stmList = myLoop->get_init_stmt(); if ( stmList.size() != 1 ) { report_error("Too many init statements",l); } else if ( isSgVariableDeclaration(stmList[0]) ) { SgInitializedNamePtrList initList = isSgVariableDeclaration(stmList[0])->get_variables(); if ( initList.size() != 1 ) { report_error("To many induction variables",l); } else { SgInitializedName * initName = initList[0]; if ( isSgAssignInitializer(initName->get_initializer()) ) { symbol = initName->get_name().getString(); start = isSgAssignInitializer(initName->get_initializer())->get_operand(); } else { report_error("Loop initializer is too complecated",initName); } } } else if ( isSgExprStatement(stmList[0]) ) { SgExpression * exp = isSgExprStatement(stmList[0])->get_expression(); if ( isSgAssignOp(exp) ) { SgExpression * lhs = isSgAssignOp(exp)->get_lhs_operand(); SgExpression * rhs = isSgAssignOp(exp)->get_rhs_operand(); if ( isSgVarRefExp(lhs) ) { symbol = isSgVarRefExp(lhs)->get_symbol()->get_name().getString(); start = rhs; } else { report_error("LHS of expression must be a single variable",exp); } } else { report_error("Init expression must be an Assign operation",exp); } } else { report_error("Loop initialization is not recognized",l); } /* STEP 2 : Get the test expression */ SgExprStatement * expStm = isSgExprStatement(myLoop->get_test()); if ( expStm ) { SgExpression * exp = expStm->get_expression(); if ( isSgLessOrEqualOp(exp) ) { SgBinaryOp * binOp = isSgBinaryOp(exp); string name = isSgVarRefExp(isSgBinaryOp(exp)->get_lhs_operand())->get_symbol()->get_name().getString(); if ( name != symbol ) report_error("Loop init and test variable miss-match",exp); end = binOp->get_rhs_operand(); } else if ( isSgLessThanOp(exp) ) { SgBinaryOp * binOp = isSgBinaryOp(exp); string name = isSgVarRefExp(binOp->get_lhs_operand())->get_symbol()->get_name().getString(); if ( name != symbol ) report_error("Loop init and test variable miss-match",exp); SgExpression * tempExp = SageInterface::copyExpression(binOp->get_rhs_operand()); end = buildSubtractOp( tempExp, buildIntVal(1) ); end->set_need_paren(true); tempExp = buildLessOrEqualOp( SageInterface::copyExpression(binOp->get_lhs_operand()), end ); SageInterface::replaceExpression(exp, tempExp, false); } else { report_error("Test expression is not recognized. Re-write the loop or normilize it accordingly",exp); } } else { report_error("Test expression is not recognized. Sorry !", l); } /* STEP 3 : Check the stride */ if ( !isSgPlusPlusOp(l->get_increment()) ) report_error("Increment expression is not recognized. Re-write the loop or normilize it accordingly. Note: Only \"++\" operator supported.",l); /* STEP 4 : Link with Loop Tail node */ back_edge = new ForLoop(start,end,symbol,l,this,this,LOOPTAIL); body = back_edge; }
Rose_STL_Container< ControlStructureContainer * >queryFindCommentsInScope (const string stringPrefixToMatch, const string stringToMatch, SgScopeStatement * sageScopeStatement) { ROSE_ASSERT (stringPrefixToMatch.length () > 0); ROSE_ASSERT (stringToMatch.length () > 0); ROSE_ASSERT (sageScopeStatement != NULL); Rose_STL_Container< ControlStructureContainer * >returnList; //find all pragmas who match the stringToMatch //cout << "Before pragma search" << endl; /*list < SgNode * >pragmaStatements = NodeQuery::querySubTree (sageScopeStatement, new SgName (stringToMatch.c_str ()), NodeQuery::PragmaDeclarationFromName); */ //list<SGNode*> pragmaStatements ; //cout << "After pragma search" << endl; /* cout << "BEFORE LIST" << endl; list < SgNode * >pragmaStatements = queryNodePragmaStatementFromName2(sageScopeStatement, new SgName(stringToMatch.c_str())); cout << "AFTER LIST" << endl;*/ //return the pragmas in containers /* for (list < SgNode * >::iterator i = pragmaStatements.begin (); i != pragmaStatements.end (); ++i) { SgPragmaDeclaration *sagePragma = isSgPragmaDeclaration (*i); ROSE_ASSERT (sagePragma); ROSE_ASSERT (sagePragma->get_pragma () != NULL); ROSE_ASSERT (sagePragma->get_pragma ()->get_pragma ()); ControlStructureContainer *container = new ControlStructureContainer (); container->setPragmaString (sagePragma->get_pragma ()->get_pragma ()); container->setAssociatedStatement (sagePragma); returnList.push_back (container); } */ //find all statements in the current scope if (sageScopeStatement->variantT () == V_SgClassDefinition) { SgDeclarationStatementPtrList statementsInScope = sageScopeStatement->getDeclarationList (); SgDeclarationStatementPtrList::iterator i; for (i = statementsInScope.begin (); i != statementsInScope.end (); i++) { SgLocatedNode *locatedNode = isSgLocatedNode (*i); ROSE_ASSERT (locatedNode != NULL); //find all comments attached to current node. AttachedPreprocessingInfoType *comments = locatedNode->getAttachedPreprocessingInfo (); if(locatedNode->variantT() == V_SgPragmaDeclaration){ SgPragmaDeclaration* sagePragmaDeclaration = isSgPragmaDeclaration(locatedNode); ROSE_ASSERT( sagePragmaDeclaration ); ROSE_ASSERT( sagePragmaDeclaration->get_pragma() != NULL ); string pragmaDeclarationString = sagePragmaDeclaration->get_pragma()->get_pragma(); //extract the part before the leftmost = is pragmaDeclarationString pragmaDeclarationString = pragmaDeclarationString.substr(0,pragmaDeclarationString.find("=")); //if the name-criteria is met accept node if(pragmaDeclarationString.find( stringToMatch ) != string::npos ){ cout << pragmaDeclarationString << endl; ControlStructureContainer *container = new ControlStructureContainer (); container->setPragmaString (sagePragmaDeclaration->get_pragma ()->get_pragma ()); container->setAssociatedStatement (sagePragmaDeclaration); returnList.push_back (container); } } if (comments != NULL) { //We need to find comments which fits the criteria printf ("Found attached comments (at %p of type: %s): \n", locatedNode, locatedNode->sage_class_name ()); AttachedPreprocessingInfoType::iterator j; for (j = comments->begin (); j != comments->end (); j++) { ROSE_ASSERT ((*j) != NULL); string comment = (*j)->getString (); //see if comment begins with stringPrefixToMatch string tempString = comment.substr (0, comment.find (' ')); if (tempString == stringPrefixToMatch) { //+stringPrefixToMatch ){ //cout << "Found string" << endl; comment = StringUtility::copyEdit (comment, stringPrefixToMatch, ""); //see if the comment has an element which matches the stringToMatch if (comment.find (stringToMatch) != string::npos) { //puit the matching comment into a container ControlStructureContainer *container = new ControlStructureContainer (); container->setPragmaString (comment); container->setAssociatedStatement (locatedNode); returnList.push_back (container); } } // printf (" Attached Comment (relativePosition=%s):\n %s\n Next comment: \n", // ((*j)->relativePosition == PreprocessingInfo::before) ? "before" : "after",(*j)->getString()); } } } } else { // AS 12/18/03 PS!! The same as the above, but a different iterator. Will replace this when a // different solution has arisen. PS!! SgStatementPtrList statementsInScope = sageScopeStatement->getStatementList (); SgStatementPtrList::iterator i; for (i = statementsInScope.begin (); i != statementsInScope.end (); i++) { SgLocatedNode *locatedNode = isSgLocatedNode (*i); ROSE_ASSERT (locatedNode != NULL); if(locatedNode->variantT() == V_SgPragmaDeclaration){ SgPragmaDeclaration* sagePragmaDeclaration = isSgPragmaDeclaration(locatedNode); ROSE_ASSERT( sagePragmaDeclaration ); ROSE_ASSERT( sagePragmaDeclaration->get_pragma() != NULL ); string pragmaDeclarationString = sagePragmaDeclaration->get_pragma()->get_pragma(); //extract the part before the leftmost = is pragmaDeclarationString pragmaDeclarationString = pragmaDeclarationString.substr(0,pragmaDeclarationString.find("=")); //if the name-criteria is met accept node if(pragmaDeclarationString.find( stringToMatch ) != string::npos ){ cout << pragmaDeclarationString << endl; ControlStructureContainer *container = new ControlStructureContainer (); container->setPragmaString (sagePragmaDeclaration->get_pragma ()->get_pragma ()); container->setAssociatedStatement (sagePragmaDeclaration); returnList.push_back (container); } } //find all comments attached to current node. AttachedPreprocessingInfoType *comments = locatedNode->getAttachedPreprocessingInfo (); if (comments != NULL) { //We need to find comments which fits the criteria //printf ("Found attached comments (at %p of type: %s): \n",locatedNode,locatedNode->sage_class_name()); AttachedPreprocessingInfoType::iterator j; for (j = comments->begin (); j != comments->end (); j++) { ROSE_ASSERT ((*j) != NULL); string comment = (*j)->getString (); //see if comment begins with stringPrefixToMatch string tempString = comment.substr (0, comment.find (' ')); if (tempString == stringPrefixToMatch) { //+stringPrefixToMatch ){ comment = StringUtility::copyEdit (comment, stringPrefixToMatch, ""); cout << "And the string is: " << comment << endl; if (comment.find (stringToMatch) != string::npos) { cout << "And even the string is matched." << endl; //ROSE_ASSERT(comment.find('=') != comment.length()); //string variableName = comment.substr(comment.find(stringToMatch), comment.find('=')); cout << "And the string is a match" << endl; //puit the matching comment into a container ControlStructureContainer *container = new ControlStructureContainer (); container->setPragmaString (comment); container->setAssociatedStatement (locatedNode); returnList.push_back (container); } } /* printf (" Attached Comment (relativePosition=%s):\n %s\n Next comment: \n", ((*j)->relativePosition == PreprocessingInfo::before) ? "before" : "after", (*j)->getString ());*/ } } } } return returnList; } /* End function: queryFindCommentsInScope() */
int main(int argc,char** argv) { SgProject* proj = frontend(argc,argv); fixAllPrefixPostfix(proj); initializeScopeInformation(proj); SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj); SgFunctionDefinition* mainDef = mainDecl->get_definition(); //SageInterface::rebuildSymbolTable(mainDef); StaticCFG::CFG cfg(mainDef); SgIncidenceDirectedGraph *g = cfg.getGraph(); PathCollector* pathCollector = new PathCollector(g,&cfg); std::vector<SgNode*> scopeNodes = NodeQuery::querySubTree(mainDef,V_SgScopeStatement); std::vector<SgGraphNode*> visited; std::vector<SgNode*> nodes = NodeQuery::querySubTree(mainDef,V_SgWhileStmt); std::vector<SgNode*>::iterator node = nodes.begin(); for (; node != nodes.end(); node++) { SgScopeStatement* scopeOfWhile = SageInterface::getEnclosingScope(*node); SgStatementPtrList statementsInScope = scopeOfWhile->getStatementList(); SgStatementPtrList::iterator statPtr = statementsInScope.begin(); std::set<SgPragmaDeclaration*> prdecls; for (; statPtr!=statementsInScope.end();statPtr++) { if (isSgPragmaDeclaration(*statPtr)) { prdecls.insert(isSgPragmaDeclaration(*statPtr)); } } //SgExprStatement* boundingConditionStatement = isSgExprStatement(isSgWhileStmt(*node)->get_condition()); //SgExpression* boundingCondition = boundingConditionStatement->get_expression(); SgStatement* body = (isSgWhileStmt(*node)->get_body()); std::vector<std::vector<SgGraphNode*> > paths = pathCollector->getPaths(); std::cout << getPrelude() << std::endl; SgGraphNode* whileStart = cfg.cfgForBeginning(isSgWhileStmt(*node)); SgGraphNode* whileEnd = cfg.cfgForEnd(isSgWhileStmt(*node)); collectPaths(whileStart,whileEnd, pathCollector); SgGraphNode* whileOut = getWhileEndNode(isSgWhileStmt(*node),pathCollector); SgGraphNode* bodyStart = cfg.cfgForBeginning(isSgWhileStmt(*node)->get_body()); SgGraphNode* bodyEnd = cfg.cfgForEnd(isSgWhileStmt(*node)->get_body()); pathCollector->clearPaths(); collectPaths(bodyStart,whileOut,pathCollector); paths.clear(); paths = pathCollector->getPaths(); std::vector<std::vector<SgGraphNode*> >::iterator i = paths.begin(); std::set<SgVariableSymbol*> vars = getVars(pathCollector); std::string vardecls; std::string initrule; std::vector<std::string> rules= getRules(*node,pathCollector, vars, vardecls,initrule); std::cout << vardecls << std::endl; for (int i = 0; i < rules.size(); i++) { std::cout << rules[i] << std::endl; } std::set<SgPragmaDeclaration*>::iterator pr = prdecls.begin(); for (; pr != prdecls.end(); pr++) { std::set<std::string> variables; std::vector<std::string> s_expressions; std::string prag_str = get_pragma_string(*pr); bool initPrag; /*std::string rhs =*/ translateToS_Expr(prag_str,variables,s_expressions,initPrag); if (s_expressions.size() > 0) { std::string queryResult; if (initPrag) { queryResult = assumptionPragma(s_expressions,initrule); } else { queryResult = queryPragma(s_expressions,initrule); } std::cout << queryResult << std::endl; } } } backend(proj); return 0; }
void SgNode::insertSourceCode ( SgProject & project, const char* sourceCodeString, const char* localDeclaration, const char* globalDeclaration, bool locateNewCodeAtTop, bool isADeclaration ) { // If this function is useful only for SgBasicBlock then it should be put into that class directly. // This function is used to insert code into AST object for which insertion make sense: // (specifically any BASIC_BLOCK_STMT) if (variant() != BASIC_BLOCK_STMT) { printf ("ERROR: insert only make since for BASIC_BLOCK_STMT statements (variant() == variant()) \n"); ROSE_ABORT(); } SgBasicBlock* currentBlock = isSgBasicBlock(this); ROSE_ASSERT (currentBlock != NULL); // printf ("##### Calling SgNode::generateAST() \n"); #if 0 printf ("In insertSourceCode(): globalDeclaration = \n%s\n",globalDeclaration); printf ("In insertSourceCode(): localDeclaration = \n%s\n",localDeclaration); printf ("In insertSourceCode(): sourceCodeString = \n%s\n",sourceCodeString); #endif // SgNode* newTransformationAST = generateAST (project,sourceCodeString,globalDeclaration); // ROSE_ASSERT (newTransformationAST != NULL); SgStatementPtrList* newTransformationStatementListPtr = generateAST (project,sourceCodeString,localDeclaration,globalDeclaration,isADeclaration); ROSE_ASSERT (newTransformationStatementListPtr != NULL); ROSE_ASSERT (newTransformationStatementListPtr->size() > 0); // printf ("##### DONE: Calling SgNode::generateAST() \n"); // get a reference to the statement list out of the basic block SgStatementPtrList & currentStatementList = currentBlock->get_statements(); if (locateNewCodeAtTop == true) { // Insert at top of list (pull the elements off the bottom of the new statement list to get the order correct // printf ("Insert new statements (new statement list size = %d) at the top of the block (in reverse order to preset the order in the final block) \n",newTransformationStatementListPtr->size()); SgStatementPtrList::reverse_iterator transformationStatementIterator; for (transformationStatementIterator = newTransformationStatementListPtr->rbegin(); transformationStatementIterator != newTransformationStatementListPtr->rend(); transformationStatementIterator++) { // Modify where a statement is inserted to avoid dependent variables from being inserted // before they are declared. // Get a list of the variables // Generate the list of types used within the target subtree of the AST list<string> typeNameStringList = NameQuery::getTypeNamesQuery ( *transformationStatementIterator ); int statementCounter = 0; int previousStatementCounter = 0; // Declaration furthest in source sequence of all variables referenced in code to be inserted (last in source sequence order) // SgStatementPtrList::iterator furthestDeclarationInSourceSequence = NULL; SgStatementPtrList::iterator furthestDeclarationInSourceSequence; #if 0 string unparsedDeclarationCodeString = (*transformationStatementIterator)->unparseToString(); ROSE_ASSERT (unparsedDeclarationCodeString.c_str() != NULL); printf ("unparsedDeclarationCodeString = %s \n",unparsedDeclarationCodeString.c_str()); #endif if ( typeNameStringList.size() > 0 ) { // There should be at least one type in the statement ROSE_ASSERT (typeNameStringList.size() > 0); // printf ("typeNameStringList.size() = %d \n",typeNameStringList.size()); // printf ("This statement has a dependence upon a variable of some type \n"); // Loop over all the types and get list of variables of each type // (so they can be declared properly when the transformation is compiled) list<string>::iterator typeListStringElementIterator; for (typeListStringElementIterator = typeNameStringList.begin(); typeListStringElementIterator != typeNameStringList.end(); typeListStringElementIterator++) { // printf ("Type = %s \n",(*typeListStringElementIterator).c_str()); // Find a list of names of variable of type (*listStringElementIterator) list<string> operandNameStringList = NameQuery::getVariableNamesWithTypeNameQuery ( *transformationStatementIterator, *typeListStringElementIterator ); // There should be at least one variable of that type in the statement ROSE_ASSERT (operandNameStringList.size() > 0); // printf ("operandNameStringList.size() = %d \n",operandNameStringList.size()); // Loop over all the types and get list of variable of each type list<string>::iterator variableListStringElementIterator; for (variableListStringElementIterator = operandNameStringList.begin(); variableListStringElementIterator != operandNameStringList.end(); variableListStringElementIterator++) { #if 0 printf ("Type = %s Variable = %s \n", (*typeListStringElementIterator).c_str(), (*variableListStringElementIterator).c_str()); #endif string variableName = *variableListStringElementIterator; string typeName = *typeListStringElementIterator; SgName name = variableName.c_str(); SgVariableSymbol* symbol = currentBlock->lookup_var_symbol(name); if ( symbol != NULL ) { // found a variable with name -- make sure that the declarations // represented by *transformationStatementIterator are inserted // after their declaration. #if 0 printf ("Found a valid symbol corresponding to Type = %s Variable = %s (must be defined in the local scope) \n", (*typeListStringElementIterator).c_str(), (*variableListStringElementIterator).c_str()); #endif ROSE_ASSERT (symbol != NULL); SgInitializedName* declarationInitializedName = symbol->get_declaration(); ROSE_ASSERT (declarationInitializedName != NULL); SgDeclarationStatement* declarationStatement = declarationInitializedName->get_declaration(); ROSE_ASSERT (declarationStatement != NULL); #if 0 printf ("declarationStatementString located at line = %d of file = %s \n", rose::getLineNumber(declarationStatement), rose::getFileName(declarationStatement)); string declarationStatementString = declarationStatement->unparseToString(); printf ("declarationStatementString = %s \n",declarationStatementString.c_str()); #endif statementCounter = 1; SgStatementPtrList::iterator i = currentStatementList.begin(); bool declarationFound = false; while ( ( i != currentStatementList.end() ) && ( declarationFound == false ) ) { // searching for the declarationStatement #if 0 printf ("statementCounter = %d previousStatementCounter = %d \n", statementCounter,previousStatementCounter); string currentStatementString = (*i)->unparseToString(); printf ("currentStatementString = %s \n",currentStatementString.c_str()); #endif if ( (*i == declarationStatement) && (statementCounter > previousStatementCounter) ) { // printf ("Found the declarationStatement at position (statementCounter = %d previousStatementCounter = %d) \n",statementCounter,previousStatementCounter); declarationFound = true; } else { // printf ("Not the declaration we are looking for! \n"); i++; statementCounter++; } } // Save a reference to the variable declaration that is furthest in // the source sequence so that we can append the new statement just // after it (so that variables referenced in the new statement will // be defined). if ( (statementCounter > previousStatementCounter) && ( declarationFound == true ) ) { previousStatementCounter = statementCounter; furthestDeclarationInSourceSequence = i; } #if 0 printf ("AFTER LOOP OVER STATEMENTS: previousStatementCounter = %d \n",previousStatementCounter); string lastStatementString = (*furthestDeclarationInSourceSequence)->unparseToString(); printf ("lastStatementString = %s \n",lastStatementString.c_str()); #endif } else { // If the variable is not found then insert the new statement at the front of the list #if 0 printf ("Can NOT find a valid symbol corresponding to Type = %s Variable = %s (so it is not declared in the local scope) \n", (*typeListStringElementIterator).c_str(), (*variableListStringElementIterator).c_str()); #endif // currentStatementList.push_front(*transformationStatementIterator); } #if 0 printf ("BOTTOM OF LOOP OVER VARIABLES: previousStatementCounter = %d \n",previousStatementCounter); #endif } if (statementCounter > previousStatementCounter) previousStatementCounter = statementCounter; #if 0 printf ("BOTTOM OF LOOP OVER TYPES: previousStatementCounter = %d \n",previousStatementCounter); #endif #if 0 printf ("Exiting in insertSourceCode(): transformationStatementIterator loop (type = %s) ... \n",(*typeListStringElementIterator).c_str()); ROSE_ABORT(); #endif } #if 0 printf ("Exiting in loop insertSourceCode (type = %s) ... \n",(*typeListStringElementIterator).c_str()); ROSE_ABORT(); #endif // Now append the new statement AFTER the declaration that we have found // currentStatementList.insert(*targetDeclarationStatementIterator,*transformationStatementIterator); // currentStatementList.insert(lastStatementIterator,*transformationStatementIterator); #if 1 // printf ("BEFORE ADDING NEW STATEMENT: previousStatementCounter = %d \n",previousStatementCounter); if (previousStatementCounter == 0) { printf ("##### Prepend new statement to the top of the local scope \n"); // currentStatementList.push_front(*transformationStatementIterator); currentBlock->prepend_statement (*transformationStatementIterator); } else { // printf ("##### Append the new statement after the last position where a dependent variable is declared in the local scope \n"); // Use new function added to append/prepend at a specified location in the list of statements currentBlock->append_statement (furthestDeclarationInSourceSequence,*transformationStatementIterator); } #else SgStatementPtrList::iterator tempIterator = furthestDeclarationInSourceSequence; tempIterator++; // Handle the case of appending at the end of the list if ( tempIterator == currentStatementList.end() ) { currentBlock->append_statement (*transformationStatementIterator); } else { currentBlock->insert_statement (tempIterator,*transformationStatementIterator); } #endif } else { // This statement has no type information (so it has no dependence upon any non-primative type) // "int x;" would be an example of a statement that would not generate a type (though perhaps it should?) // printf ("This statement has no type information (so it has no dependence upon any non-primative type) \n"); // So this statment can be places at the front of the list of statements in this block // *** Note that we can't use the STL function directly since it does not set the parent information *** // currentStatementList.push_front(*transformationStatementIterator); currentBlock->insert_statement (currentStatementList.begin(),*transformationStatementIterator); } #if 0 string bottomUnparsedDeclarationCodeString = (*transformationStatementIterator)->unparseToString(); ROSE_ASSERT (bottomUnparsedDeclarationCodeString.c_str() != NULL); printf ("bottomUnparsedDeclarationCodeString = %s \n",bottomUnparsedDeclarationCodeString.c_str()); #endif } #if 0 printf ("Exiting in insertSourceCode(): case of locateNewCodeAtTop == true ... \n"); ROSE_ABORT(); #endif } else { // Put the new statements at the end of the list (traverse the new statements from first to last) // But put it before any return statement! So find the last statement! SgStatementPtrList::iterator lastStatement = currentStatementList.begin(); bool foundEndOfList = false; while ( (foundEndOfList == false) && (lastStatement != currentStatementList.end()) ) { SgStatementPtrList::iterator tempStatement = lastStatement; tempStatement++; if (tempStatement == currentStatementList.end()) foundEndOfList = true; else lastStatement++; } ROSE_ASSERT ( *lastStatement != NULL ); // printf ("(*lastStatement)->sage_class_name() = %s \n",(*lastStatement)->sage_class_name()); // printf ("Insert new statements at the bottom of the block \n"); SgStatementPtrList::iterator transformationStatementIterator; for (transformationStatementIterator = newTransformationStatementListPtr->begin(); transformationStatementIterator != newTransformationStatementListPtr->end(); transformationStatementIterator++) { // If there is a RETURN_STMT in the block then insert the new statement just before the // existing RETURN_STMT if ( (*lastStatement)->variant() == RETURN_STMT) { // printf ("Backing away from the end of the list to find the last non-return statement \n"); // lastStatement--; currentBlock->insert_statement(lastStatement,*transformationStatementIterator); } else { currentStatementList.push_back(*transformationStatementIterator); } } } // printf ("$CLASSNAME::insertSourceCode taking (SgProject,char*,char*) not implemented yet! \n"); // ROSE_ABORT(); }
// Move variables declared in a for statement to just outside that statement. void moveForDeclaredVariables(SgNode* root) { vector<SgForStatement*> for_statements; FindForStatementsVisitor(for_statements).traverse(root, preorder); for (unsigned int i = 0; i < for_statements.size(); ++i) { SgForStatement* stmt = for_statements[i]; #ifdef FD_DEBUG cout << "moveForDeclaredVariables: " << stmt->unparseToString() << endl; #endif SgForInitStatement* init = stmt->get_for_init_stmt(); if (!init) continue; SgStatementPtrList& inits = init->get_init_stmt(); vector<SgVariableDeclaration*> decls; for (SgStatementPtrList::iterator j = inits.begin(); j != inits.end(); ++j) { SgStatement* one_init = *j; if (isSgVariableDeclaration(one_init)) { decls.push_back(isSgVariableDeclaration(one_init)); } } if (decls.empty()) continue; SgStatement* parent = isSgStatement(stmt->get_parent()); assert (parent); SgBasicBlock* bb = new SgBasicBlock(SgNULL_FILE); stmt->set_parent(bb); bb->set_parent(parent); SgStatementPtrList ls; for (unsigned int j = 0; j < decls.size(); ++j) { for (SgInitializedNamePtrList::iterator k = decls[j]->get_variables().begin(); k != decls[j]->get_variables().end(); ++k) { #ifdef FD_DEBUG cout << "Working on variable " << (*k)->get_name().getString() << endl; #endif SgVariableSymbol* sym = new SgVariableSymbol(*k); bb->insert_symbol((*k)->get_name(), sym); (*k)->set_scope(bb); SgAssignInitializer* kinit = 0; if (isSgAssignInitializer((*k)->get_initializer())) { kinit = isSgAssignInitializer((*k)->get_initializer()); (*k)->set_initializer(0); } if (kinit) { SgVarRefExp* vr = new SgVarRefExp(SgNULL_FILE, sym); vr->set_endOfConstruct(SgNULL_FILE); vr->set_lvalue(true); SgAssignOp* assignment = new SgAssignOp(SgNULL_FILE,vr,kinit->get_operand()); vr->set_parent(assignment); kinit->get_operand()->set_parent(assignment); SgExprStatement* expr = new SgExprStatement(SgNULL_FILE, assignment); assignment->set_parent(expr); ls.push_back(expr); expr->set_parent(init); } } #if 0 SgStatementPtrList::iterator fiiter = std::find(inits.begin(), inits.end(), decls[j]); assert (fiiter != inits.end()); size_t idx = fiiter - inits.begin(); inits.erase(inits.begin() + idx); inits.insert(inits.begin() + idx, ls.begin(), ls.end()); #endif bb->get_statements().push_back(decls[j]); decls[j]->set_parent(bb); } inits = ls; bb->get_statements().push_back(stmt); // printf ("In moveForDeclaredVariables(): parent = %p = %s bb = %p stmt = %p = %s \n",parent,parent->class_name().c_str(),bb,stmt,stmt->class_name().c_str()); ROSE_ASSERT(stmt->get_parent() == bb); parent->replace_statement(stmt, bb); } }
virtual void visit(SgNode* node) { if (isSgBasicBlock(node)) { SgBasicBlock* c = isSgBasicBlock(node); SgStatementPtrList newStatements; for (SgStatementPtrList::const_iterator i = c->get_statements().begin(); i != c->get_statements().end(); ++i) { if (isSgBasicBlock(*i)) { SgBasicBlock* c2 = isSgBasicBlock(*i); const SgStatementPtrList& c2Stmts = c2->get_statements(); // We need to prevent a declaration from immediately following a label, as that is illegal if (!newStatements.empty() && isSgLabelStatement(newStatements.back()) && !c2Stmts.empty() && isSgVariableDeclaration(c2Stmts.front())) { newStatements.push_back(SageBuilder::buildExprStatement(SageBuilder::buildNullExpression())); } newStatements.insert(newStatements.end(), isSgBasicBlock(*i)->get_statements().begin(), isSgBasicBlock(*i)->get_statements().end()); } else { if (!newStatements.empty() && isSgLabelStatement(newStatements.back()) && isSgVariableDeclaration(*i)) { newStatements.push_back(SageBuilder::buildExprStatement(SageBuilder::buildNullExpression())); } newStatements.push_back(*i); } } if (!newStatements.empty() && isSgLabelStatement(newStatements.back())) { // Prevent block from ending with a label newStatements.push_back(SageBuilder::buildExprStatement(SageBuilder::buildNullExpression())); } for (SgStatementPtrList::const_iterator i = newStatements.begin(); i != newStatements.end(); ++i) { (*i)->set_parent(c); } c->get_statements() = newStatements; c->get_symbol_table()->get_table()->clear(); SageInterface::rebuildSymbolTable(c); } }