<commit_before>//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements a simple loop unroller.  It works best when loops have
// been canonicalized by the -indvars pass, allowing it to determine the trip
// counts of loops easily.
//
// This pass is currently extremely limited.  It only currently only unrolls
// single basic block loops that execute a constant number of times.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "loop-unroll"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
#include "Support/STLExtras.h"
#include <cstdio>
#include <set>
using namespace llvm;

namespace {
  Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");

  cl::opt<unsigned>
  UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
                  cl::desc("The cut-off point for loop unrolling"));

  class LoopUnroll : public FunctionPass {
    LoopInfo *LI;  // The current loop information
  public:
    virtual bool runOnFunction(Function &F);
    bool visitLoop(Loop *L);

    /// This transformation requires natural loop information & requires that
    /// loop preheaders be inserted into the CFG...
    ///
    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.addRequiredID(LoopSimplifyID);
      AU.addRequired<LoopInfo>();
      AU.addPreserved<LoopInfo>();
    }
  };
  RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
}

FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }

bool LoopUnroll::runOnFunction(Function &F) {
  bool Changed = false;
  LI = &getAnalysis<LoopInfo>();

  // Transform all the top-level loops.  Copy the loop list so that the child
  // can update the loop tree if it needs to delete the loop.
  std::vector<Loop*> SubLoops(LI->begin(), LI->end());
  for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
    Changed |= visitLoop(SubLoops[i]);

  return Changed;
}

/// ApproximateLoopSize - Approximate the size of the loop after it has been
/// unrolled.
static unsigned ApproximateLoopSize(const Loop *L) {
  unsigned Size = 0;
  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
    BasicBlock *BB = L->getBlocks()[i];
    Instruction *Term = BB->getTerminator();
    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
      if (isa<PHINode>(I) && BB == L->getHeader()) {
        // Ignore PHI nodes in the header.
      } else if (I->hasOneUse() && I->use_back() == Term) {
        // Ignore instructions only used by the loop terminator.
      } else {
        ++Size;
      }

      // TODO: Ignore expressions derived from PHI and constants if inval of phi
      // is a constant, or if operation is associative.  This will get induction
      // variables.
    }
  }

  return Size;
}

// RemapInstruction - Convert the instruction operands from referencing the
// current values into those specified by ValueMap.
//
static inline void RemapInstruction(Instruction *I,
                                    std::map<const Value *, Value*> &ValueMap) {
  for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
    Value *Op = I->getOperand(op);
    std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
    if (It != ValueMap.end()) Op = It->second;
    I->setOperand(op, Op);
  }
}

bool LoopUnroll::visitLoop(Loop *L) {
  bool Changed = false;

  // Recurse through all subloops before we process this loop.  Copy the loop
  // list so that the child can update the loop tree if it needs to delete the
  // loop.
  std::vector<Loop*> SubLoops(L->begin(), L->end());
  for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
    Changed |= visitLoop(SubLoops[i]);

  // We only handle single basic block loops right now.
  if (L->getBlocks().size() != 1)
    return Changed;

  BasicBlock *BB = L->getHeader();
  BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  if (BI == 0) return Changed;  // Must end in a conditional branch

  ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
  if (!TripCountC) return Changed;  // Must have constant trip count!

  unsigned TripCount = TripCountC->getRawValue();
  if (TripCount != TripCountC->getRawValue())
    return Changed; // More than 2^32 iterations???

  unsigned LoopSize = ApproximateLoopSize(L);
  DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
        << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
        << " Trip Count = " << TripCount << " - ");
  if (LoopSize*TripCount > UnrollThreshold) {
    DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
                    << UnrollThreshold << "\n");
    return Changed;
  }
  DEBUG(std::cerr << "UNROLLING!\n");

  BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));

  // Create a new basic block to temporarily hold all of the cloned code.
  BasicBlock *NewBlock = new BasicBlock();

  // For the first iteration of the loop, we should use the precloned values for
  // PHI nodes.  Insert associations now.
  std::map<const Value*, Value*> LastValueMap;
  std::vector<PHINode*> OrigPHINode;
  for (BasicBlock::iterator I = BB->begin();
       PHINode *PN = dyn_cast<PHINode>(I); ++I) {
    OrigPHINode.push_back(PN);
    if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
      if (I->getParent() == BB)
        LastValueMap[I] = I;
  }

  // Remove the exit branch from the loop
  BB->getInstList().erase(BI);

  assert(TripCount != 0 && "Trip count of 0 is impossible!");
  for (unsigned It = 1; It != TripCount; ++It) {
    char SuffixBuffer[100];
    sprintf(SuffixBuffer, ".%d", It);
    std::map<const Value*, Value*> ValueMap;
    BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);

    // Loop over all of the PHI nodes in the block, changing them to use the
    // incoming values from the previous block.
    for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
      PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
      Value *InVal = NewPHI->getIncomingValueForBlock(BB);
      if (Instruction *InValI = dyn_cast<Instruction>(InVal))
        if (InValI->getParent() == BB)
          InVal = LastValueMap[InValI];
      ValueMap[OrigPHINode[i]] = InVal;
      New->getInstList().erase(NewPHI);
    }

    for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
      RemapInstruction(I, ValueMap);

    // Now that all of the instructions are remapped, splice them into the end
    // of the NewBlock.
    NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
    delete New;

    // LastValue map now contains values from this iteration.
    std::swap(LastValueMap, ValueMap);
  }

  // If there was more than one iteration, replace any uses of values computed
  // in the loop with values computed during the last iteration of the loop.
  if (TripCount != 1) {
    std::set<User*> Users;
    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
      Users.insert(I->use_begin(), I->use_end());

    // We don't want to reprocess entries with PHI nodes in them.  For this
    // reason, we look at each operand of each user exactly once, performing the
    // stubstitution exactly once.
    for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
         ++UI) {
      Instruction *I = cast<Instruction>(*UI);
      if (I->getParent() != BB && I->getParent() != NewBlock)
        RemapInstruction(I, LastValueMap);
    }
  }

  // Now that we cloned the block as many times as we needed, stitch the new
  // code into the original block and delete the temporary block.
  BB->getInstList().splice(BB->end(), NewBlock->getInstList());
  delete NewBlock;

  // Now loop over the PHI nodes in the original block, setting them to their
  // incoming values.
  BasicBlock *Preheader = L->getLoopPreheader();
  for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
    PHINode *PN = OrigPHINode[i];
    PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
    BB->getInstList().erase(PN);
  }

  // Finally, add an unconditional branch to the block to continue into the exit
  // block.
  new BranchInst(LoopExit, BB);

  // At this point, the code is well formed.  We now do a quick sweep over the
  // inserted code, doing constant propagation and dead code elimination as we
  // go.
  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
    Instruction *Inst = I++;

    if (isInstructionTriviallyDead(Inst))
      BB->getInstList().erase(Inst);
    else if (Constant *C = ConstantFoldInstruction(Inst)) {
      Inst->replaceAllUsesWith(C);
      BB->getInstList().erase(Inst);
    }
  }

  // Update the loop information for this loop.
  Loop *Parent = L->getParentLoop();

  // Move all of the basic blocks in the loop into the parent loop.
  LI->changeLoopFor(BB, Parent);

  // Remove the loop from the parent.
  if (Parent)
    delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
  else
    delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));

  // FIXME: Should update dominator analyses

  // Now that everything is up-to-date that will be, we fold the loop block into
  // the preheader and exit block, updating our analyses as we go.
  LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
                                 BB->getInstList().begin(),
                                 prior(BB->getInstList().end()));
  LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
                                 Preheader->getInstList().begin(),
                                 prior(Preheader->getInstList().end()));

  // Make all other blocks in the program branch to LoopExit now instead of
  // Preheader.
  Preheader->replaceAllUsesWith(LoopExit);

  // Remove BB and LoopExit from our analyses.
  LI->removeBlock(Preheader);
  LI->removeBlock(BB);

  // If the preheader was the entry block of this function, move the exit block
  // to be the new entry of the loop.
  Function *F = LoopExit->getParent();
  if (Preheader == &F->front())
    F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit);

  // Actually delete the blocks now.
  F->getBasicBlockList().erase(Preheader);
  F->getBasicBlockList().erase(BB);

  ++NumUnrolled;
  return true;
}
<commit_msg>Fix PR325<commit_after>//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements a simple loop unroller.  It works best when loops have
// been canonicalized by the -indvars pass, allowing it to determine the trip
// counts of loops easily.
//
// This pass is currently extremely limited.  It only currently only unrolls
// single basic block loops that execute a constant number of times.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "loop-unroll"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Local.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
#include "Support/STLExtras.h"
#include <cstdio>
#include <set>
using namespace llvm;

namespace {
  Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");

  cl::opt<unsigned>
  UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
                  cl::desc("The cut-off point for loop unrolling"));

  class LoopUnroll : public FunctionPass {
    LoopInfo *LI;  // The current loop information
  public:
    virtual bool runOnFunction(Function &F);
    bool visitLoop(Loop *L);

    /// This transformation requires natural loop information & requires that
    /// loop preheaders be inserted into the CFG...
    ///
    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.addRequiredID(LoopSimplifyID);
      AU.addRequired<LoopInfo>();
      AU.addPreserved<LoopInfo>();
    }
  };
  RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
}

FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }

bool LoopUnroll::runOnFunction(Function &F) {
  bool Changed = false;
  LI = &getAnalysis<LoopInfo>();

  // Transform all the top-level loops.  Copy the loop list so that the child
  // can update the loop tree if it needs to delete the loop.
  std::vector<Loop*> SubLoops(LI->begin(), LI->end());
  for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
    Changed |= visitLoop(SubLoops[i]);

  return Changed;
}

