Esempio n. 1
0
Transformation<double> StereoCartography::estimateOdometry(const vector<Feature> & featureVec)
{
    //Matching
    
    int numLandmarks = LM.size();
    int numActive = min(300, numLandmarks);
    vector<Feature> lmFeatureVec;
//    cout << "ca va" << endl;
    for (unsigned int i = numLandmarks - numActive; i < numLandmarks; i++)
    {
        lmFeatureVec.push_back(Feature(Vector2d(0, 0), LM[i].d));
    }
//    cout << "ca va" << endl;       
    Matcher matcher;    
    vector<int> matchVec;    
    matcher.bruteForce(featureVec, lmFeatureVec, matchVec);
    
    Odometry odometry(trajectory.back(), stereo.TbaseCam1, stereo.cam1);
//    cout << "ca va" << endl;
    for (unsigned int i = 0; i < featureVec.size(); i++)
    {
        const int match = matchVec[i];
        if (match == -1) continue;
        odometry.observationVec.push_back(featureVec[i].pt);
        odometry.cloud.push_back(LM[numLandmarks  - numActive + match].X);
    }
//    cout << "cloud : " << odometry.cloud.size() << endl;
    //RANSAC
    odometry.Ransac();
//    cout << odometry.TorigBase << endl;
    //Final transformation computation
    odometry.computeTransformation();
//    cout << odometry.TorigBase << endl;
    return odometry.TorigBase;
}
std::list<const LLToast*> LLScreenChannel::findToasts(const Matcher& matcher)
{
	std::list<const LLToast*> res;

	// collect stored toasts
	for (std::vector<ToastElem>::iterator it = mStoredToastList.begin(); it
			!= mStoredToastList.end(); it++)
	{
		const LLToast* toast = it->getToast();
		if (toast && matcher.matches(toast->getNotification()))
		{
			res.push_back(toast);
		}
	}

	// collect displayed toasts
	for (std::vector<ToastElem>::iterator it = mToastList.begin(); it
			!= mToastList.end(); it++)
	{
		const LLToast* toast = it->getToast();
		if (toast && matcher.matches(toast->getNotification()))
		{
			res.push_back(toast);
		}
	}

	return res;
}
Esempio n. 3
0
int main() {
    Matcher match;
    for (int i=1000; i<=100000; i+=1000) {
        clock_timer timer;
        list.clear();
        for(int j = 0; j <= i; ++j){
            list.push_back(j);
        }
        timer.start_timer();
        int hits1 = match.nSquare(i*2+1, list);
        //int hits2 = match.nLogn(i*2+1, list);
        timer.stop_timer();
        dataVector.push_back(std::make_pair(i, timer.duration));
        std::cout << "found: " << hits1 << std::endl;
    }
    
    std::ofstream myfile;
    myfile.open("A.txt");
    
    while(!dataVector.empty()) {
        std::cout<<dataVector.front().first <<" , "<<dataVector.front().second <<std::endl;
        myfile<< dataVector.front().first << "\t" << dataVector.front().second << "\n";
        dataVector.pop_front();
    }
    myfile.close();
    
    return 0;
}
Esempio n. 4
0
void AddWordMatcherImpl::operator()( boost::ptr_vector<Matcher> & matchers, const std::string & base, SpeechPart speechPart, uint index, boost::ptr_vector< Restriction > & restrictions ) const {
   	Matcher * matcher = new WordMatcher( base, speechPart );

   	matcher->variable = Variable( speechPart, index );
   	matcher->addRestrictions( restrictions );

   	matchers.push_back( matcher );
}
TEST(MatcherTest, PropertyTesting)
{
	Matcher<Sut&> m = Field(&Sut::d, Eq(0));
	MockIntf mock;
	Sut testObj(&mock);

	EXPECT_FALSE(m.Matches(testObj));
	testObj.d=0;
	EXPECT_TRUE(m.Matches(testObj));
}
TEST(MatcherTest, MatchAndExplain)
{
	Matcher<const Sut&> m = checkSumGreaterThan(10);
	StringMatchResultListener listener;
	MockIntf mock;
	Sut testObj(&mock);
	
	testObj.setA(5);
	testObj.setB(6);
	EXPECT_TRUE(m.MatchAndExplain(testObj, &listener));

	testObj.setB(1);
	EXPECT_FALSE(m.MatchAndExplain(testObj, &listener));
}
Esempio n. 7
0
/// unlinkNode - Unlink the specified node from this chain.  If Other == this,
/// we unlink the next pointer and return it.  Otherwise we unlink Other from
/// the list and return this.
Matcher *Matcher::unlinkNode(Matcher *Other) {
  if (this == Other)
    return takeNext();

  // Scan until we find the predecessor of Other.
  Matcher *Cur = this;
  for (; Cur && Cur->getNext() != Other; Cur = Cur->getNext())
    /*empty*/;

  if (Cur == 0) return 0;
  Cur->takeNext();
  Cur->setNext(Other->takeNext());
  return this;
}
void LLScreenChannel::closeHiddenToasts(const Matcher& matcher)
{
	// since we can't guarantee that close toast operation doesn't change mToastList
	// we collect matched toasts that should be closed into separate list
	std::list<LLToast*> toasts;
	for (std::vector<ToastElem>::iterator it = mToastList.begin(); it
			!= mToastList.end(); it++)
	{
		LLToast* toast = it->getToast();
		// add to list valid toast that match to provided matcher criteria
		if (toast != NULL && !toast->isDead() && toast->getNotification() != NULL
				&& !toast->getVisible() && matcher.matches(toast->getNotification()))
		{
			toasts.push_back(toast);
		}
	}

	// close collected toasts
	for (std::list<LLToast*>::iterator it = toasts.begin(); it
			!= toasts.end(); it++)
	{
		LLToast* toast = *it;
		toast->closeFloater();
	}
}
Esempio n. 9
0
//------------------------------sched_call-------------------------------------
uint Block::sched_call( Matcher &m, Block_Array &bbs, uint node_cnt, Node_List &worklist, int *ready_cnt, MachCallNode *mcall, VectorSet &next_call ) {
  RegMask regs;

  // Schedule all the users of the call right now.  All the users are
  // projection Nodes, so they must be scheduled next to the call.
  // Collect all the defined registers.
  for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
    Node* n = mcall->fast_out(i);
    assert( n->Opcode()==Op_MachProj, "" );
    --ready_cnt[n->_idx];
    assert( !ready_cnt[n->_idx], "" );
    // Schedule next to call
    _nodes.map(node_cnt++, n);
    // Collect defined registers
    regs.OR(n->out_RegMask());
    // Check for scheduling the next control-definer
    if( n->bottom_type() == Type::CONTROL ) 
      // Warm up next pile of heuristic bits
      needed_for_next_call(n, next_call, bbs);

    // Children of projections are now all ready
    for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
      Node* m = n->fast_out(j); // Get user
      if( bbs[m->_idx] != this ) continue;
      if( m->is_Phi() ) continue;
      if( !--ready_cnt[m->_idx] ) 
        worklist.push(m);
    }
  
  }

  // Act as if the call defines the Frame Pointer.
  // Certainly the FP is alive and well after the call.
  regs.Insert(m.c_frame_pointer());

  // Set all registers killed and not already defined by the call.
  uint r_cnt = mcall->tf()->range()->cnt();
  int op = mcall->ideal_Opcode();
  MachProjNode *proj = new (1) MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
  bbs.map(proj->_idx,this);
  _nodes.insert(node_cnt++, proj);

  for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {
    if( !regs.Member(r) ) {     // Not already defined by the call  
      // Save-on-call register?
      if( (m._register_save_policy[r] == 'C') ||
          (m._register_save_policy[r] == 'A') ||
          ((m._register_save_policy[r] == 'E') &&
           (op == Op_CallRuntime     ||
            op == Op_CallNative      ||
            op == Op_CallInterpreter ||
            op == Op_CallLeaf)) ) { 
        proj->_rout.Insert(r);
      }
    }
  }

  return node_cnt;
}
Esempio n. 10
0
	void readPapers(int papers, Scanner scanIn) {
		int paper;
		for (paper = 1; paper <= papers; paper++) {
			String paperAuthors;

			paperAuthors = scanIn.nextLine();
			#ifdef DEBUG
				printf("paper #%d %s\n", paper, paperAuthors);
			#endif

			Author authors[] = new Author[Author.MAX_PAPER_AUTHORS];
			int authorsIndex = 0;

			Pattern p = Pattern.compile("\\s*(\\S*)[,]\\s*(\\S*)[,:]");
			Matcher m = p.matcher(paperAuthors);
			while (m.find()) {
				String lname = m.group(1);
				String fname = m.group(2);

				if (debug) {
					printf("\t'%s' => '%s', '%s'\n", paperAuthors, lname, fname);
				}

				authors[authorsIndex] = Author.find(fname, lname);
				if (authors[authorsIndex] == null) {
					if (lname.length() == 0 || fname.length() == 0) {
						continue;
					}
					authors[authorsIndex] = new Author(fname, lname);
				}
				authorsIndex++;
			}

			for (int i = 0; i < authorsIndex; i++) {
				for (int j = 0; j < authorsIndex; j++) {
					authors[i].publicouCom(authors[j]);
				}
			}
		}
	}
