コード例 #1
0
ファイル: main.cpp プロジェクト: kivi239/Homeworks
void transformToInt(char *prefix, int l)
{
  ArrayStack s;
  int id = 0;
  while (id < l)
  {
    char c = prefix[id];
    if (c == ' ')
    {
      id++;
      continue;
    }
    if (isOperator(c))
    {
      double b = s.pop();
      double a = s.pop();
      s.push(calc(a, b, c));
      id++;
    }
    else
    {
      int number = 0;
      c = prefix[id];
      while (isNumber(c))
      {
        number *= 10;
        number += (c - '0');
        id++;
        c = prefix[id];
      }
      s.push(number);
    }
  }
  printf("%d\n", s.pop());
}
コード例 #2
0
int main()
{
    int  num;       // the number to be converted
    string numStr;  // string used for input
    int  remainder; // remainder when num is divided by 2
    ArrayStack <int> stackOfRemainders; // remainders
    char response;           // user response
    do
    {
        cout << "Enter positive integer to convert: ";
        cin >> numStr;
        num = atoi(numStr.c_str());
        while (num > 0)
        {
            remainder = num % 2;
            stackOfRemainders.push(remainder);
            num /= 2;
        }

        cout << "Base-two representation: ";
        while ( !stackOfRemainders.isEmpty() )
        {
            remainder = stackOfRemainders.peek();
            stackOfRemainders.pop();
            cout << remainder;
        }
        cout << endl;
        cout << "\nMore (Y or N)? ";
        cin >> response;
    }
    while (response == 'Y' || response == 'y');

    return EXIT_SUCCESS;

}  // end main
コード例 #3
0
void array_stack(){
    ArrayStack<char,100> charStack;
    for(int i = 0;i<100;i++)
        charStack.push('a');
    while(!charStack.empty()){
        char tmp = charStack.top();
        charStack.pop();
    }
}
コード例 #4
0
ファイル: main.cpp プロジェクト: krotovss/oop
int main()
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	ArrayStack<int> s;
	//LinkedStack<int> s;

	const int N = 2;
	for (int i = 0; i < N; ++i)
		s.push(i + 1);

	for (int i = 0; i < N; ++i)
	{
		std::cout << s.peek() << std::endl;
		//s.pop();
	}

	ArrayStack<int> other = s;
	//LinkedStack<int> other = s;
	//other = s;

	s.makeEmpty();

	std::cout << (other.isEmpty() ? 0 : other.peek()) << std::endl;

	std::cout << (s.isEmpty() ? "YES" : "NO") << std::endl;

	return 0;
}
コード例 #5
0
void Test() {
    printf("Before:\n");
    ArrayStack<int> stack;
    stack.push(2);
    stack.push(5);
    stack.push(3);
    stack.push(1);
    stack.push(4);
    stack.push(1);
    for (int i = 0; i<=stack._top; i++)
        printf("%d ", stack._array[i]);
    printf("\n");
    Sort(stack);
    printf("After:\n");
    for (int i = 0; i<=stack._top; i++)
        printf("%d ", stack._array[i]);
    printf("\n");
}
コード例 #6
0
ファイル: rationalize.cpp プロジェクト: ROOTU/coreclr
void Rationalizer::RewriteNodeAsCall(GenTree**             use,
                                     ArrayStack<GenTree*>& parents,
                                     CORINFO_METHOD_HANDLE callHnd,
#ifdef FEATURE_READYTORUN_COMPILER
                                     CORINFO_CONST_LOOKUP entryPoint,
#endif
                                     GenTreeArgList* args)
{
    GenTree* const tree           = *use;
    GenTree* const treeFirstNode  = comp->fgGetFirstNode(tree);
    GenTree* const insertionPoint = treeFirstNode->gtPrev;

    BlockRange().Remove(treeFirstNode, tree);

    // Create the call node
    GenTreeCall* call = comp->gtNewCallNode(CT_USER_FUNC, callHnd, tree->gtType, args);

#if DEBUG
    CORINFO_SIG_INFO sig;
    comp->eeGetMethodSig(callHnd, &sig);
    assert(JITtype2varType(sig.retType) == tree->gtType);
#endif // DEBUG

    call = comp->fgMorphArgs(call);
    // Determine if this call has changed any codegen requirements.
    comp->fgCheckArgCnt();

#ifdef FEATURE_READYTORUN_COMPILER
    call->gtCall.setEntryPoint(entryPoint);
#endif

    // Replace "tree" with "call"
    if (parents.Height() > 1)
    {
        parents.Index(1)->ReplaceOperand(use, call);
    }
    else
    {
        // If there's no parent, the tree being replaced is the root of the
        // statement (and no special handling is necessary).
        *use = call;
    }

    comp->gtSetEvalOrder(call);
    BlockRange().InsertAfter(insertionPoint, LIR::Range(comp->fgSetTreeSeq(call), call));

    // Propagate flags of "call" to its parents.
    // 0 is current node, so start at 1
    for (int i = 1; i < parents.Height(); i++)
    {
        parents.Index(i)->gtFlags |= (call->gtFlags & GTF_ALL_EFFECT) | GTF_CALL;
    }

    // Since "tree" is replaced with "call", pop "tree" node (i.e the current node)
    // and replace it with "call" on parent stack.
    assert(parents.Top() == tree);
    (void)parents.Pop();
    parents.Push(call);
}
コード例 #7
0
ファイル: main.cpp プロジェクト: rballeba/EstructuraDeDadesUB
/**
 * Obtains the expression from the user and enters it to the stack
 * 
 * @param pila ArrayStack which contains the numeric expression
 */