/// ApproximateLoopSize - Approximate the size of the loop after it has been
/// unrolled.
static unsigned ApproximateLoopSize(const Loop *L) {
  unsigned Size = 0;
  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
    BasicBlock *BB = L->getBlocks()[i];
    Instruction *Term = BB->getTerminator();
    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
      if (isa<PHINode>(I) && BB == L->getHeader()) {
        // Ignore PHI nodes in the header.
      } else if (I->hasOneUse() && I->use_back() == Term) {
        // Ignore instructions only used by the loop terminator.
      } else {
        ++Size;
      }

      // TODO: Ignore expressions derived from PHI and constants if inval of phi
      // is a constant, or if operation is associative.  This will get induction
      // variables.
    }
  }

  return Size;
}

// RemapInstruction - Convert the instruction operands from referencing the
// current values into those specified by ValueMap.
//
static inline void RemapInstruction(Instruction *I,
                                    std::map<const Value *, Value*> &ValueMap) {
  for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
    Value *Op = I->getOperand(op);
    std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
    if (It != ValueMap.end()) Op = It->second;
    I->setOperand(op, Op);
  }
}

bool LoopUnroll::visitLoop(Loop *L) {
  bool Changed = false;

  // Recurse through all subloops before we process this loop.  Copy the loop
  // list so that the child can update the loop tree if it needs to delete the
  // loop.
  std::vector<Loop*> SubLoops(L->begin(), L->end());
  for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
    Changed |= visitLoop(SubLoops[i]);

  // We only handle single basic block loops right now.
  if (L->getBlocks().size() != 1)
    return Changed;

  BasicBlock *BB = L->getHeader();
  BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  if (BI == 0) return Changed;  // Must end in a conditional branch

  ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
  if (!TripCountC) return Changed;  // Must have constant trip count!

  unsigned TripCount = TripCountC->getRawValue();
  if (TripCount != TripCountC->getRawValue() || TripCount == 0)
    return Changed; // More than 2^32 iterations???

  unsigned LoopSize = ApproximateLoopSize(L);
  DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
        << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
        << " Trip Count = " << TripCount << " - ");
  if (LoopSize*TripCount > UnrollThreshold) {
    DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
                    << UnrollThreshold << "\n");
    return Changed;
  }
  DEBUG(std::cerr << "UNROLLING!\n");

  BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));

  // Create a new basic block to temporarily hold all of the cloned code.
  BasicBlock *NewBlock = new BasicBlock();

  // For the first iteration of the loop, we should use the precloned values for
  // PHI nodes.  Insert associations now.
  std::map<const Value*, Value*> LastValueMap;
  std::vector<PHINode*> OrigPHINode;
  for (BasicBlock::iterator I = BB->begin();
       PHINode *PN = dyn_cast<PHINode>(I); ++I) {
    OrigPHINode.push_back(PN);
    if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
      if (I->getParent() == BB)
        LastValueMap[I] = I;
  }

  // Remove the exit branch from the loop
  BB->getInstList().erase(BI);

  assert(TripCount != 0 && "Trip count of 0 is impossible!");
  for (unsigned It = 1; It != TripCount; ++It) {
    char SuffixBuffer[100];
    sprintf(SuffixBuffer, ".%d", It);
    std::map<const Value*, Value*> ValueMap;
    BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);

    // Loop over all of the PHI nodes in the block, changing them to use the
    // incoming values from the previous block.
    for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
      PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
      Value *InVal = NewPHI->getIncomingValueForBlock(BB);
      if (Instruction *InValI = dyn_cast<Instruction>(InVal))
        if (InValI->getParent() == BB)
          InVal = LastValueMap[InValI];
      ValueMap[OrigPHINode[i]] = InVal;
      New->getInstList().erase(NewPHI);
    }

    for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
      RemapInstruction(I, ValueMap);

    // Now that all of the instructions are remapped, splice them into the end
    // of the NewBlock.
    NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
    delete New;

    // LastValue map now contains values from this iteration.
    std::swap(LastValueMap, ValueMap);
  }

  // If there was more than one iteration, replace any uses of values computed
  // in the loop with values computed during the last iteration of the loop.
  if (TripCount != 1) {
    std::set<User*> Users;
    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
      Users.insert(I->use_begin(), I->use_end());

    // We don't want to reprocess entries with PHI nodes in them.  For this
    // reason, we look at each operand of each user exactly once, performing the
    // stubstitution exactly once.
    for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
         ++UI) {
      Instruction *I = cast<Instruction>(*UI);
      if (I->getParent() != BB && I->getParent() != NewBlock)
        RemapInstruction(I, LastValueMap);
    }
  }

  // Now that we cloned the block as many times as we needed, stitch the new
  // code into the original block and delete the temporary block.
  BB->getInstList().splice(BB->end(), NewBlock->getInstList());
  delete NewBlock;

  // Now loop over the PHI nodes in the original block, setting them to their
  // incoming values.
  BasicBlock *Preheader = L->getLoopPreheader();
  for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
    PHINode *PN = OrigPHINode[i];
    PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
    BB->getInstList().erase(PN);
  }

  // Finally, add an unconditional branch to the block to continue into the exit
  // block.
  new BranchInst(LoopExit, BB);

  // At this point, the code is well formed.  We now do a quick sweep over the
  // inserted code, doing constant propagation and dead code elimination as we
  // go.
  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
    Instruction *Inst = I++;

    if (isInstructionTriviallyDead(Inst))
      BB->getInstList().erase(Inst);
    else if (Constant *C = ConstantFoldInstruction(Inst)) {
      Inst->replaceAllUsesWith(C);
      BB->getInstList().erase(Inst);
    }
  }

  // Update the loop information for this loop.
  Loop *Parent = L->getParentLoop();

  // Move all of the basic blocks in the loop into the parent loop.
  LI->changeLoopFor(BB, Parent);

  // Remove the loop from the parent.
  if (Parent)
    delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
  else
    delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));

  // FIXME: Should update dominator analyses

  // Now that everything is up-to-date that will be, we fold the loop block into
  // the preheader and exit block, updating our analyses as we go.
  LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
                                 BB->getInstList().begin(),
                                 prior(BB->getInstList().end()));
  LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
                                 Preheader->getInstList().begin(),
                                 prior(Preheader->getInstList().end()));

  // Make all other blocks in the program branch to LoopExit now instead of
  // Preheader.
  Preheader->replaceAllUsesWith(LoopExit);

  // Remove BB and LoopExit from our analyses.
  LI->removeBlock(Preheader);
  LI->removeBlock(BB);

  // If the preheader was the entry block of this function, move the exit block
  // to be the new entry of the loop.
  Function *F = LoopExit->getParent();
  if (Preheader == &F->front())
    F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit);

  // Actually delete the blocks now.
  F->getBasicBlockList().erase(Preheader);
  F->getBasicBlockList().erase(BB);

  ++NumUnrolled;
  return true;
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2002 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <iostream>
#include <fstream>
#include "OggAudioFile.h"

OggAudioFile::OggAudioFile(std::istream* in) : AudioFile(in)
{
	stream = -1;

	ov_callbacks cb;
	cb.read_func = OAFRead;
	cb.seek_func = OAFSeek;
	cb.close_func = OAFClose;
	cb.tell_func = OAFTell;

	OAFInputBundle* bundle = new OAFInputBundle;
	in->seekg(0, ios::end);
	bundle->input = in; bundle->length = std::streamoff(in->tellg());
	in->seekg(0, ios::beg);

	if(ov_open_callbacks(bundle, &file, NULL, 0, cb) < 0) {
		std::cout << "OggAudioFile() failed: call to ov_open_callbacks failed\n";
	}
	else {
		info = ov_info(&file, -1);
		int samples = ov_pcm_total(&file, -1);
		std::cout << ov_streams(&file) << " logical bitstreams\n";
		init(info->rate, info->channels, samples, 2);
	}
}

OggAudioFile::~OggAudioFile()
{
	ov_clear(&file);
}

std::string	OggAudioFile::getExtension()
{
	return ".ogg";
}

bool		OggAudioFile::read(void* buffer, int numFrames)
{
	int frames;
	int bytes = numFrames * info->channels * 2;
	ogg_int64_t oldoff = ov_pcm_tell(&file);
#if BYTE_ORDER == BIG_ENDIAN
	frames = ov_read(&file, (char *) buffer, bytes, 1, 2, 1, &stream);
#else
	frames = ov_read(&file, (char *) buffer, bytes, 0, 2, 1, &stream);
#endif
	ogg_int64_t pcmoff = ov_pcm_tell(&file);
	std::cout << "requested: " << numFrames << endl;
	std::cout << "actual:    " << pcmoff  - oldoff << endl << endl;
	if (frames < 0) {
		if (frames == OV_HOLE)
			// OV_HOLE is non-fatal
			return true;
		else
			return false;
	}
	return true;
}

size_t	OAFRead(void* ptr, size_t size, size_t nmemb, void* datasource)
{
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	std::streamoff pos1 = std::streamoff(bundle->input->tellg());
	std::streamsize read = size * nmemb;

	if (pos1 + read > bundle->length) {
		read = bundle->length - pos1;
	}
	if (pos1 == bundle->length)
		// EOF
		return 0;
	bundle->input->read((char*) ptr, read);

	return read;
}

int		OAFSeek(void* datasource, ogg_int64_t offset, int whence)
{
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	switch (whence) {
		case SEEK_SET:
			bundle->input->seekg(offset, std::ios::beg);
			break;
		case SEEK_CUR:
			bundle->input->seekg(offset, std::ios::cur);
			break;
		case SEEK_END:
			bundle->input->seekg(offset, std::ios::end);
			break;
	}
	return 0;
}

int		OAFClose(void* datasource)
{
	// technically we should close here, but this is handled outside
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	delete bundle;
	return 0;
}