Esempio n. 11
0
void Tok::Unresolve(Matcher const &matcher)
{
    int i;
    TokIdNode *nd;

    for(i = node.size(); i--;)
    {
        for(nd = node[i]; nd->v_prev != 0 && !matcher.Match(nd); nd = nd->v_prev)
        {
            unres[i + 1].push_front(nd->id[0]);
        }
    }
}
Esempio n. 12
0
int AdHunterImpl::getBestAdTargets(double minPrice, int pagesPerSite, vector<Match>& matches)
{
    matches.clear();
	for (int i = 0; i < m_seedSites.size(); i++)
	{
		Crawler c(m_seedSites[i]);
		int page = 0;
		for (Document* d = c.crawl();  page < pagesPerSite && d != NULL; page++, d = c.crawl())
			m_matcher.process(*d,minPrice,matches);
	}

	return matches.size();
}
Esempio n. 13
0
void find(string text, string pattern, int expect) {
    Matcher * impl = getImpl(pattern);
    
    clock_t start_time = clock();
    int pos = impl->find(text);
    clock_t end_time = clock();

    printf("pos :%d\texpect : %d\n", pos, expect);


    assert(pos == expect);
   // cout << pattern.size() << endl;
    string out_text = (text.size() <= 100) ? text : "Too Long";
    string out_pattern =(pattern.size() <= 100) ? pattern : "Too Long";

    
    printf("start time : %lu\n", start_time);
    printf("end   time : %lu\n", end_time);

    printf("text          : %s\npattern       : %s\nmatch positon : %d\nexecution time: %lfs\n\n", 
            out_text.c_str(), out_pattern.c_str() , pos, ((double) end_time - start_time) / CLOCKS_PER_SEC);
    delete impl;
}
Esempio n. 14
0
int MatcherDecode(SimpleImage* image,char code[4])
{
	SimpleImage* gray = siCreateImage(image->width,image->height,1);
	if (image->nChannels != 1)
	{
		siRgbToGray(image,gray);
	}
	//siThreshold(gray,gray,150,255);
	siThreshold(gray,gray,115,255);

	int ret = thiz.Decode(gray,code);
	siReleaseImage(&gray);
	return ret;
}
Esempio n. 15
0
void QueryPreProcessor::parseQuery(string query) {
	vector<string> first_split = split(query, ';'); //
	vector<string> result_part;
	vector<string> query_part;

	Matcher* m = new Matcher();
	for(size_t i = 0 ; i < first_split.size() ; i ++)
	{
		if(!m->checkTokens(first_split[i], "select"))
			result_part.push_back(first_split[i]);
		else
			query_part.push_back(first_split[i]);
	}
	delete m;

	if(query_part.size() == 0) {
		exc->throwException();
	}

	//writeVector(result_part);

	//cout << m->checkProcName(result_part[0]) << endl;
	//cout << m->checkVarName(result_part[0]) << endl;
	//cout << m->checkStmt_(result_part[0]) << endl;
	//cout << m->checkAll(result_part[0]) << endl;

	vector<Field> fields = makeFields(result_part);
	setFields(fields);

	//writeVector(query_part);

	makeTree(query_part);
	/*
	for (int j = 0; j < fields.size(); j++) {
		cout << fields[j].getType() << " " << fields[j].getValue() << endl;
	}*/
}
Esempio n. 16
0
	int readCases(int names, Scanner *scanIn, Collection<Entry<String, Author>> *theMap,
			Set<Author> *targets) {
		int nameInd;
		for (nameInd = 1; nameInd <= names; nameInd++) {
			String bigname;

			bigname = scanIn.nextLine();
			#ifdef DEBUG
				printf("\tname #%d %s\n", nameInd, bigname);
			#endif

			Pattern p = Pattern.compile("\\s*(\\S*)[,]\\s*(\\S*)");
			Matcher m = p.matcher(bigname);
			if (m.find()) {
				String lname = m.group(1);
				String fname = m.group(2);

				#ifdef DEBUG
					printf("\tmatcher2'%s' => '%s', '%s'\n", bigname, lname, fname);
				#endif

				Author a = Author.find(fname, lname);response

				theMap.add(new MyEntry(bigname, a));
				if (a != null) {
					targets.add(a);
					#ifdef DEBUG
						printf("\tauthor case '%s' is #%d\n", a.lname, targets.size());
					#endif
				}
			} else {
				theMap.add(new Entry<String, Author>(bigname, null));
			}
		}
		return nameInd;
	}