void getStackFromInput(ArrayStack<char> &pila) {
    string stringAux;
    char aux;
    cout << "Introduce a numeric expresion" << endl;
    getline (cin,stringAux);
    for(char aux: stringAux) {
        if (aux == '{' || aux == '}' || aux == '[' || aux == ']' || aux == '(' ||aux == ')') {
            pila.push(aux);
        }
    }
}
コード例 #8
0
ファイル: test.cpp プロジェクト: ColeHoff7/cse274d
int main() {
	srand(time(NULL));
	BinaryHeap<int> heap;
	ArrayStack<int> randList;

	for(int i = 0; i <= 1000; i++){
		int rando = rand() % 10000 + 1;
		randList.add(rando);
	}
	for(int i = 0; i < 1000; i++){
		heap.add(randList.get(i));
		if(heap.checkHeap()){
		  //cout << "Heap Conditions Met..." << endl;
		}
		else{
		  cout << "Heap Conditions NOT Met!" << endl;
		  cout << randList.get(i) << endl;
		  cout << i;
		  return 0;
		}
	}

	int n = 1000;
  for(int i = 0; i <= 100; i++){
  	int rando = rand() % n + 1;
  	heap.remove(rando);

  	if(heap.checkHeap()){
  		cout << "Heap Conditions Met..." << endl;
  	}
  	else{
  		cout << "Heap Conditions NOT Met!" << endl;
  		return 0;
  	}
  	n--;
  }
  cout << "Heap Conditions Were Met On All Removes. Great Success!" << endl;
	return 0;
}
コード例 #9
0
ファイル: main.cpp プロジェクト: rballeba/EstructuraDeDadesUB
/**
 * Checks if a sequence of characters have the correct order to do an arithmetic operation.
 * 
 * @param pila The stack that is going to be analyzed
 * @return true if only if the expression have the correct order
 */