long		OAFTell(void* datasource)
{
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	return bundle->input->tellg();
}
// ex: shiftwidth=4 tabstop=4
<commit_msg>fix for vc++<commit_after>/* bzflag
 * Copyright (c) 1993 - 2002 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <iostream>
#include <fstream>
#include "OggAudioFile.h"

OggAudioFile::OggAudioFile(std::istream* in) : AudioFile(in)
{
	stream = -1;

	ov_callbacks cb;
	cb.read_func = OAFRead;
	cb.seek_func = OAFSeek;
	cb.close_func = OAFClose;
	cb.tell_func = OAFTell;

	OAFInputBundle* bundle = new OAFInputBundle;
	in->seekg(0, std::ios::end);
	bundle->input = in; bundle->length = std::streamoff(in->tellg());
	in->seekg(0, std::ios::beg);

	if(ov_open_callbacks(bundle, &file, NULL, 0, cb) < 0) {
		std::cout << "OggAudioFile() failed: call to ov_open_callbacks failed\n";
	}
	else {
		info = ov_info(&file, -1);
		int samples = ov_pcm_total(&file, -1);
		std::cout << ov_streams(&file) << " logical bitstreams\n";
		init(info->rate, info->channels, samples, 2);
	}
}

OggAudioFile::~OggAudioFile()
{
	ov_clear(&file);
}

std::string	OggAudioFile::getExtension()
{
	return ".ogg";
}

bool		OggAudioFile::read(void* buffer, int numFrames)
{
	int frames;
	int bytes = numFrames * info->channels * 2;
	ogg_int64_t oldoff = ov_pcm_tell(&file);
#if BYTE_ORDER == BIG_ENDIAN
	frames = ov_read(&file, (char *) buffer, bytes, 1, 2, 1, &stream);
#else
	frames = ov_read(&file, (char *) buffer, bytes, 0, 2, 1, &stream);
#endif
	ogg_int64_t pcmoff = ov_pcm_tell(&file);
	std::cout << "requested: " << numFrames << "\n";
	std::cout << "actual:    " << pcmoff  - oldoff << "\n\n";
	if (frames < 0) {
		if (frames == OV_HOLE)
			// OV_HOLE is non-fatal
			return true;
		else
			return false;
	}
	return true;
}

size_t	OAFRead(void* ptr, size_t size, size_t nmemb, void* datasource)
{
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	std::streamoff pos1 = std::streamoff(bundle->input->tellg());
	std::streamsize read = size * nmemb;

	if (pos1 + read > bundle->length) {
		read = bundle->length - pos1;
	}
	if (pos1 == bundle->length)
		// EOF
		return 0;
	bundle->input->read((char*) ptr, read);

	return read;
}

int		OAFSeek(void* datasource, ogg_int64_t offset, int whence)
{
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	switch (whence) {
		case SEEK_SET:
			bundle->input->seekg(offset, std::ios::beg);
			break;
		case SEEK_CUR:
			bundle->input->seekg(offset, std::ios::cur);
			break;
		case SEEK_END:
			bundle->input->seekg(offset, std::ios::end);
			break;
	}
	return 0;
}

int		OAFClose(void* datasource)
{
	// technically we should close here, but this is handled outside
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	delete bundle;
	return 0;
}

long		OAFTell(void* datasource)
{
	OAFInputBundle* bundle = (OAFInputBundle*) datasource;
	return bundle->input->tellg();
}
// ex: shiftwidth=4 tabstop=4
<|endoftext|>


<commit_before>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/ValueMapper.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;

// Out of line method to get vtable etc for class.
void ValueMapTypeRemapper::anchor() {}
void ValueMaterializer::anchor() {}

Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
                      ValueMapTypeRemapper *TypeMapper,
                      ValueMaterializer *Materializer) {
  ValueToValueMapTy::iterator I = VM.find(V);

  // If the value already exists in the map, use it.
  if (I != VM.end() && I->second) return I->second;

  // If we have a materializer and it can materialize a value, use that.
  if (Materializer) {
    if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
      return VM[V] = NewV;
  }

  // Global values do not need to be seeded into the VM if they
  // are using the identity mapping.
  if (isa<GlobalValue>(V))
    return VM[V] = const_cast<Value*>(V);

  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
    // Inline asm may need *type* remapping.
    FunctionType *NewTy = IA->getFunctionType();
    if (TypeMapper) {
      NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));

      if (NewTy != IA->getFunctionType())
        V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
                           IA->hasSideEffects(), IA->isAlignStack());
    }

    return VM[V] = const_cast<Value*>(V);
  }

  if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
    const Metadata *MD = MDV->getMetadata();
    // If this is a module-level metadata and we know that nothing at the module
    // level is changing, then use an identity mapping.
    if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
      return VM[V] = const_cast<Value *>(V);

    auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
    if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
      return VM[V] = const_cast<Value *>(V);

    // FIXME: This assert crashes during bootstrap, but I think it should be
    // correct.  For now, just match behaviour from before the metadata/value
    // split.
    //
    //    assert(MappedMD && "Referenced metadata value not in value map");
    return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
  }

  // Okay, this either must be a constant (which may or may not be mappable) or
  // is something that is not in the mapping table.
  Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
  if (!C)
    return nullptr;

  if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
    Function *F =
      cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
    BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
                                                       Flags, TypeMapper, Materializer));
    return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
  }

  // Otherwise, we have some other constant to remap.  Start by checking to see
  // if all operands have an identity remapping.
  unsigned OpNo = 0, NumOperands = C->getNumOperands();
  Value *Mapped = nullptr;
  for (; OpNo != NumOperands; ++OpNo) {
    Value *Op = C->getOperand(OpNo);
    Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
    if (Mapped != C) break;
  }

  // See if the type mapper wants to remap the type as well.
  Type *NewTy = C->getType();
  if (TypeMapper)
    NewTy = TypeMapper->remapType(NewTy);

  // If the result type and all operands match up, then just insert an identity
  // mapping.
  if (OpNo == NumOperands && NewTy == C->getType())
    return VM[V] = C;

  // Okay, we need to create a new constant.  We've already processed some or
  // all of the operands, set them all up now.
  SmallVector<Constant*, 8> Ops;
  Ops.reserve(NumOperands);
  for (unsigned j = 0; j != OpNo; ++j)
    Ops.push_back(cast<Constant>(C->getOperand(j)));

  // If one of the operands mismatch, push it and the other mapped operands.
  if (OpNo != NumOperands) {
    Ops.push_back(cast<Constant>(Mapped));

    // Map the rest of the operands that aren't processed yet.
    for (++OpNo; OpNo != NumOperands; ++OpNo)
      Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
                             Flags, TypeMapper, Materializer));
  }

  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
    return VM[V] = CE->getWithOperands(Ops, NewTy);
  if (isa<ConstantArray>(C))
    return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
  if (isa<ConstantStruct>(C))
    return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
  if (isa<ConstantVector>(C))
    return VM[V] = ConstantVector::get(Ops);
  // If this is a no-operand constant, it must be because the type was remapped.
  if (isa<UndefValue>(C))
    return VM[V] = UndefValue::get(NewTy);
  if (isa<ConstantAggregateZero>(C))
    return VM[V] = ConstantAggregateZero::get(NewTy);
  assert(isa<ConstantPointerNull>(C));
  return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
}

static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
                     Metadata *Val) {
  VM.MD()[Key].reset(Val);
  return Val;
}

static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
  return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
}

static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
                                 RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer);

static Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,
                                 RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  if (!Op)
    return nullptr;
  if (Metadata *MappedOp =
          MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))
    return MappedOp;
  // Use identity map if MappedOp is null and we can ignore missing entries.
  if (Flags & RF_IgnoreMissingEntries)
    return Op;

  // FIXME: This assert crashes during bootstrap, but I think it should be
  // correct.  For now, just match behaviour from before the metadata/value
  // split.
  //
  //    llvm_unreachable("Referenced metadata not in value map!");
  return nullptr;
}

/// \brief Map a distinct MDNode.
///
/// Distinct nodes are not uniqued, so they must always recreated.
static Metadata *mapDistinctNode(const UniquableMDNode *Node,
                                 ValueToValueMapTy &VM, RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  assert(Node->isDistinct() && "Expected distinct node");

  // Create the node first so it's available for cyclical references.
  SmallVector<Metadata *, 4> EmptyOps(Node->getNumOperands());
  MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps);
  mapToMetadata(VM, Node, NewMD);

  // Fix the operands.
  for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
    NewMD->replaceOperandWith(I, mapMetadataOp(Node->getOperand(I), VM, Flags,
                                               TypeMapper, Materializer));

  return NewMD;
}

/// \brief Map a uniqued MDNode.
///
/// Uniqued nodes may not need to be recreated (they may map to themselves).
static Metadata *mapUniquedNode(const UniquableMDNode *Node,
                                 ValueToValueMapTy &VM, RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  assert(!Node->isDistinct() && "Expected uniqued node");

  // Create a dummy node in case we have a metadata cycle.
  MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);
  mapToMetadata(VM, Node, Dummy);

  // Check all operands to see if any need to be remapped.
  for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
    Metadata *Op = Node->getOperand(I);
    Metadata *MappedOp = mapMetadataOp(Op, VM, Flags, TypeMapper, Materializer);
    if (Op == MappedOp)
      continue;

    // Ok, at least one operand needs remapping.
    SmallVector<Metadata *, 4> Elts;
    Elts.reserve(Node->getNumOperands());
    for (I = 0; I != E; ++I)
      Elts.push_back(mapMetadataOp(Node->getOperand(I), VM, Flags, TypeMapper,
                                   Materializer));

    MDNode *NewMD = MDTuple::get(Node->getContext(), Elts);
    Dummy->replaceAllUsesWith(NewMD);
    MDNode::deleteTemporary(Dummy);
    return mapToMetadata(VM, Node, NewMD);
  }

  // No operands needed remapping.  Use an identity mapping.
  mapToSelf(VM, Node);
  MDNode::deleteTemporary(Dummy);
  return const_cast<Metadata *>(static_cast<const Metadata *>(Node));
}

static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
                                 RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  // If the value already exists in the map, use it.
  if (Metadata *NewMD = VM.MD().lookup(MD).get())
    return NewMD;

  if (isa<MDString>(MD))
    return mapToSelf(VM, MD);

  if (isa<ConstantAsMetadata>(MD))
    if ((Flags & RF_NoModuleLevelChanges))
      return mapToSelf(VM, MD);

  if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
    Value *MappedV =
        MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
    if (VMD->getValue() == MappedV ||
        (!MappedV && (Flags & RF_IgnoreMissingEntries)))
      return mapToSelf(VM, MD);

    // FIXME: This assert crashes during bootstrap, but I think it should be
    // correct.  For now, just match behaviour from before the metadata/value
    // split.
    //
    //    assert(MappedV && "Referenced metadata not in value map!");
    if (MappedV)
      return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
    return nullptr;
  }

  const UniquableMDNode *Node = cast<UniquableMDNode>(MD);
  assert(Node->isResolved() && "Unexpected unresolved node");

  // If this is a module-level metadata and we know that nothing at the
  // module level is changing, then use an identity mapping.
  if (Flags & RF_NoModuleLevelChanges)
    return mapToSelf(VM, MD);

  if (Node->isDistinct())
    return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);

  return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);
}

Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
                            RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
                            ValueMaterializer *Materializer) {
  Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);
  if (NewMD && NewMD != MD)
    if (auto *N = dyn_cast<UniquableMDNode>(NewMD))
      N->resolveCycles();
  return NewMD;
}

MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
                          RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
                          ValueMaterializer *Materializer) {
  return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
                                  TypeMapper, Materializer));
}

/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by VMap.
///
void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
                            RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
                            ValueMaterializer *Materializer){
  // Remap operands.
  for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
    Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
    // If we aren't ignoring missing entries, assert that something happened.
    if (V)
      *op = V;
    else
      assert((Flags & RF_IgnoreMissingEntries) &&
             "Referenced value not in value map!");
  }

  // Remap phi nodes' incoming blocks.
  if (PHINode *PN = dyn_cast<PHINode>(I)) {
    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
      Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
      // If we aren't ignoring missing entries, assert that something happened.
      if (V)
        PN->setIncomingBlock(i, cast<BasicBlock>(V));
      else
        assert((Flags & RF_IgnoreMissingEntries) &&
               "Referenced block not in value map!");
    }
  }

  // Remap attached metadata.
  SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  I->getAllMetadata(MDs);
  for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
           MI = MDs.begin(),
           ME = MDs.end();
       MI != ME; ++MI) {
    MDNode *Old = MI->second;
    MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
    if (New != Old)
      I->setMetadata(MI->first, New);
  }

  // If the instruction's type is being remapped, do so now.
  if (TypeMapper)
    I->mutateType(TypeMapper->remapType(I->getType()));
}
<commit_msg>Utils: Simplify code, NFC<commit_after>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MapValue function, which is shared by various parts of
// the lib/Transforms/Utils library.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/ValueMapper.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;

// Out of line method to get vtable etc for class.
void ValueMapTypeRemapper::anchor() {}
void ValueMaterializer::anchor() {}

Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
                      ValueMapTypeRemapper *TypeMapper,
                      ValueMaterializer *Materializer) {
  ValueToValueMapTy::iterator I = VM.find(V);

  // If the value already exists in the map, use it.
  if (I != VM.end() && I->second) return I->second;

  // If we have a materializer and it can materialize a value, use that.
  if (Materializer) {
    if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
      return VM[V] = NewV;
  }

  // Global values do not need to be seeded into the VM if they
  // are using the identity mapping.
  if (isa<GlobalValue>(V))
    return VM[V] = const_cast<Value*>(V);

  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
    // Inline asm may need *type* remapping.
    FunctionType *NewTy = IA->getFunctionType();
    if (TypeMapper) {
      NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));

      if (NewTy != IA->getFunctionType())
        V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
                           IA->hasSideEffects(), IA->isAlignStack());
    }

    return VM[V] = const_cast<Value*>(V);
  }

  if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
    const Metadata *MD = MDV->getMetadata();
    // If this is a module-level metadata and we know that nothing at the module
    // level is changing, then use an identity mapping.
    if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
      return VM[V] = const_cast<Value *>(V);

    auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
    if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
      return VM[V] = const_cast<Value *>(V);

    // FIXME: This assert crashes during bootstrap, but I think it should be
    // correct.  For now, just match behaviour from before the metadata/value
    // split.
    //
    //    assert(MappedMD && "Referenced metadata value not in value map");
    return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
  }

  // Okay, this either must be a constant (which may or may not be mappable) or
  // is something that is not in the mapping table.
  Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
  if (!C)
    return nullptr;

  if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
    Function *F =
      cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
    BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
                                                       Flags, TypeMapper, Materializer));
    return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
  }

  // Otherwise, we have some other constant to remap.  Start by checking to see
  // if all operands have an identity remapping.
  unsigned OpNo = 0, NumOperands = C->getNumOperands();
  Value *Mapped = nullptr;
  for (; OpNo != NumOperands; ++OpNo) {
    Value *Op = C->getOperand(OpNo);
    Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
    if (Mapped != C) break;
  }

  // See if the type mapper wants to remap the type as well.
  Type *NewTy = C->getType();
  if (TypeMapper)
    NewTy = TypeMapper->remapType(NewTy);

  // If the result type and all operands match up, then just insert an identity
  // mapping.
  if (OpNo == NumOperands && NewTy == C->getType())
    return VM[V] = C;

  // Okay, we need to create a new constant.  We've already processed some or
  // all of the operands, set them all up now.
  SmallVector<Constant*, 8> Ops;
  Ops.reserve(NumOperands);
  for (unsigned j = 0; j != OpNo; ++j)
    Ops.push_back(cast<Constant>(C->getOperand(j)));

  // If one of the operands mismatch, push it and the other mapped operands.
  if (OpNo != NumOperands) {
    Ops.push_back(cast<Constant>(Mapped));

    // Map the rest of the operands that aren't processed yet.
    for (++OpNo; OpNo != NumOperands; ++OpNo)
      Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
                             Flags, TypeMapper, Materializer));
  }

  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
    return VM[V] = CE->getWithOperands(Ops, NewTy);
  if (isa<ConstantArray>(C))
    return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
  if (isa<ConstantStruct>(C))
    return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
  if (isa<ConstantVector>(C))
    return VM[V] = ConstantVector::get(Ops);
  // If this is a no-operand constant, it must be because the type was remapped.
  if (isa<UndefValue>(C))
    return VM[V] = UndefValue::get(NewTy);
  if (isa<ConstantAggregateZero>(C))
    return VM[V] = ConstantAggregateZero::get(NewTy);
  assert(isa<ConstantPointerNull>(C));
  return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
}

static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
                     Metadata *Val) {
  VM.MD()[Key].reset(Val);
  return Val;
}

static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
  return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
}

static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
                                 RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer);

static Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,
                                 RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  if (!Op)
    return nullptr;
  if (Metadata *MappedOp =
          MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))
    return MappedOp;
  // Use identity map if MappedOp is null and we can ignore missing entries.
  if (Flags & RF_IgnoreMissingEntries)
    return Op;

  // FIXME: This assert crashes during bootstrap, but I think it should be
  // correct.  For now, just match behaviour from before the metadata/value
  // split.
  //
  //    llvm_unreachable("Referenced metadata not in value map!");
  return nullptr;
}

/// \brief Map a distinct MDNode.
///
/// Distinct nodes are not uniqued, so they must always recreated.
static Metadata *mapDistinctNode(const UniquableMDNode *Node,
                                 ValueToValueMapTy &VM, RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  assert(Node->isDistinct() && "Expected distinct node");

  // Create the node first so it's available for cyclical references.
  SmallVector<Metadata *, 4> EmptyOps(Node->getNumOperands());
  MDTuple *NewMD = MDTuple::getDistinct(Node->getContext(), EmptyOps);
  mapToMetadata(VM, Node, NewMD);

  // Fix the operands.
  for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
    NewMD->replaceOperandWith(I, mapMetadataOp(Node->getOperand(I), VM, Flags,
                                               TypeMapper, Materializer));

  return NewMD;
}

/// \brief Map a uniqued MDNode.
///
/// Uniqued nodes may not need to be recreated (they may map to themselves).
static Metadata *mapUniquedNode(const UniquableMDNode *Node,
                                 ValueToValueMapTy &VM, RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  assert(!Node->isDistinct() && "Expected uniqued node");

  // Create a dummy node in case we have a metadata cycle.
  MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);
  mapToMetadata(VM, Node, Dummy);

  // Check all operands to see if any need to be remapped.
  for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
    Metadata *Op = Node->getOperand(I);
    if (Op == mapMetadataOp(Op, VM, Flags, TypeMapper, Materializer))
      continue;

    // Ok, at least one operand needs remapping.
    SmallVector<Metadata *, 4> Elts;
    Elts.reserve(Node->getNumOperands());
    for (I = 0; I != E; ++I)
      Elts.push_back(mapMetadataOp(Node->getOperand(I), VM, Flags, TypeMapper,
                                   Materializer));

    MDNode *NewMD = MDTuple::get(Node->getContext(), Elts);
    Dummy->replaceAllUsesWith(NewMD);
    MDNode::deleteTemporary(Dummy);
    return mapToMetadata(VM, Node, NewMD);
  }

  // No operands needed remapping.  Use an identity mapping.
  mapToSelf(VM, Node);
  MDNode::deleteTemporary(Dummy);
  return const_cast<Metadata *>(static_cast<const Metadata *>(Node));
}

static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
                                 RemapFlags Flags,
                                 ValueMapTypeRemapper *TypeMapper,
                                 ValueMaterializer *Materializer) {
  // If the value already exists in the map, use it.
  if (Metadata *NewMD = VM.MD().lookup(MD).get())
    return NewMD;

  if (isa<MDString>(MD))
    return mapToSelf(VM, MD);

  if (isa<ConstantAsMetadata>(MD))
    if ((Flags & RF_NoModuleLevelChanges))
      return mapToSelf(VM, MD);

  if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
    Value *MappedV =
        MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
    if (VMD->getValue() == MappedV ||
        (!MappedV && (Flags & RF_IgnoreMissingEntries)))
      return mapToSelf(VM, MD);

    // FIXME: This assert crashes during bootstrap, but I think it should be
    // correct.  For now, just match behaviour from before the metadata/value
    // split.
    //
    //    assert(MappedV && "Referenced metadata not in value map!");
    if (MappedV)
      return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
    return nullptr;
  }

  const UniquableMDNode *Node = cast<UniquableMDNode>(MD);
  assert(Node->isResolved() && "Unexpected unresolved node");

  // If this is a module-level metadata and we know that nothing at the
  // module level is changing, then use an identity mapping.
  if (Flags & RF_NoModuleLevelChanges)
    return mapToSelf(VM, MD);

  if (Node->isDistinct())
    return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);

  return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);
}

Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
                            RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
                            ValueMaterializer *Materializer) {
  Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);
  if (NewMD && NewMD != MD)
    if (auto *N = dyn_cast<UniquableMDNode>(NewMD))
      N->resolveCycles();
  return NewMD;
}

MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
                          RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
                          ValueMaterializer *Materializer) {
  return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
                                  TypeMapper, Materializer));
}

/// RemapInstruction - Convert the instruction operands from referencing the
/// current values into those specified by VMap.
///
void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
                            RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
                            ValueMaterializer *Materializer){
  // Remap operands.
  for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
    Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
    // If we aren't ignoring missing entries, assert that something happened.
    if (V)
      *op = V;
    else
      assert((Flags & RF_IgnoreMissingEntries) &&
             "Referenced value not in value map!");
  }

  // Remap phi nodes' incoming blocks.
  if (PHINode *PN = dyn_cast<PHINode>(I)) {
    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
      Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
      // If we aren't ignoring missing entries, assert that something happened.
      if (V)
        PN->setIncomingBlock(i, cast<BasicBlock>(V));
      else
        assert((Flags & RF_IgnoreMissingEntries) &&
               "Referenced block not in value map!");
    }
  }

  // Remap attached metadata.
  SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  I->getAllMetadata(MDs);
  for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
           MI = MDs.begin(),
           ME = MDs.end();
       MI != ME; ++MI) {
    MDNode *Old = MI->second;
    MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
    if (New != Old)
      I->setMetadata(MI->first, New);
  }

  // If the instruction's type is being remapped, do so now.
  if (TypeMapper)
    I->mutateType(TypeMapper->remapType(I->getType()));
}
<|endoftext|>


<commit_before>#include "menu/option_mugen_menu.h"
#include "util/bitmap.h"
#include "util/font.h"
#include "menu/menu.h"
#include "util/token.h"
#include "return_exception.h"
#include "util/token_exception.h"
#include "util/funcs.h"
#include "globals.h"

#include "mugen/mugen_menu.h"
#include "mugen/mugen_exception.h"
#include "return_exception.h"

using namespace std;

OptionMugenMenu::OptionMugenMenu(Token *token) throw (LoadException): MenuOption(token, Event), _menu(0)
{
	if ( *token != "mugen" ){
		throw LoadException("Not a mugen motif menu");
	}
	while ( token->hasTokens() ){
		try{
			Token * tok;
			*token >> tok;
			if ( *tok == "name" ){
				// Create an image and push it back on to vector
				std::string temp;
				*tok >> temp;
				this->setText(temp);
			} else if (*tok == "motif"){
			    // Load Motif from file
			    std::string temp;
			    // Filename
			    *tok >> temp;
			    _menu = new MugenMenu(temp);
			}else {
				Global::debug( 3 ) <<"Unhandled menu attribute: "<<endl;
                                if (Global::getDebug() >= 3){
                                    tok->print(" ");
                                }
			}
		} catch ( const TokenException & ex ) {
			// delete current;
			string m( "Menu parse error: " );
			m += ex.getReason();
			throw LoadException( m );
		}
	}
	// Set this menu as an option
	_menu->setAsOption(true);

	// Lets check if this menu is going bye bye
	//if ( _menu->checkRemoval() ) setForRemoval(true);
}

OptionMugenMenu::~OptionMugenMenu()
{
	// Delete our menu
	if(_menu)delete _menu;
}

void OptionMugenMenu::logic()
{
	// Nothing
}

void OptionMugenMenu::run(bool &endGame){
    // Load er up and throw up a load box to inform the user
    Box::msgDialog(*getParent()->getWork(),"Loading M.U.G.E.N.!",2);
    try {
	_menu->loadData();
    } catch (const MugenException & ex){
	string m("Problem with loading MUGEN menu: ");
	m += ex.getFullReason();
	throw LoadException(m);
    }
    try {
	// Run
	_menu->run();
    } catch (const ReturnException & re){
	// Say what?
	// Do not quit game
    }
}

<commit_msg>use normal loading screen when loading mugen<commit_after>#include "menu/option_mugen_menu.h"
#include "util/bitmap.h"
#include "util/font.h"
#include "menu/menu.h"
#include "util/token.h"
#include "return_exception.h"
#include "util/token_exception.h"
#include "util/funcs.h"
#include "globals.h"
#include "loading.h"
#include <pthread.h>

#include "mugen/mugen_menu.h"
#include "mugen/mugen_exception.h"
#include "return_exception.h"

using namespace std;

OptionMugenMenu::OptionMugenMenu(Token *token) throw (LoadException): MenuOption(token, Event), _menu(0){
    if ( *token != "mugen" ){
        throw LoadException("Not a mugen motif menu");
    }
    while ( token->hasTokens() ){
        try{
            Token * tok;
            *token >> tok;
            if ( *tok == "name" ){
                // Create an image and push it back on to vector
                std::string temp;
                *tok >> temp;
                this->setText(temp);
            } else if (*tok == "motif"){
                // Load Motif from file
                std::string temp;
                // Filename
                *tok >> temp;
                _menu = new MugenMenu(temp);
            }else {
                Global::debug( 3 ) <<"Unhandled menu attribute: "<<endl;
                if (Global::getDebug() >= 3){
                    tok->print(" ");
                }
            }
        } catch ( const TokenException & ex ) {
            // delete current;
            string m( "Menu parse error: " );
            m += ex.getReason();
            throw LoadException( m );
        }
    }
    // Set this menu as an option
    _menu->setAsOption(true);

    // Lets check if this menu is going bye bye
    //if ( _menu->checkRemoval() ) setForRemoval(true);
}

OptionMugenMenu::~OptionMugenMenu(){
    // Delete our menu
    if (_menu){
        delete _menu;
    }
}

void OptionMugenMenu::logic(){
	// Nothing
}

void OptionMugenMenu::run(bool &endGame){
    // Load er up and throw up a load box to inform the user
    // Box::msgDialog(*getParent()->getWork(),"Loading M.U.G.E.N.!",2);
    pthread_t loading;
    Loader::startLoading(&loading);
    try {
        _menu->loadData();
    } catch (const MugenException & ex){
        string m("Problem with loading MUGEN menu: ");
        m += ex.getFullReason();
        Loader::stopLoading(loading);
        throw LoadException(m);
    }
    Loader::stopLoading(loading);

    try {
        // Run
        _menu->run();
    } catch (const ReturnException & re){
        // Say what?
        // Do not quit game
    }
}

<|endoftext|>


<commit_before>#if defined(LINUX)
#include "user/util.h"
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#define O_CREATE O_CREAT
#define xfork() fork()
#define xexit() exit(EXIT_SUCCESS)
typedef uint64_t u64;
#else
#include "types.h"
#include "user.h"
#include "fcntl.h"
#include "amd64.h"
#define xfork() fork(0)
#define xexit() exit()
#endif

#define CHUNKSZ 512
#define FILESZ  (NCPU*CHUNKSZ)

static const bool pinit = true;

static char chunkbuf[CHUNKSZ];

static void
bench(int tid, int nloop)
{
  if (pinit)
    setaffinity(tid);

  int fd = open("filebenchx", O_RDONLY);
  if (fd < 0)
    die("open");

  for (int i = 0; i < nloop; i++) {
    ssize_t r;

    r = pread(fd, chunkbuf, CHUNKSZ, CHUNKSZ*tid);
    if (r != CHUNKSZ)
      die("pread");
  }

  close(fd);
  xexit();
}

int
main(int ac, char **av)
{
  int nthread;
  int nloop;

#ifdef HW_qemu
  nloop = 50;
#else
  nloop = 1000;
#endif

  if (ac < 2)
    die("usage: %s nthreads [nloop]", av[0]);

  nthread = atoi(av[1]);
  if (ac > 2)
    nloop = atoi(av[2]);

  // Setup shared file
  int fd = open("filebenchx", O_CREATE|O_WRONLY);
  if (fd < 0)
    die("open O_CREAT failed");
  for (int i = 0; i < FILESZ; i += CHUNKSZ) {
    int r = write(fd, chunkbuf, CHUNKSZ);
    if (r < CHUNKSZ)
      die("write");
  }
  close(fd);

  u64 t0 = rdtsc();
  for (int i = 0; i < nthread; i++) {
    int pid = xfork();
    if (pid == 0)
      bench(i, nloop);
    else if (pid < 0)
      die("fork");
  }

  for (int i = 0; i < nthread; i++)
    wait();
  u64 t1 = rdtsc();

  printf("filebench: %lu\n", t1-t0);
  return 0;
}
<commit_msg>A few more filebench tweaks<commit_after>#if defined(LINUX)
#include "user/util.h"
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#define O_CREATE O_CREAT
#define xfork() fork()
#define xexit() exit(EXIT_SUCCESS)
#define xcreat(name) open((name), O_CREATE|O_WRONLY, S_IRUSR|S_IWUSR)
typedef uint64_t u64;
#else
#include "types.h"
#include "user.h"
#include "fcntl.h"
#include "amd64.h"
#define xfork() fork(0)
#define xexit() exit()
#define xcreat(name) open((name), O_CREATE|O_WRONLY)
#endif

#define CHUNKSZ 512
#define FILESZ  (NCPU*CHUNKSZ)

static const bool pinit = true;

static char chunkbuf[CHUNKSZ];

static void
bench(int tid, int nloop)
{
  if (pinit)
    setaffinity(tid);

  int fd = open("filebenchx", O_RDWR);
  if (fd < 0)
    die("open");

  for (int i = 0; i < nloop; i++) {
    ssize_t r;

    r = pread(fd, chunkbuf, CHUNKSZ, CHUNKSZ*tid);
    if (r != CHUNKSZ)
      die("pread");
  }

  close(fd);
  xexit();
}

int
main(int ac, char **av)
{
  int nthread;
  int nloop;

#ifdef HW_qemu
  nloop = 50;
#else
  nloop = 1000;
#endif

  if (ac < 2)
    die("usage: %s nthreads [nloop]", av[0]);

  nthread = atoi(av[1]);
  if (ac > 2)
    nloop = atoi(av[2]);

  // Setup shared file
  unlink("filebenchx");
  int fd = xcreat("filebenchx");
  if (fd < 0)
    die("open O_CREAT failed");
  for (int i = 0; i < FILESZ; i += CHUNKSZ) {
    int r = write(fd, chunkbuf, CHUNKSZ);
    if (r < CHUNKSZ)
      die("write");
  }
  close(fd);

  u64 t0 = rdtsc();
  for (int i = 0; i < nthread; i++) {
    int pid = xfork();
    if (pid == 0)
      bench(i, nloop);
    else if (pid < 0)
      die("fork");
  }

  for (int i = 0; i < nthread; i++)
    wait();
  u64 t1 = rdtsc();

  printf("filebench: %lu\n", t1-t0);
  return 0;
}
<|endoftext|>


<commit_before>#include "json.h"
#include <boost/io/ios_state.hpp>
#include <boost/type_traits.hpp>
#include <cstdio>

namespace mfast {
  namespace json {
    namespace encode_detail {

      struct quoted_string {
        quoted_string(const char* str)
          : str_(str)
        {
        }

        const char* str_;
      };

      std::ostream& operator << (std::ostream& os, quoted_string str)
      {
        os.put('"');
        const char* ptr = str.str_;
        while (*ptr != '\x0') {
          if (*ptr == '\\' || *ptr == '"')
            os.put('\\');
          os.put(*ptr++);
        }
        os.put('"');
        return os;
      }

      class json_visitor
      {
      protected:
        std::ostream& strm_;
        char separator_[2];
        unsigned json_object_tag_mask_;

      public:

        enum {
          visit_absent = 0
        };

        json_visitor(std::ostream& strm,
                     unsigned      json_object_tag_mask)
          : strm_(strm)
          , json_object_tag_mask_(json_object_tag_mask)
        {
          separator_[0] = 0;
          separator_[1] = 0;
        }

        template <typename NumericTypeRef>
        void visit(const NumericTypeRef& ref)
        {
          strm_ <<  separator_ << ref.value();
        }

        void visit(const decimal_cref& ref)
        {
          const decimal_value_storage& storage = *reinterpret_cast<const decimal_value_storage*>( field_cref_core_access::storage_of(ref) );
          strm_ <<  separator_ << storage;
        }

        void visit(const enum_cref& ref)
        {
          if (ref.is_boolean())
            strm_ <<  separator_ << ref.value_name();
          else
            strm_ << separator_ << ref.value();
        }

        template <typename Char>
        void visit(const mfast::string_cref<Char>& ref)
        {
          strm_ <<  separator_ << quoted_string(ref.c_str());
        }

        void visit(const mfast::byte_vector_cref& ref)
        {
          if (ref.instruction()->tag().to_uint64() & json_object_tag_mask_)
          {
            // if the json_object_tag_mask is on, that means the field contains
            // json encoded object already, just write it as it is without any processing.

            strm_.rdbuf()->sputn( reinterpret_cast<const char*>(ref.data()), ref.size());
          }
          else
          {
            // json doesn't have byte vector, treat it as hex string now
            strm_ <<  separator_ << "\"";
            boost::io::ios_flags_saver ifs( strm_ );
            strm_ << std::hex << std::setfill('0') << std::setw(2);

            for (std::size_t i = 0; i < ref.size(); ++i)
            {
              // if the size is 16, we treat it as a UUID
              if (ref.size() == 16 && (i==4 || i==6 || i==8 || i==10))
                strm_ << '-';
              strm_ <<  (0xFF & (int) ref[i]);
            }
            strm_ << "\"" << std::setfill(' ');
          }
        }

        template <typename IntType>
        void visit(const mfast::int_vector_cref<IntType>& ref)
        {
          strm_ << separator_  << "[";
          separator_[0] = '\0';

          for (std::size_t i = 0; i < ref.size(); ++i) {
            strm_ << separator_ << ref[i];
            separator_[0] = ',';
          }
          strm_ << "]";
        }

        void visit(const mfast::aggregate_cref& ref, int)
        {
          if (ref.num_fields()  == 1) {
            field_cref f0 = ref[0];
            if (f0.instruction()->field_type() == mfast::field_type_templateref) {
              if (f0.present())
                this->visit(mfast::nested_message_cref(f0),0);
              return;
            }
          }

          strm_ << separator_ <<  "{";
          separator_[0] = '\0';

          for (std::size_t i = 0; i < ref.num_fields(); ++i) {
            if (ref[i].present()) {
              strm_ << separator_ << quoted_string(ref[i].name()) << ":";
              separator_[0] = '\0';
              ref[i].accept_accessor(*this);
              separator_[0] = ',';
            }
          }

          strm_ << "}";
        }

        void visit(const mfast::sequence_cref& ref, int)
        {
          strm_ << separator_  << "[";
          if (ref.size()) {
            separator_[0] = '\0';
            ref.accept_accessor(*this);
          }
          strm_ << "]";
        }

        void visit(const mfast::sequence_element_cref& ref, int)
        {
          if (ref.element_unnamed()) {
            ref[0].accept_accessor(*this);
          }
          else {
            this->visit(mfast::aggregate_cref(ref), 0);
          }
          separator_[0] = ',';
        }

        void visit(const mfast::nested_message_cref& ref, int)
        {
          this->visit(mfast::aggregate_cref(ref), 0);
        }

      };

      class json_visitor_with_ignore_tag
        : public json_visitor
      {
      private:
        unsigned ignore_tag_mask_;

      public:
        using json_visitor::visit;

        json_visitor_with_ignore_tag(std::ostream& strm,
                                     unsigned      json_object_tag_mask,
                                     unsigned      ignore_tag_mask)
          : json_visitor(strm, json_object_tag_mask)
          , ignore_tag_mask_(ignore_tag_mask)
        {
        }

        void visit(const mfast::aggregate_cref& ref, int)
        {
          if (ref.num_fields()  == 1) {
            field_cref f0 = ref[0];
            if (f0.instruction()->field_type() == mfast::field_type_templateref) {
              if (f0.present())
                this->visit(mfast::nested_message_cref(f0),0);
              return;
            }
          }

          strm_ << separator_ <<  "{";
          separator_[0] = '\0';

          for (std::size_t i = 0; i < ref.num_fields(); ++i) {
            if (ref[i].present() && 0 == (ref[i].instruction()->tag().to_uint64() & ignore_tag_mask_)) {
              strm_ << separator_ << quoted_string(ref[i].name()) << ":";
              separator_[0] = '\0';
              ref[i].accept_accessor(*this);
              separator_[0] = ',';
            }
          }

          strm_ << "}";
        }

      };

    } // namspace encode_detail

    bool encode(std::ostream&                os,
                const mfast::aggregate_cref& msg,
                unsigned                     json_object_tag_mask)
    {
      encode_detail::json_visitor visitor(os, json_object_tag_mask);
      visitor.visit(msg, 0);
      return os.good();
    }

    bool encode(std::ostream&               os,
                const mfast::sequence_cref& seq,
                unsigned                    json_object_tag_mask)
    {
      encode_detail::json_visitor visitor(os, json_object_tag_mask);
      visitor.visit(seq, 0);
      return os.good();
    }

    bool encode(std::ostream&                  os,
                const ::mfast::aggregate_cref& msg,
                unsigned                       json_object_tag_mask,
                unsigned                       ignore_tag_mask)
    {
      encode_detail::json_visitor_with_ignore_tag visitor(os, json_object_tag_mask, ignore_tag_mask);
      visitor.visit(msg, 0);
      return os.good();
    }

  } // namespace json
} // namespace mfast
<commit_msg>Fixed json encoder problem with nested fields not properly ignored.<commit_after>#include "json.h"
#include <boost/io/ios_state.hpp>
#include <boost/type_traits.hpp>
#include <cstdio>

namespace mfast {
  namespace json {
    namespace encode_detail {

      struct quoted_string {
        quoted_string(const char* str)
          : str_(str)
        {
        }

        const char* str_;
      };

      std::ostream& operator << (std::ostream& os, quoted_string str)
      {
        os.put('"');
        const char* ptr = str.str_;
        while (*ptr != '\x0') {
          if (*ptr == '\\' || *ptr == '"')
            os.put('\\');
          os.put(*ptr++);
        }
        os.put('"');
        return os;
      }

      class json_visitor
      {
      protected:
        std::ostream& strm_;
        char separator_[2];
        unsigned json_object_tag_mask_;

      public:

        enum {
          visit_absent = 0
        };

        json_visitor(std::ostream& strm,
                     unsigned      json_object_tag_mask)
          : strm_(strm)
          , json_object_tag_mask_(json_object_tag_mask)
        {
          separator_[0] = 0;
          separator_[1] = 0;
        }

        template <typename NumericTypeRef>
        void visit(const NumericTypeRef& ref)
        {
          strm_ <<  separator_ << ref.value();
        }

        void visit(const decimal_cref& ref)
        {
          const decimal_value_storage& storage = *reinterpret_cast<const decimal_value_storage*>( field_cref_core_access::storage_of(ref) );
          strm_ <<  separator_ << storage;
        }

        void visit(const enum_cref& ref)
        {
          if (ref.is_boolean())
            strm_ <<  separator_ << ref.value_name();
          else
            strm_ << separator_ << ref.value();
        }

        template <typename Char>
        void visit(const mfast::string_cref<Char>& ref)
        {
          strm_ <<  separator_ << quoted_string(ref.c_str());
        }

        void visit(const mfast::byte_vector_cref& ref)
        {
          if (ref.instruction()->tag().to_uint64() & json_object_tag_mask_)
          {
            // if the json_object_tag_mask is on, that means the field contains
            // json encoded object already, just write it as it is without any processing.

            strm_.rdbuf()->sputn( reinterpret_cast<const char*>(ref.data()), ref.size());
          }
          else
          {
            // json doesn't have byte vector, treat it as hex string now
            strm_ <<  separator_ << "\"";
            boost::io::ios_flags_saver ifs( strm_ );
            strm_ << std::hex << std::setfill('0') << std::setw(2);

            for (std::size_t i = 0; i < ref.size(); ++i)
            {
              // if the size is 16, we treat it as a UUID
              if (ref.size() == 16 && (i==4 || i==6 || i==8 || i==10))
                strm_ << '-';
              strm_ <<  (0xFF & (int) ref[i]);
            }
            strm_ << "\"" << std::setfill(' ');
          }
        }

        template <typename IntType>
        void visit(const mfast::int_vector_cref<IntType>& ref)
        {
          strm_ << separator_  << "[";
          separator_[0] = '\0';

          for (std::size_t i = 0; i < ref.size(); ++i) {
            strm_ << separator_ << ref[i];
            separator_[0] = ',';
          }
          strm_ << "]";
        }

        virtual void visit(const mfast::aggregate_cref& ref, int)
        {
          if (ref.num_fields()  == 1) {
            field_cref f0 = ref[0];
            if (f0.instruction()->field_type() == mfast::field_type_templateref) {
              if (f0.present())
                this->visit(mfast::nested_message_cref(f0),0);
              return;
            }
          }

          strm_ << separator_ <<  "{";
          separator_[0] = '\0';

          for (std::size_t i = 0; i < ref.num_fields(); ++i) {
            if (ref[i].present()) {
              strm_ << separator_ << quoted_string(ref[i].name()) << ":";
              separator_[0] = '\0';
              ref[i].accept_accessor(*this);
              separator_[0] = ',';
            }
          }

          strm_ << "}";
        }

        void visit(const mfast::sequence_cref& ref, int)
        {
          strm_ << separator_  << "[";
          if (ref.size()) {
            separator_[0] = '\0';
            ref.accept_accessor(*this);
          }
          strm_ << "]";
        }

        void visit(const mfast::sequence_element_cref& ref, int)
        {
          if (ref.element_unnamed()) {
            ref[0].accept_accessor(*this);
          }
          else {
            this->visit(mfast::aggregate_cref(ref), 0);
          }
          separator_[0] = ',';
        }

        void visit(const mfast::nested_message_cref& ref, int)
        {
          this->visit(mfast::aggregate_cref(ref), 0);
        }

      };

      class json_visitor_with_ignore_tag
        : public json_visitor
      {
      private:
        unsigned ignore_tag_mask_;

      public:
        using json_visitor::visit;

        json_visitor_with_ignore_tag(std::ostream& strm,
                                     unsigned      json_object_tag_mask,
                                     unsigned      ignore_tag_mask)
          : json_visitor(strm, json_object_tag_mask)
          , ignore_tag_mask_(ignore_tag_mask)
        {
        }

        virtual void visit(const mfast::aggregate_cref& ref, int)
        {
          if (ref.num_fields()  == 1) {
            field_cref f0 = ref[0];
            if (f0.instruction()->field_type() == mfast::field_type_templateref) {
              if (f0.present())
                this->visit(mfast::nested_message_cref(f0),0);
              return;
            }
          }

          strm_ << separator_ <<  "{";
          separator_[0] = '\0';

          for (std::size_t i = 0; i < ref.num_fields(); ++i) {
            if (ref[i].present() && 0 == (ref[i].instruction()->tag().to_uint64() & ignore_tag_mask_)) {
              strm_ << separator_ << quoted_string(ref[i].name()) << ":";
              separator_[0] = '\0';
              ref[i].accept_accessor(*this);
              separator_[0] = ',';
            }
          }

          strm_ << "}";
        }

      };

    } // namspace encode_detail

    bool encode(std::ostream&                os,
                const mfast::aggregate_cref& msg,
                unsigned                     json_object_tag_mask)
    {
      encode_detail::json_visitor visitor(os, json_object_tag_mask);
      visitor.visit(msg, 0);
      return os.good();
    }

    bool encode(std::ostream&               os,
                const mfast::sequence_cref& seq,
                unsigned                    json_object_tag_mask)
    {
      encode_detail::json_visitor visitor(os, json_object_tag_mask);
      visitor.visit(seq, 0);
      return os.good();
    }

    bool encode(std::ostream&                  os,
                const ::mfast::aggregate_cref& msg,
                unsigned                       json_object_tag_mask,
                unsigned                       ignore_tag_mask)
    {
      encode_detail::json_visitor_with_ignore_tag visitor(os, json_object_tag_mask, ignore_tag_mask);
      visitor.visit(msg, 0);
      return os.good();
    }

  } // namespace json
} // namespace mfast
<|endoftext|>


<commit_before>/**
 * @file consensushash.cpp
 *
 * This file contains the function to generate consensus hashes.
 */

