Exemplo n.º 1
0
    virtual void visit(SgNode* n) {
        if (isSgVarRefExp(n)) {
            SgVarRefExp* copy_vr = isSgVarRefExp(n);
            assert (copy_vr->get_symbol());
            SgInitializedName* copy = copy_vr->get_symbol()->get_declaration();
            assert (copy);
            if (!SageInterface::isReferenceType(copy->get_type()))
                return; // Fail if non-reference

            SgInitializer* copyinit = copy->get_initializer();
            SgNode* copyscope_ =
                copy->get_parent()->get_parent();
            while (!isSgScopeStatement(copyscope_))
                copyscope_ = copyscope_->get_parent();
            // cout << "copyscope is a " << copyscope_->sage_class_name() << endl;
            // SgScopeStatement* copyscope = isSgScopeStatement(copyscope_);
            if (isSgAssignInitializer(copyinit)) {
                SgAssignInitializer* init = isSgAssignInitializer(copyinit);
                SgExpression* orig_expr = init->get_operand();
                // cout << "orig is " << orig_expr->unparseToString() << ", copy is " << copy->get_name().str() << endl;
                bool shouldReplace = false;
                if (isSgVarRefExp(orig_expr)) {
                    SgVarRefExp* orig_vr = isSgVarRefExp(orig_expr);
                    // cout << "Found potential copy from " << orig_vr->get_symbol()->get_name().str() << " to " << copy_vr->get_symbol()->get_name().str() << endl;
                    SgInitializedName* orig = orig_vr->get_symbol()->get_declaration();
                    assert (orig);
                    SgNode* origscope = orig->get_parent()->get_parent();
                    assert (origscope);
                    shouldReplace = true;
                }
                if (shouldReplace) {
                    assert (orig_expr);
                    SgExpression* orig_copy =
                        isSgExpression(orig_expr /*->copy(SgTreeCopy()) */);
                    assert (orig_copy);
                    orig_copy->set_parent(copy_vr->get_parent());
                    isSgExpression(copy_vr->get_parent())->
                    replace_expression(copy_vr, orig_copy);
                }
            }
        }
    }
Exemplo n.º 2
0
Arquivo: RoseToTerm.C Projeto: 8l/rose
/**
 * class: SgVarRefExp
 * term: var_ref_exp_annotation(tpe,name,static,scope)
 * arg tpe: type
 * arg name: name
 * arg static: wether the declaration was static
 * arg scope: scope name (either from a namespace, a class or "null")
 */
PrologCompTerm* 
RoseToTerm::getVarRefExpSpecific(SgVarRefExp* vr) {
  SgInitializedName* n = vr->get_symbol()->get_declaration();
  /* type: in general, this can be taken "as is" from the ROSE AST. However,
   * ROSE (up to 0.9.4a-8xxx at least) gets a detail wrong: a declaration
   * like "int arr[]" as a function parameter declares a *pointer*, not an
   * array. Thus we check whether the variable might be of this sort, and if
   * yes, we must make a pointer type for it. */
  PrologTerm* typeSpecific = NULL;
  SgInitializedName* vardecl = vr->get_symbol()->get_declaration();
  SgType* t = vr->get_type()->stripType(SgType::STRIP_MODIFIER_TYPE
                                      | SgType::STRIP_REFERENCE_TYPE
                                      | SgType::STRIP_TYPEDEF_TYPE);
  if (isSgFunctionParameterList(vardecl->get_parent()) && isSgArrayType(t)) {
    SgType* baseType = isSgArrayType(t)->get_base_type();
    PrologTerm* baseTypeSpecific = getTypeSpecific(baseType);
    typeSpecific = new PrologCompTerm("pointer_type", /*1,*/ baseTypeSpecific);
  } else {
    typeSpecific = getTypeSpecific(n->get_typeptr());
  }
  /* static? (relevant for unparsing if scope is a class)*/
  PrologTerm *isStatic;
  SgDeclarationStatement* vdec = n->get_declaration();
  if (vdec != NULL) {
    isStatic = 
      getEnum(vdec->get_declarationModifier().get_storageModifier().isStatic(),
	      re.static_flags);
  } else {
    isStatic = getEnum(0, re.static_flags);
  }
  PrologTerm* scope;
  if (vdec != NULL) {
    /* named scope or irrelevant?*/
    if (SgNamespaceDefinitionStatement* scn = 
	isSgNamespaceDefinitionStatement(vdec->get_parent())) {
      scope = getNamespaceScopeName(scn);
    } else if (SgClassDefinition* scn = 
	       isSgClassDefinition(vdec->get_parent())) {
      scope = getClassScopeName(scn);
    } else {
      scope = new PrologAtom("null");
    }
  } else {
    scope = new PrologAtom("null");
  }

  return new PrologCompTerm
    ("var_ref_exp_annotation", //5,
     typeSpecific,
     /* name*/ new PrologAtom(n->get_name().getString()),
     isStatic,
     scope,
     PPI(vr));
}
Exemplo n.º 3
0
Arquivo: DCL.C Projeto: 8l/rose
/**
 * Use visually distinct identifiers 
 *
 * \note also checks DCL31-C
 */