Esempio n. 17
0
TokArr Tok::GetDescendants(Matcher const &matcher) const
{
    TokIdNode *nd[2];
    TokArr rv;

    for(nd[0] = TokIdNode::GetLeaf(nd[1] = Node()); nd[0] != nd[1]; nd[0] = TokIdNode::GetNext(nd[0], nd[1]))
    {
        if(matcher.Match(nd[0]))
        {
            rv.push_back(nd[0]);
        }
    }

    return rv;
}
Esempio n. 18
0
void Scanner::doUntil(Matcher const & matcher, std::function<void(char)> before, std::function<void(char)> after)
{
	if( ! is ) return;

	int g;
	while( (g = is.get()) != std::istream::traits_type::eof() ) {
		char ch = g;
		before(ch);
		if( matcher.matches(ch) ) {
			is.putback(ch);
			break;
		}
		after(ch);
	}
}
void Foam::inplaceSubsetMatchingStrings
(
    const Matcher& matcher,
    StringListType& lst,
    const bool invert
)
{
    label nElem = 0;
    forAll(lst, elemI)
    {
        if (matcher.match(lst[elemI]) ? !invert : invert)
        {
            lst[nElem++] = lst[elemI];
        }
    }
    lst.setSize(nElem);
}
Esempio n. 20
0
void LLNotifyBoxView::purgeMessagesMatching(const Matcher& matcher)
{
	// Make a *copy* of the child list to iterate over 
	// since we'll be removing items from the real list as we go.
	LLView::child_list_t notification_queue(*getChildList());
	for(LLView::child_list_iter_t iter = notification_queue.begin();
		iter != notification_queue.end();
		iter++)
	{
		if (isGroupNotifyBox(*iter))
			continue;

		LLNotifyBox* notification = static_cast<LLNotifyBox*>(*iter);
		if (matcher.matches(notification->getNotification()))
		{
			removeChild(notification);
		}
	}
}
StringListType Foam::subsetMatchingStrings
(
    const Matcher& matcher,
    const StringListType& lst,
    const bool invert
)
{
    StringListType newLst(lst.size());

    label nElem = 0;
    forAll(lst, elemI)
    {
        if (matcher.match(lst[elemI]) ? !invert : invert)
        {
            newLst[nElem++] = lst[elemI];
        }
    }
    newLst.setSize(nElem);

    return newLst;
}
Foam::labelList Foam::findMatchingStrings
(
    const Matcher& matcher,
    const UList<StringType>& lst,
    const bool invert
)
{
    labelList indices(lst.size());

    label nElem = 0;
    forAll(lst, elemI)
    {
        if (matcher.match(lst[elemI]) ? !invert : invert)
        {
            indices[nElem++] = elemI;
        }
    }
    indices.setSize(nElem);

    return indices;
}
//=============================================================================
//------------------------------PhaseCFG---------------------------------------
PhaseCFG::PhaseCFG(ResourceArea*a,RootNode*r,Matcher&m):
  Phase(CFG),
  _bbs(a),
  _root(r)