#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/mdex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"

#include <stdint.h>
#include <string>

#include <openssl/sha.h>

namespace mastercore
{
/**
 * Obtains a hash of the active state to use for consensus verification and checkpointing.
 *
 * For increased flexibility, so other implementations like OmniWallet and OmniChest can
 * also apply this methodology without necessarily using the same exact data types (which
 * would be needed to hash the data bytes directly), create a string in the following
 * format for each entry to use for hashing:
 *
 * ---STAGE 1 - BALANCES---
 * Format specifiers & placeholders:
 *   "%s|%d|%d|%d|%d|%d" - "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
 *
 * Note: empty balance records and the pending tally are ignored. Addresses are sorted based
 * on lexicographical order, and balance records are sorted by the property identifiers.
 *
 * ---STAGE 2 - DEX SELL OFFERS---
 * Format specifiers & placeholders:
 *   "%s|%s|%d|%d|%d|%d|%d|%d|%d" - "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
 *
 * Note: ordered ascending by txid.
 *
 * ---STAGE 3 - DEX ACCEPTS---
 * Format specifiers & placeholders:
 *   "%s|%s|%d|%d|%d" - "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
 *
 * Note: ordered ascending by matchedselloffertxid followed by buyer.
 *
 * ---STAGE 4 - METADEX TRADES---
 * Format specifiers & placeholders:
 *   "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
 *
 * Note: ordered ascending by txid.
 *
 * ---STAGE 5 - CROWDSALES---
 * Format specifiers & placeholders:
 *   "%d|%d|%d|%d|%d" - "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
 *
 * Note: ordered by property ID.
 *
 * ---STAGE 6 - PROPERTIES---
 * Format specifiers & placeholders:
 *   "%d|%d" - "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
 *
 * The byte order is important, and we assume:
 *   SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
 *
 */
uint256 GetConsensusHash()
{
    // allocate and init a SHA256_CTX
    SHA256_CTX shaCtx;
    SHA256_Init(&shaCtx);

    LOCK(cs_tally);

    if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");

    // Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
    // Placeholders:  "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
    for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
        const std::string& address = my_it->first;
        CMPTally& tally = my_it->second;
        tally.init();
        uint32_t propertyId = 0;
        while (0 != (propertyId = (tally.next()))) {
            int64_t balance = tally.getMoney(propertyId, BALANCE);
            int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
            int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
            int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);

            // skip this entry if all balances are empty
            if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;

            std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
                    address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
            if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
            SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
        }
    }

    // DEx sell offers - loop through the DEx and add each sell offer to the consensus hash (ordered by txid)
    // Placeholders: "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
    std::vector<std::pair<uint256, std::string> > vecDExOffers;
    for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
        const CMPOffer& selloffer = it->second;
        const std::string& sellCombo = it->first;
        uint32_t propertyId = selloffer.getProperty();
        std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
        std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d|%d|%d",
                selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
                selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit(),
                getMPbalance(seller, propertyId, SELLOFFER_RESERVE), getMPbalance(seller, propertyId, ACCEPT_RESERVE));
        vecDExOffers.push_back(std::make_pair(selloffer.getHash(), dataStr));
    }
    std::sort (vecDExOffers.begin(), vecDExOffers.end());
    for (std::vector<std::pair<uint256, std::string> >::iterator it = vecDExOffers.begin(); it != vecDExOffers.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // DEx accepts - loop through the accepts map and add each accept to the consensus hash (ordered by matchedtxid then buyer)
    // Placeholders: "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
    std::vector<std::pair<std::string, std::string> > vecAccepts;
    for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) {
        const CMPAccept& accept = it->second;
        const std::string& acceptCombo = it->first;
        std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1)));
        std::string dataStr = strprintf("%s|%s|%d|%d|%d",
                accept.getHash().GetHex(), buyer, accept.getAcceptAmount(), accept.getAcceptAmountRemaining(), accept.getAcceptBlock());
        std::string sortKey = strprintf("%s-%s", accept.getHash().GetHex(), buyer);
        vecAccepts.push_back(std::make_pair(sortKey, dataStr));
    }
    std::sort (vecAccepts.begin(), vecAccepts.end());
    for (std::vector<std::pair<std::string, std::string> >::iterator it = vecAccepts.begin(); it != vecAccepts.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash (ordered by txid)
    // Placeholders: "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
    std::vector<std::pair<uint256, std::string> > vecMetaDExTrades;
    for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
        const md_PricesMap& prices = my_it->second;
        for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) {
            const md_Set& indexes = it->second;
            for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
                const CMPMetaDEx& obj = *it;
                std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
                    obj.getHash().GetHex(), obj.getAddr(), obj.getProperty(), obj.getAmountForSale(),
                    obj.getDesProperty(), obj.getAmountDesired(), obj.getAmountRemaining());
                    vecMetaDExTrades.push_back(std::make_pair(obj.getHash(), dataStr));
            }
        }
    }
    std::sort (vecMetaDExTrades.begin(), vecMetaDExTrades.end());
    for (std::vector<std::pair<uint256, std::string> >::iterator it = vecMetaDExTrades.begin(); it != vecMetaDExTrades.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID)
    // Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to
    // avoid additionalal loading of SP entries from the database
    // Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
    std::vector<std::pair<uint32_t, std::string> > vecCrowds;
    for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) {
        const CMPCrowd& crowd = it->second;
        uint32_t propertyId = crowd.getPropertyId();
        std::string dataStr = strprintf("%d|%d|%d|%d|%d",
            crowd.getPropertyId(), crowd.getCurrDes(), crowd.getDeadline(), crowd.getUserCreated(), crowd.getIssuerCreated());
        vecCrowds.push_back(std::make_pair(propertyId, dataStr));
    }
    std::sort (vecCrowds.begin(), vecCrowds.end());
    for (std::vector<std::pair<uint32_t, std::string> >::iterator it = vecCrowds.begin(); it != vecCrowds.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // Properties - add the next available property ID in both the main and test ecosystems
    // Placeholders: "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
    std::string dataStr = strprintf("%d|%d", _my_sps->peekNextSPID(1), _my_sps->peekNextSPID(2));
    if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr);
    SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());

    // extract the final result and return the hash
    uint256 consensusHash;
    SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
    if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash.  Result: %s\n", consensusHash.GetHex());

    return consensusHash;
}

} // namespace mastercore
<commit_msg>Remove reserved amounts from DEx sell data added to consensus hash<commit_after>/**
 * @file consensushash.cpp
 *
 * This file contains the function to generate consensus hashes.
 */