bool DCL02_C( const SgNode *node ) {
	static std::map<const SgScopeStatement *, std::set<std::string> > scopeMap;
	static std::map<std::string, const SgInitializedName *> strVarMap;

	const SgScopeStatement *scope = isSgScopeStatement(node);
	if (!scope)
		return false;

	bool violation = false;

	if (isSgGlobal(scope)) {
		std::set<std::string> externNames;

		/** populate scopeMap */
		FOREACH_SUBNODE(scope, nodes, i, V_SgInitializedName) {
			SgInitializedName *var = isSgInitializedName(*i);
			assert(var);
			if (isCompilerGeneratedNode(var)
			|| !isSgDeclarationStatement(var->get_parent())
			|| findParentOfType(var, SgCtorInitializerList)
			|| findParentOfType(var, SgClassDeclaration) // Might be too strong
			|| var->get_name().getString().empty()
			|| (var->get_name().getString().substr(0,2) == "__"))
				continue;

			/** Ignore function prototypes */
			const SgFunctionDeclaration * fnDecl = findParentOfType(var, SgFunctionDeclaration);
			if (fnDecl && !fnDecl->get_definition())
				continue;

			if (isExternVar(var)) {
				if (externNames.find(var->get_name().getString()) != externNames.end())
					continue;

				externNames.insert(var->get_name().getString());
			}

			const SgScopeStatement *varScope = var->get_scope();
			std::string str (normalize_string(var->get_name().str(), isExternVar(var)));
			if (scopeMap[varScope].find(str) != scopeMap[varScope].end()) {
				DCL02_report_error(var);
				violation = true;
			} else {
				scopeMap[varScope].insert(str);
				strVarMap[str] = var;
			}
		}
		return false;
	}
Exemplo n.º 4
0
void
FixupEnumValues::visit(SgNode* node)
   {
#if 0
     printf ("##### FixupEnumValues::visit(node = %p = %s) \n",node,node->sage_class_name());
#endif

     SgEnumVal* enumVal = isSgEnumVal(node);
     ROSE_ASSERT(enumVal != NULL);

     if (enumVal->get_declaration() == NULL)
        {
          ROSE_ASSERT(enumVal->get_startOfConstruct() != NULL);
          ROSE_ASSERT(enumVal->get_endOfConstruct() != NULL);

       // printf ("Found an enum value with a NULL declaration, fixup the declaration! \n");
       // enumVal->get_startOfConstruct()->display("Found an enum value with a NULL declaration");

          SgClassDefinition* enclosingClassDefinition = TransformationSupport::getClassDefinition(enumVal);
          ROSE_ASSERT(enclosingClassDefinition != NULL);

       // Now search for the enumVal name in the symbol table
          SgEnumFieldSymbol* enumFieldSymbol = enclosingClassDefinition->lookup_enum_field_symbol(enumVal->get_name());
          ROSE_ASSERT(enumFieldSymbol != NULL);
          if (enumFieldSymbol != NULL)
             {
            // We have now found the enum symbol in the scope of the class where the enum value was used.  
            // It could have been elsewhere and we don't search there, it could be in a namespace that was 
            // included using a using directive, so this could be very complex if it is not in the enclosing 
            // class.  To handle the case of where we can't find it, we ALLOW the declaration in the enumVal 
            // to be NULL, but we try to set it where we can easily figure it out.

                SgInitializedName* enumFieldName = enumFieldSymbol->get_declaration();
                SgNode* parentNode = enumFieldName->get_parent();
                ROSE_ASSERT(parentNode != NULL);
                SgEnumDeclaration* enumDeclaration = isSgEnumDeclaration(parentNode);
                ROSE_ASSERT(enumDeclaration != NULL);

             // Set the declaration to the enum declaration found!
             // printf ("Fixup the NULL declaration in enumVal = %p = %s with valid enum declaration = %p = %s \n",enumVal,enumVal->get_name().str(),enumDeclaration,enumDeclaration->get_name().str());
                enumVal->set_declaration(enumDeclaration);
             }


        }
   }
Exemplo n.º 5
0
void
FixupSelfReferentialMacrosInAST::visit ( SgNode* node )
   {
  // DQ (3/11/2006): Set NULL pointers where we would like to have none.
  // printf ("In FixupSelfReferentialMacrosInAST::visit(): node = %s \n",node->class_name().c_str());

     ROSE_ASSERT(node != NULL);
     switch (node->variantT())
        {
          case V_SgInitializedName:
             {
               SgInitializedName* initializedName = isSgInitializedName(node);
               ROSE_ASSERT(initializedName != NULL);
               SgType* type = initializedName->get_type()->stripType();
               SgClassType* classType = isSgClassType(type);
               if (classType != NULL)
                  {
                    SgClassDeclaration* targetClassDeclaration = isSgClassDeclaration(classType->get_declaration());
                    SgName className = targetClassDeclaration->get_name();

                 // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a class declaration name = %s \n",className.str());

                 // For sudo_exec_pty.c also look for siginfo
                    if (className == "sigaction" || className == "siginfo")
                       {
                      // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a sigaction type \n");

                      // Note we could also check that the declaration came from a known header file.
                         SgStatement* associatedStatement = isSgStatement(initializedName->get_parent());
                         if (associatedStatement != NULL)
                            {
                           // Add a macro to undefine the "#define sa_handler __sigaction_handler.sa_handler" macro.
                           // printf ("In FixupSelfReferentialMacrosInAST::visit(): Add a macro to undefine the macro #define sa_handler __sigaction_handler.sa_handler \n");

                           // PreprocessingInfo* macro = new PreprocessingInfo(DirectiveType, const std::string & inputString,const std::string & filenameString, int line_no , int col_no,int nol, RelativePositionType relPos );

                              PreprocessingInfo::DirectiveType directiveType = PreprocessingInfo::CpreprocessorUndefDeclaration;

                           // We are puting out all macros anytime we see either type.  This might be too much...

                           // From the sigaction.h file (included by signal.h):
                              addMacro(associatedStatement,"#undef sa_handler\n",directiveType);
                              addMacro(associatedStatement,"#undef sa_sigaction\n",directiveType);

                           // From the siginfo.h file (included by signal.h):
                              addMacro(associatedStatement,"#undef si_pid\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_uid\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_timerid\n",directiveType);
                              addMacro(associatedStatement,"#undef si_overrun\n",directiveType);
                              addMacro(associatedStatement,"#undef si_status\n", directiveType);
                              addMacro(associatedStatement,"#undef si_utime\n",  directiveType);
                              addMacro(associatedStatement,"#undef si_stime\n",  directiveType);
                              addMacro(associatedStatement,"#undef si_value\n",  directiveType);
                              addMacro(associatedStatement,"#undef si_int\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_ptr\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_addr\n",   directiveType);
                              addMacro(associatedStatement,"#undef si_band\n",   directiveType);
                              addMacro(associatedStatement,"#undef si_fd\n",     directiveType);
                            }
                       }
                  }
             }

          default:
             {
            // printf ("Not handled in FixupSelfReferentialMacrosInAST::visit(%s) \n",node->class_name().c_str());
             }
        }

   }
Exemplo n.º 6
0
void SystemDependenceGraph::build()
{
    boost::unordered_map<CFGVertex, Vertex> cfgVerticesToSdgVertices;
    boost::unordered_map<SgNode*, Vertex>   astNodesToSdgVertices;

    //map<SgFunctionCallExp*, vector<SDGNode*> > funcCallToArgs;

    vector<CallSiteInfo> functionCalls;


    map<SgNode*, vector<Vertex> > actualInParameters;
    map<SgNode*, vector<Vertex> > actualOutParameters;

    map<SgNode*, Vertex> formalInParameters;
    map<SgNode*, Vertex> formalOutParameters;

    vector<SgFunctionDefinition*> funcDefs = 
        SageInterface::querySubTree<SgFunctionDefinition>(project_, V_SgFunctionDefinition);
    foreach (SgFunctionDefinition* funcDef, funcDefs)
    {
        SgFunctionDeclaration* funcDecl = funcDef->get_declaration();

        CFG* cfg = new CFG(funcDef, cfgNodefilter_);
        functionsToCFGs_[funcDecl] = cfg;

        // For each function, build an entry node for it.
        SDGNode* entry = new SDGNode(SDGNode::Entry);
        entry->astNode = funcDef;
        //entry->funcDef = funcDef;
        Vertex entryVertex = addVertex(entry);
        functionsToEntries_[funcDecl] = entryVertex;

        // Add all out formal parameters to SDG.
        const SgInitializedNamePtrList& formalArgs = funcDecl->get_args();
        foreach (SgInitializedName* initName, formalArgs)
        {
            // If the parameter is passed by reference, create a formal-out node.
            if (isParaPassedByRef(initName->get_type()))
            {
                SDGNode* formalOutNode = new SDGNode(SDGNode::FormalOut);
                formalOutNode->astNode = initName;
                Vertex formalOutVertex = addVertex(formalOutNode);
                formalOutParameters[initName] = formalOutVertex;

                // Add a CD edge from call node to this formal-out node.
                addTrueCDEdge(entryVertex, formalOutVertex);
            }
        }

        // A vertex representing the returned value.
        Vertex returnVertex;

        // If the function returns something, build a formal-out node.
        if (!isSgTypeVoid(funcDecl->get_type()->get_return_type()))
        {
            SDGNode* formalOutNode = new SDGNode(SDGNode::FormalOut);
            // Assign the function declaration to the AST node of this vertex to make
            // it possible to classify this node into the subgraph of this function.
            formalOutNode->astNode = funcDecl;
            returnVertex = addVertex(formalOutNode);
            formalOutParameters[funcDecl] = returnVertex;

            // Add a CD edge from call node to this formal-out node.
            addTrueCDEdge(entryVertex, returnVertex);
        }

        // Add all CFG vertices to SDG.
        foreach (CFGVertex cfgVertex, boost::vertices(*cfg))
        {
            if (cfgVertex == cfg->getEntry() || cfgVertex == cfg->getExit())
                continue;

            SgNode* astNode = (*cfg)[cfgVertex]->getNode();

            // If this node is an initialized name and it is a parameter, make it 
            // as a formal in node.
            SgInitializedName* initName = isSgInitializedName(astNode);
            if (initName && isSgFunctionParameterList(initName->get_parent()))
            {
                SDGNode* formalInNode = new SDGNode(SDGNode::FormalIn);
                formalInNode->astNode = initName;
                Vertex formalInVertex = addVertex(formalInNode);
                formalInParameters[initName] = formalInVertex;

                cfgVerticesToSdgVertices[cfgVertex] = formalInVertex;
                astNodesToSdgVertices[astNode] = formalInVertex;

                // Add a CD edge from call node to this formal-in node.
                addTrueCDEdge(entryVertex, formalInVertex);
                continue;
            }

            // Add a new node to SDG.
            SDGNode* newSdgNode = new SDGNode(SDGNode::ASTNode);
            //newSdgNode->cfgNode = (*cfg)[cfgVertex];
            newSdgNode->astNode = astNode;
            Vertex sdgVertex = addVertex(newSdgNode);

            cfgVerticesToSdgVertices[cfgVertex] = sdgVertex;
            astNodesToSdgVertices[astNode] = sdgVertex;


            // Connect a vertex containing the return statement to the formal-out return vertex.
            if (isSgReturnStmt(astNode)
                    || isSgReturnStmt(astNode->get_parent()))
            {
                SDGEdge* newEdge = new SDGEdge(SDGEdge::DataDependence);
                addEdge(sdgVertex, returnVertex, newEdge);                
            }

            // If this CFG node contains a function call expression, extract its all parameters
            // and make them as actual-in nodes.

            if (SgFunctionCallExp* funcCallExpr = isSgFunctionCallExp(astNode))
            {
                CallSiteInfo callInfo;
                callInfo.funcCall = funcCallExpr;
                callInfo.vertex = sdgVertex;

                // Change the node type.
                newSdgNode->type = SDGNode::FunctionCall;
                vector<SDGNode*> argsNodes;

                // Get the associated function declaration.
                SgFunctionDeclaration* funcDecl = funcCallExpr->getAssociatedFunctionDeclaration();
                
                if (funcDecl == NULL) 
                    continue;
                    
                ROSE_ASSERT(funcDecl);
                const SgInitializedNamePtrList& formalArgs = funcDecl->get_args();

                SgExprListExp* args = funcCallExpr->get_args();
                const SgExpressionPtrList& actualArgs = args->get_expressions();
                
                if (formalArgs.size() != actualArgs.size())
                {
                    cout << "The following function has variadic arguments:\n";
                    cout << funcDecl->get_file_info()->get_filename() << endl;
                    cout << funcDecl->get_name() << formalArgs.size() << " " << actualArgs.size() << endl;
                    continue;
                }

                for (int i = 0, s = actualArgs.size(); i < s; ++i)
                {
                    // Make sure that this parameter node is added to SDG then we
                    // change its node type from normal AST node to a ActualIn arg.
                    ROSE_ASSERT(astNodesToSdgVertices.count(actualArgs[i]));

                    Vertex paraInVertex = astNodesToSdgVertices.at(actualArgs[i]);
                    SDGNode* paraInNode = (*this)[paraInVertex]; 
                    paraInNode->type = SDGNode::ActualIn;

                    actualInParameters[formalArgs[i]].push_back(paraInVertex);
                    callInfo.inPara.push_back(paraInVertex);

                    // Add a CD edge from call node to this actual-in node.
                    addTrueCDEdge(sdgVertex, paraInVertex);

                    // If the parameter is passed by reference, create a parameter-out node.
                    if (isParaPassedByRef(formalArgs[i]->get_type()))
                    {
                        SDGNode* paraOutNode = new SDGNode(SDGNode::ActualOut);
                        paraOutNode->astNode = actualArgs[i];
                        //argsNodes.push_back(paraInNode);

                        // Add an actual-out parameter node.
                        Vertex paraOutVertex = addVertex(paraOutNode);
                        actualOutParameters[formalArgs[i]].push_back(paraOutVertex);
                        callInfo.outPara.push_back(paraOutVertex);

                        // Add a CD edge from call node to this actual-out node.
                        addTrueCDEdge(sdgVertex, paraOutVertex);
                    }
                }

                if (!isSgTypeVoid(funcDecl->get_type()->get_return_type())) 
                {
                    // If this function returns a value, create a actual-out vertex.
                    SDGNode* paraOutNode = new SDGNode(SDGNode::ActualOut);
                    paraOutNode->astNode = funcCallExpr;

                    // Add an actual-out parameter node.
                    Vertex paraOutVertex = addVertex(paraOutNode);
                    actualOutParameters[funcDecl].push_back(paraOutVertex);
                    callInfo.outPara.push_back(paraOutVertex);
                    callInfo.isVoid = false;
                    callInfo.returned = paraOutVertex;

                    // Add a CD edge from call node to this actual-out node.
                    addTrueCDEdge(sdgVertex, paraOutVertex);
                }

                functionCalls.push_back(callInfo);
                //funcCallToArgs[funcCallExpr] = argsNodes;
            }
        }

        // Add control dependence edges.
        addControlDependenceEdges(cfgVerticesToSdgVertices, *cfg, entryVertex);
    }
Exemplo n.º 7
0
InheritedAttribute
visitorTraversal::evaluateInheritedAttribute(SgNode* n, InheritedAttribute inheritedAttribute)
   {
    Sg_File_Info* s = n->get_startOfConstruct();
    Sg_File_Info* e = n->get_endOfConstruct();
    Sg_File_Info* f = n->get_file_info();
    for(int x=0; x < inheritedAttribute.depth; ++x) {
        printf(" ");
    }
    if(s != NULL && e != NULL && !isSgLabelStatement(n)) { 
        printf ("%s (%d, %d, %d)->(%d, %d): %s",n->sage_class_name(),s->get_file_id()+1,s->get_raw_line(),s->get_raw_col(),e->get_raw_line(),e->get_raw_col(),  verbose ? n->unparseToString().c_str() : "" );
        if(isSgAsmDwarfConstruct(n)) {
            printf(" [DWARF construct name: %s]", isSgAsmDwarfConstruct(n)->get_name().c_str());
        }
        SgExprStatement * exprStmt = isSgExprStatement(n);
        if(exprStmt != NULL) {
            printf(" [expr type: %s]", exprStmt->get_expression()->sage_class_name());           
            SgFunctionCallExp * fcall = isSgFunctionCallExp(exprStmt->get_expression());
            if(fcall != NULL) {
               SgExpression * funcExpr = fcall->get_function();
               if(funcExpr != NULL) {
                    printf(" [function expr: %s]", funcExpr->class_name().c_str());
               }
               SgFunctionDeclaration * fdecl = fcall->getAssociatedFunctionDeclaration();
               if(fdecl != NULL) {
                    printf(" [called function: %s]", fdecl->get_name().str());
               }
            }
        }
        if(isSgFunctionDeclaration(n)) {
            printf(" [declares function: %s]", isSgFunctionDeclaration(n)->get_name().str());
        }
        SgStatement * sgStmt = isSgStatement(n);
        if(sgStmt != NULL) {
            printf(" [scope: %s, %p]", sgStmt->get_scope()->sage_class_name(), sgStmt->get_scope());
        }
        //SgLabelStatement * lblStmt = isSgLabelStatement(n);
        //if(lblStmt != NULL) {
        //    SgStatement * lblStmt2 = lblStmt->get_statement();
        //}
    } else if (f != NULL) {
		SgInitializedName * iname = isSgInitializedName(n);
		if(iname != NULL) {
            SgType* inameType = iname->get_type();
			printf("%s (%d, %d, %d): %s [type: %s", n->sage_class_name(),f->get_file_id()+1,f->get_raw_line(),f->get_raw_col(),n->unparseToString().c_str(),inameType->class_name().c_str());
			SgDeclarationStatement * ds = isSgDeclarationStatement(iname->get_parent());
			if(ds != NULL) {
				if(ds->get_declarationModifier().get_storageModifier().isStatic()) {
					printf(" static");
				}
			}
			
			SgArrayType * art = isSgArrayType(iname->get_type());
			if(art != NULL) {
				printf(" %d", art->get_rank());
			}
			
			printf("]");
            if(isSgAsmDwarfConstruct(n)) {
                printf(" [DWARF construct name: %s]", isSgAsmDwarfConstruct(n)->get_name().c_str());
            }
            } else {
        	printf("%s (%d, %d, %d): %s", n->sage_class_name(),f->get_file_id()+1,f->get_raw_line(),f->get_raw_col(), verbose ? n->unparseToString().c_str() : "");
		}
    } else {
        printf("%s : %s", n->sage_class_name(), verbose ? n->unparseToString().c_str() : "");
        if(isSgAsmDwarfConstruct(n)) {
            printf(" [DWARF construct name: %s]", isSgAsmDwarfConstruct(n)->get_name().c_str());
        }
    }
    printf(" succ# %lu", n->get_numberOfTraversalSuccessors());
	printf("\n");
     return InheritedAttribute(inheritedAttribute.depth+1);
   }
Exemplo n.º 8
0
int main( int argc, char * argv[] )
{
// Option to linearize the array.
  Rose_STL_Container<std::string> localCopy_argv = CommandlineProcessing::generateArgListFromArgcArgv(argc, argv);
  int newArgc;
  char** newArgv = NULL;
  vector<string> argList = localCopy_argv;
  if (CommandlineProcessing::isOption(argList,"-f2c:","linearize",true) == true)
  {
    isLinearlizeArray = true;
  }
  CommandlineProcessing::generateArgcArgvFromList(argList,newArgc, newArgv);
// Build the AST used by ROSE
  SgProject* project = frontend(newArgc,newArgv);
  AstTests::runAllTests(project);   

  if (SgProject::get_verbose() > 2)
    generateAstGraph(project,8000,"_orig");
  
  // Traversal with Memory Pool to search for variableDeclaration
  variableDeclTraversal translateVariableDeclaration;
  traverseMemoryPoolVisitorPattern(translateVariableDeclaration);
  for(vector<SgVariableDeclaration*>::iterator dec=variableDeclList.begin(); dec!=variableDeclList.end(); ++dec)
  {
    /*
       For the Fortran AST, a single variableDeclaration can be shared by multiple variables.
       This violated the normalization rules for C unparser.  Therefore, we have to transform it.
    */
    SgVariableDeclaration* variableDeclaration = isSgVariableDeclaration(*dec);
    ROSE_ASSERT(variableDeclaration);
    if((variableDeclaration->get_variables()).size() != 1)
    {
      updateVariableDeclarationList(variableDeclaration);
      statementList.push_back(variableDeclaration);
      removeList.push_back(variableDeclaration);
    }
  }

  // reset the vector that collects all variable declaration. We need to walk through memory pool again to find types
  
  variableDeclList.clear();
  traverseMemoryPoolVisitorPattern(translateVariableDeclaration);
  for(vector<SgVariableDeclaration*>::iterator dec=variableDeclList.begin(); dec!=variableDeclList.end(); ++dec)
  {
    SgVariableDeclaration* variableDeclaration = isSgVariableDeclaration(*dec);
    ROSE_ASSERT(variableDeclaration);
    SgInitializedNamePtrList initializedNameList = variableDeclaration->get_variables();
    for(SgInitializedNamePtrList::iterator i=initializedNameList.begin(); i!=initializedNameList.end();++i)
    {
      SgInitializedName* initiallizedName = isSgInitializedName(*i);
      SgType* baseType = initiallizedName->get_type();
      if(baseType->variantT() == V_SgArrayType)
      {
        SgArrayType* arrayBase = isSgArrayType(baseType);
        // At this moment, we are still working on the Fortran-stype AST.  Therefore, there is no nested types for multi-dim array.
        if(arrayBase->findBaseType()->variantT() == V_SgTypeString)
        {
          arrayBase->reset_base_type(translateType(arrayBase->findBaseType()));
          arrayBase->set_rank(arrayBase->get_rank()+1);
        }
      }
      else
      {
        initiallizedName->set_type(translateType(baseType));
      }
    }
  }

  // replace the AttributeSpecificationStatement 
  Rose_STL_Container<SgNode*> AttributeSpecificationStatement = NodeQuery::querySubTree (project,V_SgAttributeSpecificationStatement);
  for (Rose_STL_Container<SgNode*>::iterator i = AttributeSpecificationStatement.begin(); i != AttributeSpecificationStatement.end(); i++)
  {
    SgAttributeSpecificationStatement* attributeSpecificationStatement = isSgAttributeSpecificationStatement(*i);
    ROSE_ASSERT(attributeSpecificationStatement);
    translateAttributeSpecificationStatement(attributeSpecificationStatement);
    statementList.push_back(attributeSpecificationStatement);
    removeList.push_back(attributeSpecificationStatement);
  }

  // replace the parameter reference
  parameterTraversal translateParameterRef;
  traverseMemoryPoolVisitorPattern(translateParameterRef);
  for(vector<SgVarRefExp*>::iterator i=parameterRefList.begin(); i!=parameterRefList.end(); ++i)
  {
    SgVarRefExp* parameterRef = isSgVarRefExp(*i);
    if(parameterSymbolList.find(parameterRef->get_symbol()) != parameterSymbolList.end())
    {
      SgExpression* newExpr = isSgExpression(deepCopy(parameterSymbolList.find(parameterRef->get_symbol())->second));
      ROSE_ASSERT(newExpr);
      newExpr->set_parent(parameterRef->get_parent());
      replaceExpression(parameterRef,
                        newExpr,
                        false);
    }
  }

  /*
     Parameters will be replaced by #define, all the declarations should be removed
  */
  for(map<SgVariableSymbol*,SgExpression*>::iterator i=parameterSymbolList.begin();i!=parameterSymbolList.end();++i)
  {
    SgVariableSymbol* symbol = i->first;
    SgInitializedName* initializedName = symbol->get_declaration();
    SgVariableDeclaration* decl = isSgVariableDeclaration(initializedName->get_parent());
    statementList.push_back(decl);
    removeList.push_back(decl);
  }


  // Traversal with Memory Pool to search for arrayType
  arrayTypeTraversal translateArrayType;
  traverseMemoryPoolVisitorPattern(translateArrayType);
  for(vector<SgArrayType*>::iterator i=arrayTypeList.begin(); i!=arrayTypeList.end(); ++i)
  {
    if(isLinearlizeArray)
    {
      linearizeArrayDeclaration(*i);
    }
    else
    {
      translateArrayDeclaration(*i);
    }
  }

  // Traversal with Memory Pool to search for pntrArrRefExp
  pntrArrRefTraversal translatePntrArrRefExp;
  traverseMemoryPoolVisitorPattern(translatePntrArrRefExp);
  for(vector<SgPntrArrRefExp*>::iterator i=pntrArrRefList.begin(); i!=pntrArrRefList.end(); ++i)
  {
    if(isLinearlizeArray)
    {
      linearizeArraySubscript(*i);
    }
    else
    {
      translateArraySubscript(*i);
    }
  }


  Rose_STL_Container<SgNode*> functionList = NodeQuery::querySubTree (project,V_SgFunctionDeclaration);
  for (Rose_STL_Container<SgNode*>::iterator i = functionList.begin(); i != functionList.end(); i++)
  {
    if((isSgProcedureHeaderStatement(*i) != NULL) ||
       (isSgProgramHeaderStatement(*i) != NULL)){
      SgFunctionDeclaration* functionBody = isSgFunctionDeclaration(*i);
      bool hasReturnVal = false;
      if(isSgProcedureHeaderStatement(functionBody))
      {
        hasReturnVal = isSgProcedureHeaderStatement(functionBody)->isFunction();
      }
      fixFortranSymbolTable(functionBody->get_definition(),hasReturnVal);
    }
  } 

  // Traversal with Memory Pool to search for equivalenceStatement
  equivalencelTraversal translateEquivalenceStmt;
  traverseMemoryPoolVisitorPattern(translateEquivalenceStmt);
  for(vector<SgEquivalenceStatement*>::iterator i=equivalenceList.begin(); i!=equivalenceList.end(); ++i)
  {
    SgEquivalenceStatement* equivalenceStatement = isSgEquivalenceStatement(*i);
    ROSE_ASSERT(equivalenceStatement);
    translateEquivalenceStatement(equivalenceStatement);
    statementList.push_back(equivalenceStatement);
    removeList.push_back(equivalenceStatement);
  }



  // Simple traversal, bottom-up, to translate the rest
  f2cTraversal f2c;
  f2c.traverseInputFiles(project,postorder);

  // removing all the unsed statement from AST
  for(vector<SgStatement*>::iterator i=statementList.begin(); i!=statementList.end(); ++i)
  {
    removeStatement(*i);
    (*i)->set_parent(NULL);
  }
      
  // deepDelete the removed nodes 
  for(vector<SgNode*>::iterator i=removeList.begin(); i!=removeList.end(); ++i)
  {
    deepDelete(*i);
  }
      
/*
  1. There should be no Fortran-specific AST nodes in the whole
     AST graph after the translation. 
  
  TODO: make sure translator generating clean AST 
*/
    //generateDOT(*project);
  if (SgProject::get_verbose() > 2)
    generateAstGraph(project,8000);
  return backend(project);
}
void
FixupSelfReferentialMacrosInAST::visit ( SgNode* node )
   {
  // DQ (3/11/2006): Set NULL pointers where we would like to have none.
  // printf ("In FixupSelfReferentialMacrosInAST::visit(): node = %s \n",node->class_name().c_str());

     ROSE_ASSERT(node != NULL);
     switch (node->variantT())
        {
          case V_SgInitializedName:
             {
               SgInitializedName* initializedName = isSgInitializedName(node);
               ROSE_ASSERT(initializedName != NULL);
               SgType* type = initializedName->get_type()->stripType();
               SgClassType* classType = isSgClassType(type);
               if (classType != NULL)
                  {
                    SgClassDeclaration* targetClassDeclaration = isSgClassDeclaration(classType->get_declaration());
                    SgName className = targetClassDeclaration->get_name();

                 // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a class declaration name = %s \n",className.str());

                    if (className == "sigaction")
                       {
                      // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a sigaction type \n");

                      // Note we could also check that the declaration came from a known header file.
                         SgStatement* associatedStatement = isSgStatement(initializedName->get_parent());
                         if (associatedStatement != NULL)
                            {
                           // Add a macro to undefine the "#define sa_handler __sigaction_handler.sa_handler" macro.
                           // printf ("In FixupSelfReferentialMacrosInAST::visit(): Add a macro to undefine the macro #define sa_handler __sigaction_handler.sa_handler \n");

                           // PreprocessingInfo* macro = new PreprocessingInfo(DirectiveType, const std::string & inputString,const std::string & filenameString, int line_no , int col_no,int nol, RelativePositionType relPos );

                              PreprocessingInfo::DirectiveType directiveType = PreprocessingInfo::CpreprocessorUndefDeclaration;
                              std::string macroString = "#undef sa_handler\n";
                              std::string filenameString = "macro_call_fixupSelfReferentialMacrosInAST";
                              int line_no = 1;
                              int col_no  = 1;
                              int nol     = 1;
                              PreprocessingInfo::RelativePositionType relPos = PreprocessingInfo::before;

                              PreprocessingInfo* macro = new PreprocessingInfo(directiveType,macroString,filenameString,line_no,col_no,nol,relPos);

                           // printf ("Attaching CPP directive %s to IR node %p as attributes. \n",PreprocessingInfo::directiveTypeName(macro->getTypeOfDirective()).c_str(),associatedStatement);
                              associatedStatement->addToAttachedPreprocessingInfo(macro);
#if 0
                              printf ("Exiting as a test! \n");
                              ROSE_ASSERT(false);
#endif
                            }
                       }
                  }
             }

          default:
             {
            // printf ("Not handled in FixupSelfReferentialMacrosInAST::visit(%s) \n",node->class_name().c_str());
             }
        }

   }
Exemplo n.º 10
0
    virtual void visit(SgNode* n) {
        if (isSgVarRefExp(n)) {
            SgVarRefExp* copy_vr = isSgVarRefExp(n);
            assert (copy_vr->get_symbol());
            SgInitializedName* copy = copy_vr->get_symbol()->get_declaration();
            assert (copy);
            SgInitializer* copyinit = copy->get_initializer();
            SgScopeStatement* copyscope =
                SageInterface::getScope(copy->get_parent()->get_parent());
            if (isSgAssignInitializer(copyinit)) {
                SgAssignInitializer* init =
                    isSgAssignInitializer(copyinit);
                SgExpression* orig_expr = init->get_operand();
                // cout << "orig is " << orig_expr->unparseToString() << ", copy is " << copy->get_name().str() << endl;
                if (!isPotentiallyModified(copy_vr, copyscope) &&
                        !isSgGlobal(copyscope) &&
                        !isSgNamespaceDefinitionStatement(copyscope)) {
                    bool shouldReplace = false;
                    if (isSgVarRefExp(orig_expr)) {
                        SgVarRefExp* orig_vr = isSgVarRefExp(orig_expr);
                        // cout << "Found potential copy from " << orig_vr->get_symbol()->get_name().str() << " to " << copy_vr->get_symbol()->get_name().str() << endl;
                        SgInitializedName* orig =
                            orig_vr->get_symbol()->get_declaration();
                        assert (orig);
                        SgNode* origscope = orig->get_parent()->get_parent();
                        assert (origscope);
                        if (!hasAddressTaken(orig_vr, origscope) &&
                                isSgBasicBlock(copyscope) &&
                                !isPotentiallyModifiedDuringLifeOf(isSgBasicBlock(copyscope),
                                        orig, copy) &&
                                !isSgGlobal(origscope) &&
                                !isSgNamespaceDefinitionStatement(origscope)) {
                            shouldReplace = true;
                        }
                    } else if (isSgValueExp(orig_expr)) {
                        shouldReplace = true;
                    }
                    // cout << "shouldReplace is " << shouldReplace << endl;
                    if (shouldReplace) {
                        assert (orig_expr);
                        SgExpression* orig_copy = isSgExpression(orig_expr /*->copy(SgTreeCopy()) */);
                        assert (orig_copy);
                        orig_copy->set_parent(copy_vr->get_parent());
                        orig_copy->set_lvalue(copy_vr->get_lvalue());

                        ROSE_ASSERT(copy_vr != NULL);
                        ROSE_ASSERT(copy_vr->get_parent() != NULL);
                        // ROSE_ASSERT(isSgExpression(copy_vr->get_parent()) != NULL);

                        // DQ (12/15/2006): Need to handle cases where the parent is a SgStatement or a SgExpression (or make it an error).
                        // isSgExpression(copy_vr->get_parent())->replace_expression(copy_vr, orig_copy);
                        SgStatement* statement = isSgStatement(copy_vr->get_parent());
                        if (statement != NULL)
                        {
                            statement->replace_expression(copy_vr, orig_copy);
                        }
                        else
                        {
                            SgExpression* expression = isSgExpression(copy_vr->get_parent());
                            if (expression != NULL)
                            {
                                expression->replace_expression(copy_vr, orig_copy);
                            }
                            else
                            {
                                printf ("Error: what is this copy_vr->get_parent() = %s \n",copy_vr->get_parent()->class_name().c_str());
                                ROSE_ASSERT(false);
                            }
                        }

                    }
                }
            }
        }
    }
void
FixupSelfReferentialMacrosInAST::visit ( SgNode* node )
   {
  // DQ (3/11/2006): Set NULL pointers where we would like to have none.
  // printf ("In FixupSelfReferentialMacrosInAST::visit(): node = %s \n",node->class_name().c_str());

     ROSE_ASSERT(node != NULL);
     switch (node->variantT())
        {
          case V_SgInitializedName:
             {
               SgInitializedName* initializedName = isSgInitializedName(node);
               ROSE_ASSERT(initializedName != NULL);
               SgType* type = initializedName->get_type()->stripType();
               SgClassType* classType = isSgClassType(type);
               if (classType != NULL)
                  {
                    SgClassDeclaration* targetClassDeclaration = isSgClassDeclaration(classType->get_declaration());
                    SgName className = targetClassDeclaration->get_name();

                 // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a class declaration name = %s \n",className.str());

                 // For sudo_exec_pty.c also look for siginfo
                    if (className == "sigaction" || className == "siginfo")
                       {
                      // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a sigaction type \n");

                      // Note we could also check that the declaration came from a known header file.
                         SgStatement* associatedStatement = isSgStatement(initializedName->get_parent());
                         if (associatedStatement != NULL)
                            {
                           // Add a macro to undefine the "#define sa_handler __sigaction_handler.sa_handler" macro.
                           // printf ("In FixupSelfReferentialMacrosInAST::visit(): Add a macro to undefine the macro #define sa_handler __sigaction_handler.sa_handler \n");

                           // PreprocessingInfo* macro = new PreprocessingInfo(DirectiveType, const std::string & inputString,const std::string & filenameString, int line_no , int col_no,int nol, RelativePositionType relPos );

                              PreprocessingInfo::DirectiveType directiveType = PreprocessingInfo::CpreprocessorUndefDeclaration;

                           // We are puting out all macros anytime we see either type.  This might be too much...

                           // From the sigaction.h file (included by signal.h):
                              addMacro(associatedStatement,"#undef sa_handler\n",directiveType);
                              addMacro(associatedStatement,"#undef sa_sigaction\n",directiveType);

                           // From the siginfo.h file (included by signal.h):
                              addMacro(associatedStatement,"#undef si_pid\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_uid\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_timerid\n",directiveType);
                              addMacro(associatedStatement,"#undef si_overrun\n",directiveType);
                              addMacro(associatedStatement,"#undef si_status\n", directiveType);
                              addMacro(associatedStatement,"#undef si_utime\n",  directiveType);
                              addMacro(associatedStatement,"#undef si_stime\n",  directiveType);
                              addMacro(associatedStatement,"#undef si_value\n",  directiveType);
                              addMacro(associatedStatement,"#undef si_int\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_ptr\n",    directiveType);
                              addMacro(associatedStatement,"#undef si_addr\n",   directiveType);
                              addMacro(associatedStatement,"#undef si_band\n",   directiveType);
                              addMacro(associatedStatement,"#undef si_fd\n",     directiveType);
                            }
                       }
                  }
             }

          default:
             {
            // printf ("Not handled in FixupSelfReferentialMacrosInAST::visit(%s) \n",node->class_name().c_str());
             }
        }

#if 0
  // DQ (12/30/2013): Comments and CPP directives have not yet been attached to the AST, so we can't process them here.

  // SgLocatedNode* locatedNode = isSgLocatedNode(node);
  // if (locatedNode != NULL)
     SgStatement* stmt = isSgStatement(node);
     if (stmt != NULL)
        {
       // Find all #define statements and look for self referencing macros

          int numberOfComments = -1;
          if (stmt->getAttachedPreprocessingInfo() != NULL)
               numberOfComments = stmt->getAttachedPreprocessingInfo()->size();

          std::string s = std::string(" --- startOfConstruct: file = " ) + stmt->get_startOfConstruct()->get_filenameString()
             + " raw filename = " + stmt->get_startOfConstruct()->get_raw_filename()
             + " raw line = "     + StringUtility::numberToString(stmt->get_startOfConstruct()->get_raw_line())
             + " raw column = "   + StringUtility::numberToString(stmt->get_startOfConstruct()->get_raw_col())
             + " #comments = "    + StringUtility::numberToString(numberOfComments)
             + " \n ";

          AttachedPreprocessingInfoType* comments = stmt->getAttachedPreprocessingInfo();

          if (comments != NULL)
             {
               printf ("Found attached comments (at %p of type: %s): \n",stmt,stmt->class_name().c_str());
               AttachedPreprocessingInfoType::iterator i;
               for (i = comments->begin(); i != comments->end(); i++)
                  {
                    ROSE_ASSERT ( (*i) != NULL );
                    printf ("          Attached Comment (relativePosition=%s): %s\n",
                         ((*i)->getRelativePosition() == PreprocessingInfo::before) ? "before" : "after",
                         (*i)->getString().c_str());
                    printf ("Comment/Directive getNumberOfLines = %d getColumnNumberOfEndOfString = %d \n",(*i)->getNumberOfLines(),(*i)->getColumnNumberOfEndOfString());
                    (*i)->get_file_info()->display("comment/directive location");
                  }
             }
            else
             {
               printf ("No attached comments (at %p of type: %s): \n",stmt,stmt->class_name().c_str());
             }
        }
#endif
   }