#ifndef PRODUCT
  , _trace_opto_pipelining(TraceOptoPipelining || C->method_has_option("TraceOptoPipelining"))
#endif
{
  ResourceMark rm;
  // I'll need a few machine-specific GotoNodes.  Make an Ideal GotoNode,
  // then Match it into a machine-specific Node.  Then clone the machine
  // Node on demand.
  Node *x = new (C, 1) GotoNode(NULL);
  x->init_req(0, x);
  _goto = m.match_tree(x);
  assert(_goto != NULL, "");
  _goto->set_req(0,_goto);

  // Build the CFG in Reverse Post Order
  _num_blocks = build_cfg();
  _broot = _bbs[_root->_idx];
}
Esempio n. 24
0
std::vector< std::pair< TokIdNode *, int > > TokIdNode::AmbigResolve(
    TokIdNode const *node,
    std::deque< TokId >::const_iterator arr,
    int len,
    Matcher const &matcher,
    TokIdNode const *context,
    TokIdNode const *subroot)
{
    int i;
    Map::const_iterator it, itEnd;
    std::vector< std::pair< TokIdNode *, int > > rv[2];
    TokIdNode const *nd;

    if(len == 0)
    {
        if(node && node->IsInContext(context) && matcher.Match(node))
        {
            rv[0].push_back(std::make_pair((TokIdNode *)node, 0));
        }
        return rv[0];
    }

    if(node && !context->IsInContext(node) && !node->IsInContext(context))
    {
        return rv[0];
    }

    if(!context->IsInContext(subroot))
    {
        PNL_THROW(pnl::CBadArg, "context must lie in subtree rooted at subroot");
    }

    if(node == 0 && subroot->Match(arr[0]))
    {
        rv[1] = AmbigResolve(subroot, arr + 1, len - 1, matcher, context, subroot);
        for(i = rv[1].size(); i--;)
        {
            rv[0].push_back(std::make_pair(rv[1][i].first, rv[1][i].second + 1));
        }
    }

    nd = node ? node : subroot;
    it = nd->desc.find(arr[0]);
    if(it != nd->desc.end())
    {
	for(itEnd = nd->desc.upper_bound(arr[0]); it != itEnd; ++it)
	{
	    rv[1] = AmbigResolve(it->second, arr + 1, len - 1, matcher, context, subroot);
	    for(i = rv[1].size(); i--;)
	    {
		rv[0].push_back(std::make_pair(rv[1][i].first, rv[1][i].second + 1));
	    }
	}
    }

    if(rv[0].empty())
    {
        rv[0].push_back(std::make_pair((TokIdNode *)node, 0));
    }
    return rv[0];
}
Esempio n. 25
0
    bool run(OperationContext* txn,
             const std::string& db,
             BSONObj& cmdObj,
             int options,
             std::string& errmsg,
             BSONObjBuilder& result) final {
        const bool includeAll = cmdObj["$all"].trueValue();
        const bool ownOpsOnly = cmdObj["$ownOps"].trueValue();

        // Filter the output
        BSONObj filter;
        {
            BSONObjBuilder b;
            BSONObjIterator i(cmdObj);
            invariant(i.more());
            i.next();  // skip {currentOp: 1} which is required to be the first element
            while (i.more()) {
                BSONElement e = i.next();
                if (str::equals("$all", e.fieldName())) {
                    continue;
                } else if (str::equals("$ownOps", e.fieldName())) {
                    continue;
                }

                b.append(e);
            }
            filter = b.obj();
        }

        std::vector<BSONObj> inprogInfos;
        BSONArrayBuilder inprogBuilder(result.subarrayStart("inprog"));

        for (ServiceContext::LockedClientsCursor cursor(txn->getClient()->getServiceContext());
             Client* client = cursor.next();) {
            invariant(client);

            stdx::lock_guard<Client> lk(*client);

            if (ownOpsOnly &&
                !AuthorizationSession::get(txn->getClient())->isCoauthorizedWithClient(client)) {
                continue;
            }

            const OperationContext* opCtx = client->getOperationContext();

            if (!includeAll) {
                // Skip over inactive connections.
                if (!opCtx)
                    continue;
            }

            BSONObjBuilder infoBuilder;

            // The client information
            client->reportState(infoBuilder);

            const auto& clientMetadata =
                ClientMetadataIsMasterState::get(client).getClientMetadata();
            if (clientMetadata) {
                auto appName = clientMetadata.get().getApplicationName();
                if (!appName.empty()) {
                    infoBuilder.append("appName", appName);
                }
            }

            // Operation context specific information
            infoBuilder.appendBool("active", static_cast<bool>(opCtx));
            if (opCtx) {
                infoBuilder.append("opid", opCtx->getOpID());
                if (opCtx->isKillPending()) {
                    infoBuilder.append("killPending", true);
                }

                CurOp::get(opCtx)->reportState(&infoBuilder);

                // LockState
                Locker::LockerInfo lockerInfo;
                opCtx->lockState()->getLockerInfo(&lockerInfo);
                fillLockerInfo(lockerInfo, infoBuilder);
            }

            // If we want to include all results or if the filter is empty, then we can append
            // straight to the inprogBuilder, but otherwise we should run the filter Matcher
            // outside this loop so we don't lock the ServiceContext while matching - in some cases
            // this can cause deadlocks.
            if (includeAll || filter.isEmpty()) {
                inprogBuilder.append(infoBuilder.obj());
            } else {
                inprogInfos.emplace_back(infoBuilder.obj());
            }
        }

        if (!inprogInfos.empty()) {
            // We use ExtensionsCallbackReal here instead of ExtensionsCallbackNoop in order to
            // support the use case of having a $where filter with currentOp. However, since we
            // don't have a collection, we pass in a fake collection name (and this is okay,
            // because $where parsing only relies on the database part of the namespace).
            const NamespaceString fakeNS(db, "$dummyNamespaceForCurrop");
            const Matcher matcher(filter, ExtensionsCallbackReal(txn, &fakeNS), nullptr);

            for (const auto& info : inprogInfos) {
                if (matcher.matches(info)) {
                    inprogBuilder.append(info);
                }
            }
        }
        inprogBuilder.done();

        if (lockedForWriting()) {
            result.append("fsyncLock", true);
            result.append("info",
                          "use db.fsyncUnlock() to terminate the fsync write/snapshot lock");
        }

        return true;
    }