#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/mdex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"

#include <stdint.h>
#include <string>

#include <openssl/sha.h>

namespace mastercore
{
/**
 * Obtains a hash of the active state to use for consensus verification and checkpointing.
 *
 * For increased flexibility, so other implementations like OmniWallet and OmniChest can
 * also apply this methodology without necessarily using the same exact data types (which
 * would be needed to hash the data bytes directly), create a string in the following
 * format for each entry to use for hashing:
 *
 * ---STAGE 1 - BALANCES---
 * Format specifiers & placeholders:
 *   "%s|%d|%d|%d|%d|%d" - "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
 *
 * Note: empty balance records and the pending tally are ignored. Addresses are sorted based
 * on lexicographical order, and balance records are sorted by the property identifiers.
 *
 * ---STAGE 2 - DEX SELL OFFERS---
 * Format specifiers & placeholders:
 *   "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit"
 *
 * Note: ordered ascending by txid.
 *
 * ---STAGE 3 - DEX ACCEPTS---
 * Format specifiers & placeholders:
 *   "%s|%s|%d|%d|%d" - "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
 *
 * Note: ordered ascending by matchedselloffertxid followed by buyer.
 *
 * ---STAGE 4 - METADEX TRADES---
 * Format specifiers & placeholders:
 *   "%s|%s|%d|%d|%d|%d|%d" - "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
 *
 * Note: ordered ascending by txid.
 *
 * ---STAGE 5 - CROWDSALES---
 * Format specifiers & placeholders:
 *   "%d|%d|%d|%d|%d" - "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
 *
 * Note: ordered by property ID.
 *
 * ---STAGE 6 - PROPERTIES---
 * Format specifiers & placeholders:
 *   "%d|%d" - "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
 *
 * The byte order is important, and we assume:
 *   SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
 *
 */
uint256 GetConsensusHash()
{
    // allocate and init a SHA256_CTX
    SHA256_CTX shaCtx;
    SHA256_Init(&shaCtx);

    LOCK(cs_tally);

    if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");

    // Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
    // Placeholders:  "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
    for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
        const std::string& address = my_it->first;
        CMPTally& tally = my_it->second;
        tally.init();
        uint32_t propertyId = 0;
        while (0 != (propertyId = (tally.next()))) {
            int64_t balance = tally.getMoney(propertyId, BALANCE);
            int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
            int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
            int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);

            // skip this entry if all balances are empty
            if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;

            std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
                    address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
            if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
            SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
        }
    }

    // DEx sell offers - loop through the DEx and add each sell offer to the consensus hash (ordered by txid)
    // Placeholders: "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit"
    std::vector<std::pair<uint256, std::string> > vecDExOffers;
    for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
        const CMPOffer& selloffer = it->second;
        const std::string& sellCombo = it->first;
        uint32_t propertyId = selloffer.getProperty();
        std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
        std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
                selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
                selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit());
        vecDExOffers.push_back(std::make_pair(selloffer.getHash(), dataStr));
    }
    std::sort (vecDExOffers.begin(), vecDExOffers.end());
    for (std::vector<std::pair<uint256, std::string> >::iterator it = vecDExOffers.begin(); it != vecDExOffers.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // DEx accepts - loop through the accepts map and add each accept to the consensus hash (ordered by matchedtxid then buyer)
    // Placeholders: "matchedselloffertxid|buyer|acceptamount|acceptamountremaining|acceptblock"
    std::vector<std::pair<std::string, std::string> > vecAccepts;
    for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) {
        const CMPAccept& accept = it->second;
        const std::string& acceptCombo = it->first;
        std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1)));
        std::string dataStr = strprintf("%s|%s|%d|%d|%d",
                accept.getHash().GetHex(), buyer, accept.getAcceptAmount(), accept.getAcceptAmountRemaining(), accept.getAcceptBlock());
        std::string sortKey = strprintf("%s-%s", accept.getHash().GetHex(), buyer);
        vecAccepts.push_back(std::make_pair(sortKey, dataStr));
    }
    std::sort (vecAccepts.begin(), vecAccepts.end());
    for (std::vector<std::pair<std::string, std::string> >::iterator it = vecAccepts.begin(); it != vecAccepts.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash (ordered by txid)
    // Placeholders: "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
    std::vector<std::pair<uint256, std::string> > vecMetaDExTrades;
    for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
        const md_PricesMap& prices = my_it->second;
        for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) {
            const md_Set& indexes = it->second;
            for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
                const CMPMetaDEx& obj = *it;
                std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
                    obj.getHash().GetHex(), obj.getAddr(), obj.getProperty(), obj.getAmountForSale(),
                    obj.getDesProperty(), obj.getAmountDesired(), obj.getAmountRemaining());
                    vecMetaDExTrades.push_back(std::make_pair(obj.getHash(), dataStr));
            }
        }
    }
    std::sort (vecMetaDExTrades.begin(), vecMetaDExTrades.end());
    for (std::vector<std::pair<uint256, std::string> >::iterator it = vecMetaDExTrades.begin(); it != vecMetaDExTrades.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID)
    // Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to
    // avoid additionalal loading of SP entries from the database
    // Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
    std::vector<std::pair<uint32_t, std::string> > vecCrowds;
    for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) {
        const CMPCrowd& crowd = it->second;
        uint32_t propertyId = crowd.getPropertyId();
        std::string dataStr = strprintf("%d|%d|%d|%d|%d",
            crowd.getPropertyId(), crowd.getCurrDes(), crowd.getDeadline(), crowd.getUserCreated(), crowd.getIssuerCreated());
        vecCrowds.push_back(std::make_pair(propertyId, dataStr));
    }
    std::sort (vecCrowds.begin(), vecCrowds.end());
    for (std::vector<std::pair<uint32_t, std::string> >::iterator it = vecCrowds.begin(); it != vecCrowds.end(); ++it) {
        std::string dataStr = (*it).second;
        if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr);
        SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
    }

    // Properties - add the next available property ID in both the main and test ecosystems
    // Placeholders: "nextavailablepropertyidmaineco|nextavailablepropertyidtesteco"
    std::string dataStr = strprintf("%d|%d", _my_sps->peekNextSPID(1), _my_sps->peekNextSPID(2));
    if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr);
    SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());

    // extract the final result and return the hash
    uint256 consensusHash;
    SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
    if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash.  Result: %s\n", consensusHash.GetHex());

    return consensusHash;
}

} // namespace mastercore
<|endoftext|>