bool comprovaExpresio (ArrayStack<char> &pila) {
    //If the stack is empty, it returns true because there isn't elements to analyze.
    if(!pila.empty()) {
        
        /**
         * If the stack is not empty, we proceed to do the next algorithm:
         * Two elements: pila (the original stack) and pilaAux2 (an auxiliary stack
         * to do the proper operations)
         * 1) If "pilaAux2" is empty, we transfer the last char of "pila" to "pilaAux2"
         *      and we delete this char from "pila". We go directly to step 4.
         *    If "pilaAux2" is not empty, we go to the step 2:
         * 2) We check if the top of pilaAux2 is equal to the opposite of the top
         *      element of "pila" (Note that we only check the closing expression).
         *      If it is true, we delete the char from "pilaAux2" and "pila" and
         *      we go directly to step 4. If it is not true, we go to the step 3.
         * 3) We push the top element of "pila" to "pilaAux". We go to the step 4.
         * 4) If pila is not empty, we do again the process deleting always the top
         *      element of "pila".
         * 
         * We can prove that the loop finishes. If the size of the stack is n and 
         * also is a positive integer, this implies that the stack has a size of n
         * that follows the next rule, 0 <= n.
         * If n = 0 we stop. If not,  we decrement the size of stack in 1 in each
         * loop, so we have a size of n-1. If n-1 = 0 pila is empty, and the algorithm
         * stops, if not, we do again the same process until we have size=0. QED
         * 
         * If "pilaAux2" is empty, implies that the expression is correct.
         * The complexity of this algorithm is O(n). Because we have O(n) (we create
         * the first stack) + O(n) (we check all elements of first stack) + O(1) 
         * (const senteces) = 2*O(n) + O(1) = O(n)
         */
        ArrayStack<char> pilaAux2;
        while(!pila.empty()) { //Checks if "pila" is empty
            
            if(pilaAux2.empty()) { //Checks if "pilaAux2" is empty
                pilaAux2.push(pila.top()); //Adds the top element of "pila" to "pilaAux2"
            }
            else {
                if(topAparellat(pila.top() , pilaAux2.top())) { //Checks if the tops elemets of the stacks are opposite
                    pilaAux2.pop(); //Deletes the last element of "pilaAux2"
                }
                else {
                    pilaAux2.push(pila.top()); //Adds the top element of "pila" to "pilaAux2"
                }
            }
            pila.pop(); //Deletes the top element of "pila"
        }
        if (pilaAux2.empty()) { //Checks if "pilaAux2" is empty to know if the expression is well done or not
            return true;
        } 
        else {
            return false;
        }
    }
    else {
        return true;
    }
}
コード例 #10
0
ファイル: Stacks.cpp プロジェクト: tarungulati1988/code-base
void main(void)
{
    ArrayStack s;
    try{
                if(s.isEmpty()){
                                        cout<<"Stack is empty"<<endl;
                                }
                s.push(200);
                s.push(300);
                cout<<"Size of the stack is: "<<s.size()<<endl;
                cout<<"top is "<<s.Top()<<endl;
                s.pop();
                s.pop();
                cout<<s.isEmpty();
        }
    catch(...){
                cout<<"Some exception occured!!"<<endl;
               }
    getchar();
}
コード例 #11
0
void Sort(ArrayStack<int> &stack) {
    ArrayStack<int> helper;
    while (!stack.empty()) {
        int cur = stack.pop();
        int count = 0;
        while (!helper.empty() && helper.peek() < cur) {
            count++;
            stack.push(helper.pop());
        }
        helper.push(cur);
        while (count--)
            helper.push(stack.pop());
    }

    while (!helper.empty())
        stack.push(helper.pop());
}
コード例 #12
0
ファイル: rationalize.cpp プロジェクト: DrewScoggins/coreclr
Compiler::fgWalkResult Rationalizer::RewriteNode(GenTree** useEdge, ArrayStack<GenTree*>& parentStack)
{
    assert(useEdge != nullptr);

    GenTree* node = *useEdge;
    assert(node != nullptr);

#ifdef DEBUG
    const bool isLateArg = (node->gtFlags & GTF_LATE_ARG) != 0;
#endif

    // First, remove any preceeding list nodes, which are not otherwise visited by the tree walk.
    //
    // NOTE: GT_FIELD_LIST head nodes, and GT_LIST nodes used by phi nodes will in fact be visited.
    for (GenTree* prev = node->gtPrev; prev != nullptr && prev->OperIsAnyList() && !(prev->OperIsFieldListHead());
         prev          = node->gtPrev)
    {
        BlockRange().Remove(prev);
    }

    // In addition, remove the current node if it is a GT_LIST node that is not an aggregate.
    if (node->OperIsAnyList())
    {
        GenTreeArgList* list = node->AsArgList();
        if (!list->OperIsFieldListHead())
        {
            BlockRange().Remove(list);
        }
        return Compiler::WALK_CONTINUE;
    }

    LIR::Use use;
    if (parentStack.Height() < 2)
    {
        use = LIR::Use::GetDummyUse(BlockRange(), *useEdge);
    }
    else
    {
        use = LIR::Use(BlockRange(), useEdge, parentStack.Index(1));
    }

    assert(node == use.Def());
    switch (node->OperGet())
    {
        case GT_ASG:
            RewriteAssignment(use);
            break;

        case GT_BOX:
            // GT_BOX at this level just passes through so get rid of it
            use.ReplaceWith(comp, node->gtGetOp1());
            BlockRange().Remove(node);
            break;

        case GT_ADDR:
            RewriteAddress(use);
            break;

        case GT_IND:
            // Clear the `GTF_IND_ASG_LHS` flag, which overlaps with `GTF_IND_REQ_ADDR_IN_REG`.
            node->gtFlags &= ~GTF_IND_ASG_LHS;

            if (varTypeIsSIMD(node))
            {
                RewriteSIMDOperand(use, false);
            }
            else
            {
                // Due to promotion of structs containing fields of type struct with a
                // single scalar type field, we could potentially see IR nodes of the
                // form GT_IND(GT_ADD(lclvarAddr, 0)) where 0 is an offset representing
                // a field-seq. These get folded here.
                //
                // TODO: This code can be removed once JIT implements recursive struct
                // promotion instead of lying about the type of struct field as the type
                // of its single scalar field.
                GenTree* addr = node->AsIndir()->Addr();
                if (addr->OperGet() == GT_ADD && addr->gtGetOp1()->OperGet() == GT_LCL_VAR_ADDR &&
                    addr->gtGetOp2()->IsIntegralConst(0))
                {
                    GenTreeLclVarCommon* lclVarNode = addr->gtGetOp1()->AsLclVarCommon();
                    unsigned             lclNum     = lclVarNode->GetLclNum();
                    LclVarDsc*           varDsc     = comp->lvaTable + lclNum;
                    if (node->TypeGet() == varDsc->TypeGet())
                    {
                        JITDUMP("Rewriting GT_IND(GT_ADD(LCL_VAR_ADDR,0)) to LCL_VAR\n");
                        lclVarNode->SetOper(GT_LCL_VAR);
                        lclVarNode->gtType = node->TypeGet();
                        use.ReplaceWith(comp, lclVarNode);
                        BlockRange().Remove(addr);
                        BlockRange().Remove(addr->gtGetOp2());
                        BlockRange().Remove(node);
                    }
                }
            }
            break;

        case GT_NOP:
            // fgMorph sometimes inserts NOP nodes between defs and uses
            // supposedly 'to prevent constant folding'. In this case, remove the
            // NOP.
            if (node->gtGetOp1() != nullptr)
            {
                use.ReplaceWith(comp, node->gtGetOp1());
                BlockRange().Remove(node);
            }
            break;

        case GT_COMMA:
        {
            GenTree* op1 = node->gtGetOp1();
            if ((op1->gtFlags & GTF_ALL_EFFECT) == 0)
            {
                // The LHS has no side effects. Remove it.
                bool               isClosed    = false;
                unsigned           sideEffects = 0;
                LIR::ReadOnlyRange lhsRange    = BlockRange().GetTreeRange(op1, &isClosed, &sideEffects);

                // None of the transforms performed herein violate tree order, so these
                // should always be true.
                assert(isClosed);
                assert((sideEffects & GTF_ALL_EFFECT) == 0);

                BlockRange().Delete(comp, m_block, std::move(lhsRange));
            }

            GenTree* replacement = node->gtGetOp2();
            if (!use.IsDummyUse())
            {
                use.ReplaceWith(comp, replacement);
            }
            else
            {
                // This is a top-level comma. If the RHS has no side effects we can remove
                // it as well.
                if ((replacement->gtFlags & GTF_ALL_EFFECT) == 0)
                {
                    bool               isClosed    = false;
                    unsigned           sideEffects = 0;
                    LIR::ReadOnlyRange rhsRange    = BlockRange().GetTreeRange(replacement, &isClosed, &sideEffects);

                    // None of the transforms performed herein violate tree order, so these
                    // should always be true.
                    assert(isClosed);
                    assert((sideEffects & GTF_ALL_EFFECT) == 0);

                    BlockRange().Delete(comp, m_block, std::move(rhsRange));
                }
            }

            BlockRange().Remove(node);
        }
        break;

        case GT_ARGPLACE:
            // Remove argplace and list nodes from the execution order.
            //
            // TODO: remove phi args and phi nodes as well?
            BlockRange().Remove(node);
            break;

#if defined(_TARGET_XARCH_) || defined(_TARGET_ARM_)
        case GT_CLS_VAR:
        {
            // Class vars that are the target of an assignment will get rewritten into
            // GT_STOREIND(GT_CLS_VAR_ADDR, val) by RewriteAssignment. This check is
            // not strictly necessary--the GT_IND(GT_CLS_VAR_ADDR) pattern that would
            // otherwise be generated would also be picked up by RewriteAssignment--but
            // skipping the rewrite here saves an allocation and a bit of extra work.
            const bool isLHSOfAssignment = (use.User()->OperGet() == GT_ASG) && (use.User()->gtGetOp1() == node);
            if (!isLHSOfAssignment)
            {
                GenTree* ind = comp->gtNewOperNode(GT_IND, node->TypeGet(), node);

                node->SetOper(GT_CLS_VAR_ADDR);
                node->gtType = TYP_BYREF;

                BlockRange().InsertAfter(node, ind);
                use.ReplaceWith(comp, ind);

                // TODO: JIT dump
            }
        }
        break;
#endif // _TARGET_XARCH_

        case GT_INTRINSIC:
            // Non-target intrinsics should have already been rewritten back into user calls.
            assert(Compiler::IsTargetIntrinsic(node->gtIntrinsic.gtIntrinsicId));
            break;

#ifdef FEATURE_SIMD
        case GT_BLK:
        case GT_OBJ:
        {
            // TODO-1stClassStructs: These should have been transformed to GT_INDs, but in order
            // to preserve existing behavior, we will keep this as a block node if this is the
            // lhs of a block assignment, and either:
            // - It is a "generic" TYP_STRUCT assignment, OR
            // - It is an initblk, OR
            // - Neither the lhs or rhs are known to be of SIMD type.

            GenTree* parent  = use.User();
            bool     keepBlk = false;
            if ((parent->OperGet() == GT_ASG) && (node == parent->gtGetOp1()))
            {
                if ((node->TypeGet() == TYP_STRUCT) || parent->OperIsInitBlkOp())
                {
                    keepBlk = true;
                }
                else if (!comp->isAddrOfSIMDType(node->AsBlk()->Addr()))
                {
                    GenTree* dataSrc = parent->gtGetOp2();
                    if (!dataSrc->IsLocal() && (dataSrc->OperGet() != GT_SIMD))
                    {
                        noway_assert(dataSrc->OperIsIndir());
                        keepBlk = !comp->isAddrOfSIMDType(dataSrc->AsIndir()->Addr());
                    }
                }
            }
            RewriteSIMDOperand(use, keepBlk);
        }
        break;

        case GT_LCL_FLD:
        case GT_STORE_LCL_FLD:
            // TODO-1stClassStructs: Eliminate this.
            FixupIfSIMDLocal(node->AsLclVarCommon());
            break;

        case GT_SIMD:
        {
            noway_assert(comp->featureSIMD);
            GenTreeSIMD* simdNode = node->AsSIMD();
            unsigned     simdSize = simdNode->gtSIMDSize;
            var_types    simdType = comp->getSIMDTypeForSize(simdSize);

            // TODO-1stClassStructs: This should be handled more generally for enregistered or promoted
            // structs that are passed or returned in a different register type than their enregistered
            // type(s).
            if (simdNode->gtType == TYP_I_IMPL && simdNode->gtSIMDSize == TARGET_POINTER_SIZE)
            {
                // This happens when it is consumed by a GT_RET_EXPR.
                // It can only be a Vector2f or Vector2i.
                assert(genTypeSize(simdNode->gtSIMDBaseType) == 4);
                simdNode->gtType = TYP_SIMD8;
            }
            // Certain SIMD trees require rationalizing.
            if (simdNode->gtSIMD.gtSIMDIntrinsicID == SIMDIntrinsicInitArray)
            {
                // Rewrite this as an explicit load.
                JITDUMP("Rewriting GT_SIMD array init as an explicit load:\n");
                unsigned int baseTypeSize = genTypeSize(simdNode->gtSIMDBaseType);
                GenTree*     address = new (comp, GT_LEA) GenTreeAddrMode(TYP_BYREF, simdNode->gtOp1, simdNode->gtOp2,
                                                                      baseTypeSize, offsetof(CORINFO_Array, u1Elems));
                GenTree* ind = comp->gtNewOperNode(GT_IND, simdType, address);

                BlockRange().InsertBefore(simdNode, address, ind);
                use.ReplaceWith(comp, ind);
                BlockRange().Remove(simdNode);

                DISPTREERANGE(BlockRange(), use.Def());
                JITDUMP("\n");
            }
            else
            {
                // This code depends on the fact that NONE of the SIMD intrinsics take vector operands
                // of a different width.  If that assumption changes, we will EITHER have to make these type
                // transformations during importation, and plumb the types all the way through the JIT,
                // OR add a lot of special handling here.
                GenTree* op1 = simdNode->gtGetOp1();
                if (op1 != nullptr && op1->gtType == TYP_STRUCT)
                {
                    op1->gtType = simdType;
                }

                GenTree* op2 = simdNode->gtGetOp2IfPresent();
                if (op2 != nullptr && op2->gtType == TYP_STRUCT)
                {
                    op2->gtType = simdType;
                }
            }
        }
        break;
#endif // FEATURE_SIMD

        default:
            // JCC nodes should not be present in HIR.
            assert(node->OperGet() != GT_JCC);
            break;
    }

    // Do some extra processing on top-level nodes to remove unused local reads.
    if (node->OperIsLocalRead())
    {
        if (use.IsDummyUse())
        {
            comp->lvaDecRefCnts(node);
            BlockRange().Remove(node);
        }
        else
        {
            // Local reads are side-effect-free; clear any flags leftover from frontend transformations.
            node->gtFlags &= ~GTF_ALL_EFFECT;
        }
    }

    assert(isLateArg == ((use.Def()->gtFlags & GTF_LATE_ARG) != 0));

    return Compiler::WALK_CONTINUE;
}
コード例 #13
0
ファイル: stack.cpp プロジェクト: kernelbandwidth/DSA_Cpp
int main() {
  ArrayStack<int> s;
  s.push(10);
  cout << s.peek() << endl;
  return 0;
}
コード例 #14
0
ファイル: rationalize.cpp プロジェクト: bretambrose/coreclr
Compiler::fgWalkResult Rationalizer::RewriteNode(GenTree** useEdge, ArrayStack<GenTree*>& parentStack)
{
    assert(useEdge != nullptr);

    GenTree* node = *useEdge;
    assert(node != nullptr);

#ifdef DEBUG
    const bool isLateArg = (node->gtFlags & GTF_LATE_ARG) != 0;
#endif

    // First, remove any preceeding GT_LIST nodes, which are not otherwise visited by the tree walk.
    //
    // NOTE: GT_LIST nodes that are used by block ops and phi nodes will in fact be visited.
    for (GenTree* prev = node->gtPrev; prev != nullptr && prev->OperGet() == GT_LIST; prev = node->gtPrev)
    {
        BlockRange().Remove(prev);
    }

    // In addition, remove the current node if it is a GT_LIST node.
    if ((*useEdge)->OperGet() == GT_LIST)
    {
        BlockRange().Remove(*useEdge);
        return Compiler::WALK_CONTINUE;
    }

    LIR::Use use;
    if (parentStack.Height() < 2)
    {
        use = LIR::Use::GetDummyUse(BlockRange(), *useEdge);
    }
    else
    {
        use = LIR::Use(BlockRange(), useEdge, parentStack.Index(1));
    }

    assert(node == use.Def());
    switch (node->OperGet())
    {
        case GT_ASG:
            RewriteAssignment(use);
            break;

        case GT_BOX:
            // GT_BOX at this level just passes through so get rid of it
            use.ReplaceWith(comp, node->gtGetOp1());
            BlockRange().Remove(node);
            break;

        case GT_ADDR:
            RewriteAddress(use);
            break;

        case GT_NOP:
            // fgMorph sometimes inserts NOP nodes between defs and uses
            // supposedly 'to prevent constant folding'. In this case, remove the
            // NOP.
            if (node->gtGetOp1() != nullptr)
            {
                use.ReplaceWith(comp, node->gtGetOp1());
                BlockRange().Remove(node);
            }
            break;

        case GT_COMMA:
        {
            GenTree* op1 = node->gtGetOp1();
            if ((op1->gtFlags & GTF_ALL_EFFECT) == 0)
            {
                // The LHS has no side effects. Remove it.
                bool               isClosed    = false;
                unsigned           sideEffects = 0;
                LIR::ReadOnlyRange lhsRange    = BlockRange().GetTreeRange(op1, &isClosed, &sideEffects);

                // None of the transforms performed herein violate tree order, so these
                // should always be true.
                assert(isClosed);
                assert((sideEffects & GTF_ALL_EFFECT) == 0);

                BlockRange().Delete(comp, m_block, std::move(lhsRange));
            }

            GenTree* replacement = node->gtGetOp2();
            if (!use.IsDummyUse())
            {
                use.ReplaceWith(comp, replacement);
            }
            else
            {
                // This is a top-level comma. If the RHS has no side effects we can remove
                // it as well.
                if ((replacement->gtFlags & GTF_ALL_EFFECT) == 0)
                {
                    bool               isClosed    = false;
                    unsigned           sideEffects = 0;
                    LIR::ReadOnlyRange rhsRange    = BlockRange().GetTreeRange(replacement, &isClosed, &sideEffects);

                    // None of the transforms performed herein violate tree order, so these
                    // should always be true.
                    assert(isClosed);
                    assert((sideEffects & GTF_ALL_EFFECT) == 0);

                    BlockRange().Delete(comp, m_block, std::move(rhsRange));
                }
            }

            BlockRange().Remove(node);
        }
        break;

        case GT_ARGPLACE:
            // Remove argplace and list nodes from the execution order.
            //
            // TODO: remove phi args and phi nodes as well?
            BlockRange().Remove(node);
            break;

#ifdef _TARGET_XARCH_
        case GT_CLS_VAR:
        {
            // Class vars that are the target of an assignment will get rewritten into
            // GT_STOREIND(GT_CLS_VAR_ADDR, val) by RewriteAssignment. This check is
            // not strictly necessary--the GT_IND(GT_CLS_VAR_ADDR) pattern that would
            // otherwise be generated would also be picked up by RewriteAssignment--but
            // skipping the rewrite here saves an allocation and a bit of extra work.
            const bool isLHSOfAssignment = (use.User()->OperGet() == GT_ASG) && (use.User()->gtGetOp1() == node);
            if (!isLHSOfAssignment)
            {
                GenTree* ind = comp->gtNewOperNode(GT_IND, node->TypeGet(), node);

                node->SetOper(GT_CLS_VAR_ADDR);
                node->gtType = TYP_BYREF;

                BlockRange().InsertAfter(node, ind);
                use.ReplaceWith(comp, ind);

                // TODO: JIT dump
            }
        }
        break;
#endif // _TARGET_XARCH_

        case GT_INTRINSIC:
            // Non-target intrinsics should have already been rewritten back into user calls.
            assert(Compiler::IsTargetIntrinsic(node->gtIntrinsic.gtIntrinsicId));
            break;

#ifdef FEATURE_SIMD
        case GT_INITBLK:
            RewriteInitBlk(use);
            break;

        case GT_COPYBLK:
            RewriteCopyBlk(use);
            break;

        case GT_OBJ:
            RewriteObj(use);
            break;

        case GT_LCL_FLD:
        case GT_STORE_LCL_FLD:
            // TODO-1stClassStructs: Eliminate this.
            FixupIfSIMDLocal(node->AsLclVarCommon());
            break;

        case GT_STOREIND:
        case GT_IND:
            if (node->gtType == TYP_STRUCT)
            {
                GenTree* addr = node->AsIndir()->Addr();
                assert(addr->TypeGet() == TYP_BYREF);

                if (addr->OperIsLocal())
                {
                    LclVarDsc* varDsc = &(comp->lvaTable[addr->AsLclVarCommon()->gtLclNum]);
                    assert(varDsc->lvSIMDType);
                    unsigned simdSize = (unsigned int)roundUp(varDsc->lvExactSize, TARGET_POINTER_SIZE);
                    node->gtType      = comp->getSIMDTypeForSize(simdSize);
                }
#if DEBUG
                else
                {
                    // If the address is not a local var, assert that the user of this IND is an ADDR node.
                    assert((use.User()->OperGet() == GT_ADDR) || use.User()->OperIsLocalAddr());
                }
#endif
            }
            break;

        case GT_SIMD:
        {
            noway_assert(comp->featureSIMD);
            GenTreeSIMD* simdNode = node->AsSIMD();
            unsigned     simdSize = simdNode->gtSIMDSize;
            var_types    simdType = comp->getSIMDTypeForSize(simdSize);

            // TODO-1stClassStructs: This should be handled more generally for enregistered or promoted
            // structs that are passed or returned in a different register type than their enregistered
            // type(s).
            if (simdNode->gtType == TYP_I_IMPL && simdNode->gtSIMDSize == TARGET_POINTER_SIZE)
            {
                // This happens when it is consumed by a GT_RET_EXPR.
                // It can only be a Vector2f or Vector2i.
                assert(genTypeSize(simdNode->gtSIMDBaseType) == 4);
                simdNode->gtType = TYP_SIMD8;
            }
            else if (simdNode->gtType == TYP_STRUCT || varTypeIsSIMD(simdNode))
            {
                node->gtType = simdType;
            }

            // Certain SIMD trees require rationalizing.
            if (simdNode->gtSIMD.gtSIMDIntrinsicID == SIMDIntrinsicInitArray)
            {
                // Rewrite this as an explicit load.
                JITDUMP("Rewriting GT_SIMD array init as an explicit load:\n");
                unsigned int baseTypeSize = genTypeSize(simdNode->gtSIMDBaseType);
                GenTree*     address = new (comp, GT_LEA) GenTreeAddrMode(TYP_BYREF, simdNode->gtOp1, simdNode->gtOp2,
                                                                      baseTypeSize, offsetof(CORINFO_Array, u1Elems));
                GenTree* ind = comp->gtNewOperNode(GT_IND, simdType, address);

                BlockRange().InsertBefore(simdNode, address, ind);
                use.ReplaceWith(comp, ind);
                BlockRange().Remove(simdNode);

                DISPTREERANGE(BlockRange(), use.Def());
                JITDUMP("\n");
            }
            else
            {
                // This code depends on the fact that NONE of the SIMD intrinsics take vector operands
                // of a different width.  If that assumption changes, we will EITHER have to make these type
                // transformations during importation, and plumb the types all the way through the JIT,
                // OR add a lot of special handling here.
                GenTree* op1 = simdNode->gtGetOp1();
                if (op1 != nullptr && op1->gtType == TYP_STRUCT)
                {
                    op1->gtType = simdType;
                }

                GenTree* op2 = simdNode->gtGetOp2();
                if (op2 != nullptr && op2->gtType == TYP_STRUCT)
                {
                    op2->gtType = simdType;
                }
            }
        }
        break;
#endif // FEATURE_SIMD

        default:
            break;
    }

    // Do some extra processing on top-level nodes to remove unused local reads.
    if (use.IsDummyUse() && node->OperIsLocalRead())
    {
        assert((node->gtFlags & GTF_ALL_EFFECT) == 0);

        comp->lvaDecRefCnts(node);
        BlockRange().Remove(node);
    }

    assert(isLateArg == ((node->gtFlags & GTF_LATE_ARG) != 0));

    return Compiler::WALK_CONTINUE;
}
コード例 #15
0
ファイル: StacksImp.cpp プロジェクト: fullarray/C_Plus_Plus
int main(){
	ArrayStack s;
	try{
		if(s.isEmpty()){
			cout << "Stack is empty"<< endl;
		}
		
		s.Push(349);
		s.Push(49);
		s.Push(679);
		
		// Print size of stack
		cout << "Size of stack = " << s.Size() << endl;
		
		// Print top element in stack
		cout << "Top Element " << s.Top() << endl;
		
		// Print popped element from stack
		cout << "Element " << s.Pop() << " popped." << endl;
		
		// Print popped element from stack
		cout << "Element " << s.Pop() << " popped." << endl;
		
		// Print popped element from stack
		cout << "Element " << s.Pop() << " popped." << endl;
		
		// Print popped element from stack
		cout << "Element " << s.Pop() << " popped." << endl;
	}catch(...)
		cout << "Some exception occured." << endl;
	}
	
}
コード例 #16
0
void Display::ShowDataStructItems()
{
	ArrayStack<int> dsArrayStack;
	ListStack<int>	lsListStack;
	ArrayQueue<int> aqArrayQueue;
	CycleDoublyLinkList<int> dcllCycleDoublyLinkList;
	BinarySearchTree<int> bstBinarySearchTree;
	RedBlackTree<int> rbtRedBlackTree;
	MergeFindSet<int> mfsMergeFindSet;
	HashTable<int> htHashTable;
	cout<<WELCOME_STRING<<endl;
	cout<<"This is the Implement of Data Structs"<<endl;
	cout<<"Please Select the Item you are Interest in:"<<endl;
	cout<<"1.	Stack(Implement of Array);"<<endl;
	cout<<"2.	Stack(Implement of List);"<<endl;
	cout<<"3.	Queue(Implement of Array);"<<endl;
	cout<<"4.	Cycle Doubly Linked List"<<endl;
	cout<<"5.	Binary Search Tree"<<endl;
	cout<<"6.	Red Black Tree"<<endl;
	cout<<"7.	Merge Find Set"<<endl;
	cout<<"8.	Hash Table"<<endl;
	cout<<"98.	Up Layer;"<<endl;
	cout<<"99.	Quit."<<endl;
	cout<<STAR_STRING<<endl;
	cout<<endl;
	int nSelect;
	while(1)
	{
		cin>>nSelect;
		if(cin.fail())
		{
			ClearScreen();
			cout<<"Input Error! Please Select Again!"<<endl;
			cin.clear();
			cin.sync();
			ShowDataStructItems();
		}
		ClearScreen();
		switch(nSelect)
		{
		case 1:
			cout<<dsArrayStack.GetTitle().c_str()<<endl;
			dsArrayStack.Description();
			dsArrayStack.Test();
			ShowDataStructItems();
			break;
		case 2:
			cout<<lsListStack.GetTitle().c_str()<<endl;
			lsListStack.Description();
			lsListStack.Test();
			ShowDataStructItems();
			break;
		case 3:
			cout<<aqArrayQueue.GetTitle().c_str()<<endl;
			aqArrayQueue.Description();
			aqArrayQueue.Test();
			ShowDataStructItems();
			break;
		case 4:
			cout<<dcllCycleDoublyLinkList.GetTitle().c_str()<<endl;
			dcllCycleDoublyLinkList.Description();
			dcllCycleDoublyLinkList.Test();
			ShowDataStructItems();
			break;
		case 5:
			cout<<bstBinarySearchTree.GetTitle().c_str()<<endl;
			bstBinarySearchTree.Description();
			bstBinarySearchTree.Test();
			ShowDataStructItems();
			break;
		case 6:
			cout<<rbtRedBlackTree.GetTitle().c_str()<<endl;
			rbtRedBlackTree.Description();
			rbtRedBlackTree.Test();
			ShowDataStructItems();
			break;
		case 7:
			cout<<mfsMergeFindSet.GetTitle().c_str()<<endl;
			mfsMergeFindSet.Description();
			mfsMergeFindSet.Test();
			ShowDataStructItems();
			break;
		case 8:
			cout<<htHashTable.GetTitle().c_str()<<endl;
			htHashTable.Description();
			htHashTable.Test();
			ShowDataStructItems();
			break;
		case 98:
			goto ShowWelcome;
			break;
		case 99:
			exit(0);
			break;
		default:
			ClearScreen();
			cout<<"Select Error! Please Select Again!"<<endl;
			cin.clear();
			cin.sync();
			ShowDataStructItems();
			break;
		}
	}
ShowWelcome:
	Show();
	return;
}
コード例 #17
0
void main() {

	ArrayStack myArrayStack;

	myArrayStack.isEmpty();

	myArrayStack.Push(45);
	myArrayStack.Push(4);
	myArrayStack.Push(34);
	myArrayStack.Push(99);
	myArrayStack.Push(1200);
	//myArrayStack.Push(771);		//causes stack overflow

	myArrayStack.isEmpty();
	cout << myArrayStack.Size() << endl;

	cout << "\nTop element: " << myArrayStack.Top() << endl;

	cout << "\nRemoving top element: " << myArrayStack.Pop() << endl;

	cout << "\nCurrent top element: " << myArrayStack.Top() << endl;

	cout << myArrayStack.Size() << endl;


	getchar();

}