Esempio n. 26
0
int MatcherInitImage(SimpleImage* image,const char* charArray)
{
	return thiz.Init(image,charArray);
}
Esempio n. 27
0
int MatcherInit(const char* fontData,const char* charArray)
{
	return thiz.Init(fontData,charArray);
}
Esempio n. 28
0
//------------------------------sched_call-------------------------------------
uint Block::sched_call( Matcher &matcher, Block_Array &bbs, uint node_cnt, Node_List &worklist, GrowableArray<int> &ready_cnt, MachCallNode *mcall, VectorSet &next_call ) {
  RegMask regs;

  // Schedule all the users of the call right now.  All the users are
  // projection Nodes, so they must be scheduled next to the call.
  // Collect all the defined registers.
  for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
    Node* n = mcall->fast_out(i);
    assert( n->is_MachProj(), "" );
    int n_cnt = ready_cnt.at(n->_idx)-1;
    ready_cnt.at_put(n->_idx, n_cnt);
    assert( n_cnt == 0, "" );
    // Schedule next to call
    _nodes.map(node_cnt++, n);
    // Collect defined registers
    regs.OR(n->out_RegMask());
    // Check for scheduling the next control-definer
    if( n->bottom_type() == Type::CONTROL )
      // Warm up next pile of heuristic bits
      needed_for_next_call(n, next_call, bbs);

    // Children of projections are now all ready
    for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
      Node* m = n->fast_out(j); // Get user
      if( bbs[m->_idx] != this ) continue;
      if( m->is_Phi() ) continue;
      int m_cnt = ready_cnt.at(m->_idx)-1;
      ready_cnt.at_put(m->_idx, m_cnt);
      if( m_cnt == 0 )
        worklist.push(m);
    }

  }

  // Act as if the call defines the Frame Pointer.
  // Certainly the FP is alive and well after the call.
  regs.Insert(matcher.c_frame_pointer());

  // Set all registers killed and not already defined by the call.
  uint r_cnt = mcall->tf()->range()->cnt();
  int op = mcall->ideal_Opcode();
  MachProjNode *proj = new (matcher.C, 1) MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
  bbs.map(proj->_idx,this);
  _nodes.insert(node_cnt++, proj);

  // Select the right register save policy.
  const char * save_policy;
  switch (op) {
    case Op_CallRuntime:
    case Op_CallLeaf:
    case Op_CallLeafNoFP:
      // Calling C code so use C calling convention
      save_policy = matcher._c_reg_save_policy;
      break;

    case Op_CallStaticJava:
    case Op_CallDynamicJava:
      // Calling Java code so use Java calling convention
      save_policy = matcher._register_save_policy;
      break;

    default:
      ShouldNotReachHere();
  }

  // When using CallRuntime mark SOE registers as killed by the call
  // so values that could show up in the RegisterMap aren't live in a
  // callee saved register since the register wouldn't know where to
  // find them.  CallLeaf and CallLeafNoFP are ok because they can't
  // have debug info on them.  Strictly speaking this only needs to be
  // done for oops since idealreg2debugmask takes care of debug info
  // references but there no way to handle oops differently than other
  // pointers as far as the kill mask goes.
  bool exclude_soe = op == Op_CallRuntime;

  // If the call is a MethodHandle invoke, we need to exclude the
  // register which is used to save the SP value over MH invokes from
  // the mask.  Otherwise this register could be used for
  // deoptimization information.
  if (op == Op_CallStaticJava) {
    MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall;
    if (mcallstaticjava->_method_handle_invoke)
      proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask());
  }

  add_call_kills(proj, regs, save_policy, exclude_soe);

  return node_cnt;
}
Esempio n. 29
0
//------------------------------schedule_local---------------------------------
// Topological sort within a block.  Someday become a real scheduler.
bool Block::schedule_local(PhaseCFG *cfg, Matcher &matcher, GrowableArray<int> &ready_cnt, VectorSet &next_call) {
  // Already "sorted" are the block start Node (as the first entry), and
  // the block-ending Node and any trailing control projections.  We leave
  // these alone.  PhiNodes and ParmNodes are made to follow the block start
  // Node.  Everything else gets topo-sorted.

#ifndef PRODUCT
    if (cfg->trace_opto_pipelining()) {
      tty->print_cr("# --- schedule_local B%d, before: ---", _pre_order);
      for (uint i = 0;i < _nodes.size();i++) {
        tty->print("# ");
        _nodes[i]->fast_dump();
      }
      tty->print_cr("#");
    }
#endif

  // RootNode is already sorted
  if( _nodes.size() == 1 ) return true;

  // Move PhiNodes and ParmNodes from 1 to cnt up to the start
  uint node_cnt = end_idx();
  uint phi_cnt = 1;
  uint i;
  for( i = 1; i<node_cnt; i++ ) { // Scan for Phi
    Node *n = _nodes[i];
    if( n->is_Phi() ||          // Found a PhiNode or ParmNode
        (n->is_Proj()  && n->in(0) == head()) ) {
      // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt
      _nodes.map(i,_nodes[phi_cnt]);
      _nodes.map(phi_cnt++,n);  // swap Phi/Parm up front
    } else {                    // All others
      // Count block-local inputs to 'n'
      uint cnt = n->len();      // Input count
      uint local = 0;
      for( uint j=0; j<cnt; j++ ) {
        Node *m = n->in(j);
        if( m && cfg->_bbs[m->_idx] == this && !m->is_top() )
          local++;              // One more block-local input
      }
      ready_cnt.at_put(n->_idx, local); // Count em up

#ifdef ASSERT
      if( UseConcMarkSweepGC || UseG1GC ) {
        if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_StoreCM ) {
          // Check the precedence edges
          for (uint prec = n->req(); prec < n->len(); prec++) {
            Node* oop_store = n->in(prec);
            if (oop_store != NULL) {
              assert(cfg->_bbs[oop_store->_idx]->_dom_depth <= this->_dom_depth, "oop_store must dominate card-mark");
            }
          }
        }
      }
#endif

      // A few node types require changing a required edge to a precedence edge
      // before allocation.
      if( n->is_Mach() && n->req() > TypeFunc::Parms &&
          (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||
           n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {
        // MemBarAcquire could be created without Precedent edge.
        // del_req() replaces the specified edge with the last input edge
        // and then removes the last edge. If the specified edge > number of
        // edges the last edge will be moved outside of the input edges array
        // and the edge will be lost. This is why this code should be
        // executed only when Precedent (== TypeFunc::Parms) edge is present.
        Node *x = n->in(TypeFunc::Parms);
        n->del_req(TypeFunc::Parms);
        n->add_prec(x);
      }
    }
  }
  for(uint i2=i; i2<_nodes.size(); i2++ ) // Trailing guys get zapped count
    ready_cnt.at_put(_nodes[i2]->_idx, 0);

  // All the prescheduled guys do not hold back internal nodes
  uint i3;
  for(i3 = 0; i3<phi_cnt; i3++ ) {  // For all pre-scheduled
    Node *n = _nodes[i3];       // Get pre-scheduled
    for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
      Node* m = n->fast_out(j);
      if( cfg->_bbs[m->_idx] ==this ) { // Local-block user
        int m_cnt = ready_cnt.at(m->_idx)-1;
        ready_cnt.at_put(m->_idx, m_cnt);   // Fix ready count
      }
    }
  }

  Node_List delay;
  // Make a worklist
  Node_List worklist;
  for(uint i4=i3; i4<node_cnt; i4++ ) {    // Put ready guys on worklist
    Node *m = _nodes[i4];
    if( !ready_cnt.at(m->_idx) ) {   // Zero ready count?
      if (m->is_iteratively_computed()) {
        // Push induction variable increments last to allow other uses
        // of the phi to be scheduled first. The select() method breaks
        // ties in scheduling by worklist order.
        delay.push(m);
      } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {
        // Force the CreateEx to the top of the list so it's processed
        // first and ends up at the start of the block.
        worklist.insert(0, m);
      } else {
        worklist.push(m);         // Then on to worklist!
      }
    }
  }
  while (delay.size()) {
    Node* d = delay.pop();
    worklist.push(d);
  }

  // Warm up the 'next_call' heuristic bits
  needed_for_next_call(_nodes[0], next_call, cfg->_bbs);

#ifndef PRODUCT
    if (cfg->trace_opto_pipelining()) {
      for (uint j=0; j<_nodes.size(); j++) {
        Node     *n = _nodes[j];
        int     idx = n->_idx;
        tty->print("#   ready cnt:%3d  ", ready_cnt.at(idx));
        tty->print("latency:%3d  ", cfg->_node_latency->at_grow(idx));
        tty->print("%4d: %s\n", idx, n->Name());
      }
    }
#endif

  uint max_idx = (uint)ready_cnt.length();
  // Pull from worklist and schedule
  while( worklist.size() ) {    // Worklist is not ready

#ifndef PRODUCT
    if (cfg->trace_opto_pipelining()) {
      tty->print("#   ready list:");
      for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
        Node *n = worklist[i];      // Get Node on worklist
        tty->print(" %d", n->_idx);
      }
      tty->cr();
    }
#endif

    // Select and pop a ready guy from worklist
    Node* n = select(cfg, worklist, ready_cnt, next_call, phi_cnt);
    _nodes.map(phi_cnt++,n);    // Schedule him next

#ifndef PRODUCT
    if (cfg->trace_opto_pipelining()) {
      tty->print("#    select %d: %s", n->_idx, n->Name());
      tty->print(", latency:%d", cfg->_node_latency->at_grow(n->_idx));
      n->dump();
      if (Verbose) {
        tty->print("#   ready list:");
        for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
          Node *n = worklist[i];      // Get Node on worklist
          tty->print(" %d", n->_idx);
        }
        tty->cr();
      }
    }

#endif
    if( n->is_MachCall() ) {
      MachCallNode *mcall = n->as_MachCall();
      phi_cnt = sched_call(matcher, cfg->_bbs, phi_cnt, worklist, ready_cnt, mcall, next_call);
      continue;
    }

    if (n->is_Mach() && n->as_Mach()->has_call()) {
      RegMask regs;
      regs.Insert(matcher.c_frame_pointer());
      regs.OR(n->out_RegMask());

      MachProjNode *proj = new (matcher.C, 1) MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj );
      cfg->_bbs.map(proj->_idx,this);
      _nodes.insert(phi_cnt++, proj);

      add_call_kills(proj, regs, matcher._c_reg_save_policy, false);
    }

    // Children are now all ready
    for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {
      Node* m = n->fast_out(i5); // Get user
      if( cfg->_bbs[m->_idx] != this ) continue;
      if( m->is_Phi() ) continue;
      if (m->_idx >= max_idx) { // new node, skip it
        assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types");
        continue;
      }
      int m_cnt = ready_cnt.at(m->_idx)-1;
      ready_cnt.at_put(m->_idx, m_cnt);
      if( m_cnt == 0 )
        worklist.push(m);
    }
  }

  if( phi_cnt != end_idx() ) {
    // did not schedule all.  Retry, Bailout, or Die
    Compile* C = matcher.C;
    if (C->subsume_loads() == true && !C->failing()) {
      // Retry with subsume_loads == false
      // If this is the first failure, the sentinel string will "stick"
      // to the Compile object, and the C2Compiler will see it and retry.
      C->record_failure(C2Compiler::retry_no_subsuming_loads());
    }
    // assert( phi_cnt == end_idx(), "did not schedule all" );
    return false;
  }

#ifndef PRODUCT
  if (cfg->trace_opto_pipelining()) {
    tty->print_cr("#");
    tty->print_cr("# after schedule_local");
    for (uint i = 0;i < _nodes.size();i++) {
      tty->print("# ");
      _nodes[i]->fast_dump();
    }
    tty->cr();
  }
#endif


  return true;
}
//
// Load the D3DAPICalls benchmark report:
//
// benchmarkable_call_number,frame_time_ms,time_difference,call_type,draw_call_number,calls_skipped,calls_executed,ps_text,vs_text,vdecl_text
//
bool loadD3DAPICallsCSVFile(const char *name, const char *fname, const std::vector<std::string> &keywordTable, bool bDiffGraph, bool bCollapse)
{
    char tmpstr[1024];
    int graphDiff = -1;

    std::ifstream fs(fname);
    if(!fs.is_open())
	{
		if(g_pLog) g_pLog->AddMessage("no>>Failure...");
        return false;
	}
    // for size of the file so we can display a progress bar
    fs.seekg( -1, std::ios_base::end );
    int bSize = (int)fs.tellg();
    fs.seekg( 0, std::ios_base::beg );
    g_pProgressBar->SetTitle("Loading D3DAPICalls benchmark data...");
	if(g_pLog) g_pLog->AddMessage("Loading D3DAPICalls benchmark data %s", fname);

    fs.getline(tmpstr, 1023); //Dummy line
    if(*tmpstr == '\0')
	{
		if(g_pLog) g_pLog->AddMessage("no>>Failure...");
        return false;
	}
    g_apiCall.clear();

    int disp = (int)g_pDisplays.size();
    IWindowFolding *pWFold;
    if(disp == 0)
    {
        TLDisplay *pDisp = new TLDisplay(g_hwnd);
        pDisp->name = "API Calls Benchmark";
        g_pDisplays.push_back(pDisp);
        //UI:
        pWFold = g_pwinHandler->CreateWindowFolding((LPCSTR)(1<<16), "API Calls Benchmark", g_pMainContainer);
    }
    else
    {
        pWFold = (IWindowFolding *)g_pwinHandler->Get((LPCSTR)(1<<16))->QueryInterface("IWindowFolding");
    }
    // LET's ASSUME that this is always done in display #0 :
    disp = 0;
    int graphTime = g_pDisplays[disp]->addGraph(name);

    //Create a second graph for time difference...
    if(bDiffGraph)
    {
        TLDisplay *pDisp = new TLDisplay(g_hwnd);
        pDisp->name = "API Calls time difference";
        g_pDisplays.push_back(pDisp);
        graphDiff = g_pDisplays[1]->addGraph(name);
    }
    //UI:
    g_pwinHandler->CreateCtrlCheck((LPCSTR)graphTime, name, pWFold)->SetChecked(true);

    //Examples:
    //-1,2.40242,2.40242,first_call_was_skipped,,1999,0
    //0,2.4076,0.005188,Clear,,1998,1
    //Examples2:
    //-1,2.10559,2.10559,first_call_was_skipped,,4147,0,,,
    //0,2.42992,0.32433,Clear,,4146,1,,,
    //2,2.66265,0.215147,Draw,0,4144,3,ps_ea97b1f6b1cbfb27_1,vs_text_1,vdecl_text_1

    //Fill in the graph
    Pattern::registerPattern("int", "\\s*([\\-0-9]*)\\s*");
    Pattern::registerPattern("float", "\\s*([\\-0-9\\.eE]*)\\s*");
    Pattern::registerPattern("text", "\\s*(\\w*)\\s*");
    Pattern *p = Pattern::compile("{int},{float},{float},(\\w+),?{int},?{int},?{int},?{text},?{text},?{text}");
    Matcher *m = p->createMatcher("");
	int benchmarkable_call_number_collapsed = 0;
    do {
        int benchmarkable_call_number;
        float frame_time_ms;
        float time_difference;
        std::string call_type;
        int draw_call_number;
        int calls_skipped;
        int calls_executed;
        std::string ps_text;
        std::string vs_text;
        std::string vdecl_text;
        std::string comment;

        fs.getline(tmpstr, 1023);
        if(fs.eof())
            break;
        m->setString(tmpstr);
        if(m->findFirstMatch())
        {
            benchmarkable_call_number = atoi(m->getGroup(1).c_str());
            frame_time_ms = (float)atof(m->getGroup(2).c_str());
            time_difference = (float)atof(m->getGroup(3).c_str());
            call_type = m->getGroup(4);
            draw_call_number = atoi(m->getGroup(5).c_str());
            calls_skipped = atoi(m->getGroup(6).c_str());
            calls_executed = atoi(m->getGroup(7).c_str());
            ps_text = m->getGroup(8);
            vs_text = m->getGroup(9);
            vdecl_text = m->getGroup(10);
            comment = m->getGroup(11);
			for(int i=0; i< keywordTable.size(); i++)
			{
				if(call_type == keywordTable[i])
				{
					benchmarkable_call_number = -1;
					break;
				}
			}
            if((!fs.eof()) && (benchmarkable_call_number >= 0))
            {
				if(bCollapse)
					benchmarkable_call_number = benchmarkable_call_number_collapsed;
                if(bDiffGraph)
                    g_pDisplays[1]->addMeasure(graphDiff, TMeasure(time_difference, draw_call_number, call_type.c_str(), vs_text.c_str(), ps_text.c_str()), benchmarkable_call_number);
                g_pDisplays[disp]->addMeasure(graphTime, TMeasure(frame_time_ms, draw_call_number, call_type.c_str(), vs_text.c_str(), ps_text.c_str()), benchmarkable_call_number);
                if(call_type == "Clear")
                {
                    g_pDisplays[disp]->setCommentForMeasure(graphTime, benchmarkable_call_number, call_type.c_str(), NULL, RGB(128,160,128));
                }
                if(call_type == "Draw")
                {
                    g_apiCall.push_back(benchmarkable_call_number);
                    //assert((g_apiCall.size()-1) == draw_call_number);
                }
                /*if((call_type == "Lock")
                    ||(call_type == "memcpy"))
                {
                    g_pDisplays[disp]->setCommentForMeasure(graphTime, benchmarkable_call_number, NULL, NULL, RGB(128,160,128));
                }*/
                if(!comment.empty())
                {
                    int i;
                    while((i=(int)comment.find_first_of("|")) >= 0)
                    {
                        comment.replace(i, 1,"\n");
                    }
                    g_pDisplays[disp]->Graphs[graphTime].Measures[benchmarkable_call_number].tooltipComments = comment;
                }
				benchmarkable_call_number_collapsed++;
            }
        }
        else 
        {
            assert(!"ERROR in parsing the line");
			if(g_pLog) g_pLog->AddMessage("error>>Error in parsing a line");
        }
        if((benchmarkable_call_number % 200)==0)
            g_pProgressBar->SetPercent((float)(100*fs.tellg()/bSize));
    } while(!fs.eof());
	if(g_pLog) g_pLog->AddMessage("yes>>Done");
    return true;
}