<commit_before>#include <Refal2.h>

namespace Refal2 {

//-----------------------------------------------------------------------------
// CProgram

CProgram::CProgram( int numberOfModules ) :
	modulesSize( numberOfModules ),
	modules( new CRuntimeModule[modulesSize] )
{
	assert( modulesSize > 0 );
	assert( modules != nullptr );
}

CProgram::~CProgram()
{
	delete[] modules;
}

CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId )
{
	assert( moduleId >= 0 && moduleId < modulesSize );
	return modules[moduleId];
}

//-----------------------------------------------------------------------------
// Standart embedded functions

static void notImplemented( const char* name )
{
	std::cout << "external function `" << name << "` not implemented yet.";
}

static bool embeddedPrint()
{
	notImplemented( __FUNCTION__ );
	return false;
}

static bool embeddedPrintm()
{
	notImplemented( __FUNCTION__ );
	return false;
}

static bool embeddedProut()
{
	notImplemented( __FUNCTION__ );
	return false;
}

static bool embeddedProutm()
{
	notImplemented( __FUNCTION__ );
	return false;
}

//-----------------------------------------------------------------------------
// CStandartEmbeddedFunctionData

struct CStandartEmbeddedFunctionData {
	const char* const externalName;
	const TEmbeddedFunctionPtr EmbeddedFunction;
};

const CStandartEmbeddedFunctionData standartEmbeddedFunctions[] = {
	{ "print", embeddedPrint },
	{ "printm", embeddedPrintm },
	{ "prout", embeddedProut },
	{ "proutm", embeddedProutm },
	{ nullptr, nullptr }
};

//-----------------------------------------------------------------------------
// CGlobalFunctionData

class CGlobalFunctionData {
public:
	CGlobalFunctionData() :
		preparatoryFunction( nullptr ),
		embeddedFunction( nullptr ),
		runtimeModuleId( 0 )
	{
	}

	bool IsEmbeddedFunction() const
	{
		return ( embeddedFunction != nullptr );
	}

	bool IsPreparatoryFunction() const
	{
		return ( preparatoryFunction != nullptr );
	}

	bool IsDefined() const
	{
		return ( IsEmbeddedFunction() || IsPreparatoryFunction() );
	}

	void SetPreparatoryFunction(
		const CPreparatoryFunction* const _preparatoryFunction,
		const TRuntimeModuleId _runtimeModuleId )
	{
		assert( !IsDefined() );
		assert( _preparatoryFunction != nullptr );
		preparatoryFunction = _preparatoryFunction;
		runtimeModuleId = _runtimeModuleId;
	}

	const CPreparatoryFunction* PreparatoryFunction() const
	{
		assert( IsPreparatoryFunction() );
		return preparatoryFunction;
	}

	const TRuntimeModuleId RuntimeModuleId() const
	{
		assert( IsPreparatoryFunction() );
		return runtimeModuleId;
	}

	void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction )
	{
		assert( !IsDefined() );
		assert( _embeddedFunction != nullptr );
		embeddedFunction = _embeddedFunction;
	}

	TEmbeddedFunctionPtr EmbeddedFunction() const
	{
		assert( IsEmbeddedFunction() );
		return embeddedFunction;
	}

private:
	const CPreparatoryFunction* preparatoryFunction;
	TEmbeddedFunctionPtr embeddedFunction;
	TRuntimeModuleId runtimeModuleId;
};

//-----------------------------------------------------------------------------
// CExternalFunctionData

class CExternalFunctionData {
public:
	CExternalFunctionData( int _globalIndex,
			CPreparatoryFunction* _preparatoryFunction ) :
		globalIndex( _globalIndex ),
		preparatoryFunction( _preparatoryFunction )
	{
		assert( globalIndex >= 0 );
		assert( preparatoryFunction != nullptr );
	}

	int GlobalIndex() const { return globalIndex; }
	CPreparatoryFunction* PreparatoryFunction() const
		{ return preparatoryFunction; }

private:
	int globalIndex;
	CPreparatoryFunction* preparatoryFunction;
};

//-----------------------------------------------------------------------------
// CPreparatoryRuntimeFunction

class CPreparatoryRuntimeFunction : public CRuntimeFunction {
public:
	CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& function,
		const TRuntimeModuleId moduleId );

	CPreparatoryFunction* PreparatoryFunction() const { return function.get(); }
	TRuntimeModuleId RuntimeModuleId() const { return moduleId; }

private:
	const CPreparatoryFunctionPtr function;
	const TRuntimeModuleId moduleId;

	static TRuntimeFunctionType convertType(
		const CPreparatoryFunction* const function );
};

CPreparatoryRuntimeFunction::CPreparatoryRuntimeFunction(
		CPreparatoryFunctionPtr& _function, const TRuntimeModuleId _moduleId ) :
CRuntimeFunction( convertType( _function.get() ) ),
	function( _function.release() ),
	moduleId( _moduleId )
{
}

TRuntimeFunctionType CPreparatoryRuntimeFunction::convertType(
	const CPreparatoryFunction* const function )
{
	assert( function != nullptr );
	switch( function->GetType() ) {
		case PFT_Ordinary:
			return RFT_Ordinary;
		case PFT_Empty:
			return RFT_Empty;
		case PFT_External:
			return RFT_External;
		case PFT_Declared:
		case PFT_Defined:
		case PFT_Compiled:
		case PFT_Embedded:
		default:
			break;
	}
	assert( false );
	return RFT_Empty;
}

//-----------------------------------------------------------------------------
// CInternalProgramBuilder

class CInternalProgramBuilder {
public:
	static CProgramPtr Build( CModuleDataVector& modules,
		CErrorsHelper& errors );

private:
	CErrorsHelper& errors;
	typedef std::vector<CExternalFunctionData> CExternals;
	CExternals externals;
	CDictionary<CGlobalFunctionData, std::string> globals;
	CProgramPtr program;

	CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules );

	void addFunction( CPreparatoryFunction* function,
		const TRuntimeModuleId runtimeModuleId );
	void addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule,
		const TRuntimeModuleId runtimeModuleId );
	void collect( CModuleDataVector& modules );
	void check();
	void compile();
	void link();
};

//-----------------------------------------------------------------------------

CInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors,
		int numberOfModules ) :
	errors( _errors ),
	program( new CProgram( numberOfModules ) )
{
	assert( static_cast<bool>( program ) );
	for( int i = 0; standartEmbeddedFunctions[i].EmbeddedFunction != nullptr;
		i++ )
	{
		assert( standartEmbeddedFunctions[i].externalName != nullptr );
		std::string externalName = standartEmbeddedFunctions[i].externalName;
		assert( !externalName.empty() );
		const int globalIndex = globals.AddKey( externalName );
		CGlobalFunctionData& global = globals.GetData( globalIndex );
		global.SetEmbeddedFunction(
			standartEmbeddedFunctions[i].EmbeddedFunction );
	}
}

CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules,
	CErrorsHelper& errors )
{
	assert( !errors.HasErrors() );
	assert( !modules.empty() );
	CInternalProgramBuilder builder( errors, modules.size() );
	builder.collect( modules );
	if( errors.HasErrors() ) {
		return nullptr;
	}
	builder.check();
	if( errors.HasErrors() ) {
		return nullptr;
	}
	builder.compile();
	assert( !errors.HasErrors() );
	builder.link();
	assert( !errors.HasErrors() );
	return CProgramPtr( builder.program.release() );
}

void CInternalProgramBuilder::addFunction( CPreparatoryFunction* function,
	const TRuntimeModuleId runtimeModuleId )
{
	const bool isExternal = function->IsExternal();
	const bool isGlobal = function->IsEntry();
	if( !( isExternal || isGlobal ) ) {
		return;
	}
	const int globalIndex = globals.AddKey( function->ExternalName() );
	if( isGlobal ) {
		assert( !isExternal );
		CGlobalFunctionData& global = globals.GetData( globalIndex );
		if( global.IsDefined() ) {
			std::ostringstream stringStream;
			stringStream << "function with external name `"
				<< function->ExternalNameToken().word
				<< "` already defined in program";
			errors.Error( stringStream.str() );
		} else {
			global.SetPreparatoryFunction( function, runtimeModuleId );
		}
	} else {
		assert( isExternal );
		externals.push_back( CExternalFunctionData( globalIndex, function ) );
	}
}
void CInternalProgramBuilder::addFunctions( const CModuleData& module,
	CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId )
{
	const CPreparatoryFunctions& functions = module.Functions;
	for( int i = 0; i < functions.Size(); i++ ) {
		CPreparatoryFunctionPtr function( functions.GetData( i ).release() );
		addFunction( function.get(), runtimeModuleId );
		CRuntimeFunctionPtr& runtimeFunction = runtimeModule.Functions.GetData(
			runtimeModule.Functions.AddKey( function->Name() ) );
		assert( !static_cast<bool>( runtimeFunction ) );
		runtimeFunction.reset( new CPreparatoryRuntimeFunction( function,
			runtimeModuleId ) );
	}
}

void CInternalProgramBuilder::collect( CModuleDataVector& modules )
{
	TRuntimeModuleId currentModuleId = 0;
	for( CModuleDataVector::const_iterator module = modules.begin();
		module != modules.end(); ++module )
	{
		addFunctions( *( *module ), program->Module( currentModuleId ),
			currentModuleId );
		currentModuleId++;
	}
	modules.clear();
}

void CInternalProgramBuilder::check()
{
	for( CExternals::const_iterator	function = externals.begin();
		function != externals.end(); ++function )
	{
		const int globalIndex = function->GlobalIndex();
		if( !globals.GetData( globalIndex ).IsDefined() ) {
			std::ostringstream stringStream;
			stringStream << "function with external name `"
				<< globals.GetKey( globalIndex )
				<< "` was not defined in program";
			errors.Error( stringStream.str() );
		}
	}
}

void CInternalProgramBuilder::compile()
{
	CFunctionCompiler compiler;
	for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ )
	{
		const CRuntimeFunctions& functions =
			program->Module( moduleId ).Functions;
		for( int i = 0; i < functions.Size(); i++ ) {
			const CRuntimeFunction& runtimeFunction = *functions.GetData( i );
			const CPreparatoryRuntimeFunction& function = static_cast<
				const CPreparatoryRuntimeFunction&>( runtimeFunction );
			if( function.PreparatoryFunction()->IsOrdinary() ) {
				function.PreparatoryFunction()->Compile( compiler );
			}
		}
	}
}

void CInternalProgramBuilder::link()
{
	for( CExternals::iterator function = externals.begin();
		function != externals.end(); ++function )
	{
		function->PreparatoryFunction();
		const int globalIndex = function->GlobalIndex();
		const CGlobalFunctionData& global = globals.GetData( globalIndex );
		assert( global.IsDefined() );
		if( global.IsEmbeddedFunction() ) {
			function->PreparatoryFunction()->SetEmbedded(
				global.EmbeddedFunction() );
		} else {
			assert( !global.IsPreparatoryFunction() );
			function->PreparatoryFunction()->Link(
				*global.PreparatoryFunction() );
		}
	}

	for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ )
	{
		const CRuntimeFunctions& functions =
			program->Module( moduleId ).Functions;
		for( int i = 0; i < functions.Size(); i++ ) {
			const CPreparatoryRuntimeFunction& function = static_cast<
				CPreparatoryRuntimeFunction&>( *functions.GetData( i ) );
			const CPreparatoryFunction* preparatoryFunction =
				function.PreparatoryFunction();
			CRuntimeFunctionPtr newRuntimeFunction;
			switch( function.Type() ) {
				case RFT_Empty:
					assert( preparatoryFunction->IsEmpty() );
					newRuntimeFunction.reset( new CEmptyFunction );
					break;
				case RFT_Embedded:
					assert( preparatoryFunction->IsEmbedded() );
					newRuntimeFunction.reset( new CEmbeddedFunction(
						preparatoryFunction->EmbeddedFunction() ) );
					break;
				case RFT_External:
					assert( preparatoryFunction->IsEmpty()
						|| preparatoryFunction->IsEmbedded()
						|| preparatoryFunction->IsOrdinary() );
					// todo: ---
					newRuntimeFunction.reset( new CExternalFunction( 0,
						function.RuntimeModuleId() ) );
					break;
				case RFT_Ordinary:
					assert( preparatoryFunction->IsOrdinary() );
					// todo: ---
					newRuntimeFunction.reset( new COrdinaryFunction( 0 ) );
					break;
				default:
					assert( false );
					break;
			}
		}
	}
}

//-----------------------------------------------------------------------------
// CProgramBuilder

CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) :
	CFunctionBuilder( errorHandler )
{
	Reset();
}

void CProgramBuilder::Reset()
{
	CFunctionBuilder::Reset();
}

void CProgramBuilder::AddModule( CModuleDataPtr& module )
{
	modules.push_back( CModuleDataPtr( module.release() ) );
}

void CProgramBuilder::BuildProgram()
{
	CInternalProgramBuilder::Build( modules, *this );
}

//-----------------------------------------------------------------------------

} // end of namespace Refal2
<commit_msg>error fixes<commit_after>#include <Refal2.h>

namespace Refal2 {

//-----------------------------------------------------------------------------
// CProgram

CProgram::CProgram( int numberOfModules ) :
	modulesSize( numberOfModules ),
	modules( new CRuntimeModule[modulesSize] )
{
	assert( modulesSize > 0 );
	assert( modules != nullptr );
}

CProgram::~CProgram()
{
	delete[] modules;
}

CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId )
{
	assert( moduleId >= 0 && moduleId < modulesSize );
	return modules[moduleId];
}

//-----------------------------------------------------------------------------
// Standart embedded functions

static void notImplemented( const char* name )
{
	std::cout << "external function `" << name << "` not implemented yet.";
}

static bool embeddedPrint()
{
	notImplemented( __FUNCTION__ );
	return false;
}

static bool embeddedPrintm()
{
	notImplemented( __FUNCTION__ );
	return false;
}

static bool embeddedProut()
{
	notImplemented( __FUNCTION__ );
	return false;
}

static bool embeddedProutm()
{
	notImplemented( __FUNCTION__ );
	return false;
}

//-----------------------------------------------------------------------------
// CStandartEmbeddedFunctionData

struct CStandartEmbeddedFunctionData {
	const char* const externalName;
	const TEmbeddedFunctionPtr EmbeddedFunction;
};

const CStandartEmbeddedFunctionData standartEmbeddedFunctions[] = {
	{ "print", embeddedPrint },
	{ "printm", embeddedPrintm },
	{ "prout", embeddedProut },
	{ "proutm", embeddedProutm },
	{ nullptr, nullptr }
};

//-----------------------------------------------------------------------------
// CGlobalFunctionData

class CGlobalFunctionData {
public:
	CGlobalFunctionData() :
		preparatoryFunction( nullptr ),
		embeddedFunction( nullptr ),
		runtimeModuleId( 0 )
	{
	}

	bool IsEmbeddedFunction() const
	{
		return ( embeddedFunction != nullptr );
	}

	bool IsPreparatoryFunction() const
	{
		return ( preparatoryFunction != nullptr );
	}

	bool IsDefined() const
	{
		return ( IsEmbeddedFunction() || IsPreparatoryFunction() );
	}

	void SetPreparatoryFunction(
		const CPreparatoryFunction* const _preparatoryFunction,
		const TRuntimeModuleId _runtimeModuleId )
	{
		assert( !IsDefined() );
		assert( _preparatoryFunction != nullptr );
		preparatoryFunction = _preparatoryFunction;
		runtimeModuleId = _runtimeModuleId;
	}

	const CPreparatoryFunction* PreparatoryFunction() const
	{
		assert( IsPreparatoryFunction() );
		return preparatoryFunction;
	}

	const TRuntimeModuleId RuntimeModuleId() const
	{
		assert( IsPreparatoryFunction() );
		return runtimeModuleId;
	}

	void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction )
	{
		assert( !IsDefined() );
		assert( _embeddedFunction != nullptr );
		embeddedFunction = _embeddedFunction;
	}

	TEmbeddedFunctionPtr EmbeddedFunction() const
	{
		assert( IsEmbeddedFunction() );
		return embeddedFunction;
	}

private:
	const CPreparatoryFunction* preparatoryFunction;
	TEmbeddedFunctionPtr embeddedFunction;
	TRuntimeModuleId runtimeModuleId;
};

//-----------------------------------------------------------------------------
// CExternalFunctionData

class CExternalFunctionData {
public:
	CExternalFunctionData( int _globalIndex,
			CPreparatoryFunction* _preparatoryFunction ) :
		globalIndex( _globalIndex ),
		preparatoryFunction( _preparatoryFunction )
	{
		assert( globalIndex >= 0 );
		assert( preparatoryFunction != nullptr );
	}

	int GlobalIndex() const { return globalIndex; }
	CPreparatoryFunction* PreparatoryFunction() const
		{ return preparatoryFunction; }

private:
	int globalIndex;
	CPreparatoryFunction* preparatoryFunction;
};

//-----------------------------------------------------------------------------
// CPreparatoryRuntimeFunction

class CPreparatoryRuntimeFunction : public CRuntimeFunction {
public:
	CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& function,
		const TRuntimeModuleId moduleId );

	CPreparatoryFunction* PreparatoryFunction() const { return function.get(); }
	TRuntimeModuleId RuntimeModuleId() const { return moduleId; }

private:
	const CPreparatoryFunctionPtr function;
	const TRuntimeModuleId moduleId;

	static TRuntimeFunctionType convertType(
		const CPreparatoryFunction* const function );
};

CPreparatoryRuntimeFunction::CPreparatoryRuntimeFunction(
		CPreparatoryFunctionPtr& _function, const TRuntimeModuleId _moduleId ) :
CRuntimeFunction( convertType( _function.get() ) ),
	function( _function.release() ),
	moduleId( _moduleId )
{
}

TRuntimeFunctionType CPreparatoryRuntimeFunction::convertType(
	const CPreparatoryFunction* const function )
{
	assert( function != nullptr );
	switch( function->GetType() ) {
		case PFT_Ordinary:
			return RFT_Ordinary;
		case PFT_Empty:
			return RFT_Empty;
		case PFT_External:
			return RFT_External;
		case PFT_Declared:
		case PFT_Defined:
		case PFT_Compiled:
		case PFT_Embedded:
		default:
			break;
	}
	assert( false );
	return RFT_Empty;
}

//-----------------------------------------------------------------------------
// CInternalProgramBuilder

class CInternalProgramBuilder {
public:
	static CProgramPtr Build( CModuleDataVector& modules,
		CErrorsHelper& errors );

private:
	CErrorsHelper& errors;
	typedef std::vector<CExternalFunctionData> CExternals;
	CExternals externals;
	CDictionary<CGlobalFunctionData, std::string> globals;
	CProgramPtr program;

	CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules );

	void addFunction( CPreparatoryFunction* function,
		const TRuntimeModuleId runtimeModuleId );
	void addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule,
		const TRuntimeModuleId runtimeModuleId );
	void collect( CModuleDataVector& modules );
	void check();
	void compile();
	void link();
};

//-----------------------------------------------------------------------------

CInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors,
		int numberOfModules ) :
	errors( _errors ),
	program( new CProgram( numberOfModules ) )
{
	assert( static_cast<bool>( program ) );
	for( int i = 0; standartEmbeddedFunctions[i].EmbeddedFunction != nullptr;
		i++ )
	{
		assert( standartEmbeddedFunctions[i].externalName != nullptr );
		std::string externalName = standartEmbeddedFunctions[i].externalName;
		assert( !externalName.empty() );
		const int globalIndex = globals.AddKey( externalName );
		CGlobalFunctionData& global = globals.GetData( globalIndex );
		global.SetEmbeddedFunction(
			standartEmbeddedFunctions[i].EmbeddedFunction );
	}
}

CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules,
	CErrorsHelper& errors )
{
	assert( !errors.HasErrors() );
	assert( !modules.empty() );
	CInternalProgramBuilder builder( errors, modules.size() );
	builder.collect( modules );
	if( errors.HasErrors() ) {
		return nullptr;
	}
	builder.check();
	if( errors.HasErrors() ) {
		return nullptr;
	}
	builder.compile();
	assert( !errors.HasErrors() );
	builder.link();
	assert( !errors.HasErrors() );
	return CProgramPtr( builder.program.release() );
}

void CInternalProgramBuilder::addFunction( CPreparatoryFunction* function,
	const TRuntimeModuleId runtimeModuleId )
{
	const bool isExternal = function->IsExternal();
	const bool isGlobal = function->IsEntry();
	if( !( isExternal || isGlobal ) ) {
		return;
	}
	const int globalIndex = globals.AddKey( function->ExternalName() );
	if( isGlobal ) {
		assert( !isExternal );
		CGlobalFunctionData& global = globals.GetData( globalIndex );
		if( global.IsDefined() ) {
			std::ostringstream stringStream;
			stringStream << "function with external name `"
				<< function->ExternalNameToken().word
				<< "` already defined in program";
			errors.Error( stringStream.str() );
		} else {
			global.SetPreparatoryFunction( function, runtimeModuleId );
		}
	} else {
		assert( isExternal );
		externals.push_back( CExternalFunctionData( globalIndex, function ) );
	}
}
void CInternalProgramBuilder::addFunctions( const CModuleData& module,
	CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId )
{
	const CPreparatoryFunctions& functions = module.Functions;
	for( int i = 0; i < functions.Size(); i++ ) {
		CPreparatoryFunctionPtr function( functions.GetData( i ).release() );
		addFunction( function.get(), runtimeModuleId );
		CRuntimeFunctionPtr& runtimeFunction = runtimeModule.Functions.GetData(
			runtimeModule.Functions.AddKey( function->Name() ) );
		assert( !static_cast<bool>( runtimeFunction ) );
		runtimeFunction.reset( new CPreparatoryRuntimeFunction( function,
			runtimeModuleId ) );
	}
}

void CInternalProgramBuilder::collect( CModuleDataVector& modules )
{
	TRuntimeModuleId currentModuleId = 0;
	for( CModuleDataVector::const_iterator module = modules.begin();
		module != modules.end(); ++module )
	{
		addFunctions( *( *module ), program->Module( currentModuleId ),
			currentModuleId );
		currentModuleId++;
	}
	modules.clear();
}

void CInternalProgramBuilder::check()
{
	for( CExternals::const_iterator	function = externals.begin();
		function != externals.end(); ++function )
	{
		const int globalIndex = function->GlobalIndex();
		if( !globals.GetData( globalIndex ).IsDefined() ) {
			std::ostringstream stringStream;
			stringStream << "function with external name `"
				<< globals.GetKey( globalIndex )
				<< "` was not defined in program";
			errors.Error( stringStream.str() );
		}
	}
}

void CInternalProgramBuilder::compile()
{
	CFunctionCompiler compiler;
	for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ )
	{
		const CRuntimeFunctions& functions =
			program->Module( moduleId ).Functions;
		for( int i = 0; i < functions.Size(); i++ ) {
			const CRuntimeFunction& runtimeFunction = *functions.GetData( i );
			const CPreparatoryRuntimeFunction& function = static_cast<
				const CPreparatoryRuntimeFunction&>( runtimeFunction );
			if( function.PreparatoryFunction()->IsOrdinary() ) {
				function.PreparatoryFunction()->Compile( compiler );
			}
		}
	}
}

void CInternalProgramBuilder::link()
{
	for( CExternals::iterator function = externals.begin();
		function != externals.end(); ++function )
	{
		function->PreparatoryFunction();
		const int globalIndex = function->GlobalIndex();
		const CGlobalFunctionData& global = globals.GetData( globalIndex );
		assert( global.IsDefined() );
		if( global.IsEmbeddedFunction() ) {
			function->PreparatoryFunction()->SetEmbedded(
				global.EmbeddedFunction() );
		} else {
			assert( !global.IsPreparatoryFunction() );
			function->PreparatoryFunction()->Link(
				*global.PreparatoryFunction() );
		}
	}

	for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ )
	{
		const CRuntimeFunctions& functions =
			program->Module( moduleId ).Functions;
		for( int i = 0; i < functions.Size(); i++ ) {
			const CPreparatoryRuntimeFunction& function = static_cast<
				CPreparatoryRuntimeFunction&>( *functions.GetData( i ) );
			const CPreparatoryFunction* preparatoryFunction =
				function.PreparatoryFunction();
			CRuntimeFunctionPtr newRuntimeFunction;
			switch( function.Type() ) {
				case RFT_Empty:
					assert( preparatoryFunction->IsEmpty() );
					newRuntimeFunction.reset( new CEmptyFunction );
					break;
				case RFT_Embedded:
					assert( preparatoryFunction->IsEmbedded() );
					newRuntimeFunction.reset( new CEmbeddedFunction(
						preparatoryFunction->EmbeddedFunction() ) );
					break;
				case RFT_External:
					assert( preparatoryFunction->IsEmpty()
						|| preparatoryFunction->IsEmbedded()
						|| preparatoryFunction->IsCompiled() );
					// todo: ---
					//newRuntimeFunction.reset( new CExternalFunction( 0,
					//	function.RuntimeModuleId() ) );
					break;
				case RFT_Ordinary:
					assert( preparatoryFunction->IsCompiled() );
					// todo: ---
					//newRuntimeFunction.reset( new COrdinaryFunction( 0 ) );
					break;
				default:
					assert( false );
					break;
			}
			functions.GetData( i ).reset( newRuntimeFunction.release() );
		}
	}
}

//-----------------------------------------------------------------------------
// CProgramBuilder

CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) :
	CFunctionBuilder( errorHandler )
{
	Reset();
}

void CProgramBuilder::Reset()
{
	CFunctionBuilder::Reset();
}

void CProgramBuilder::AddModule( CModuleDataPtr& module )
{
	modules.push_back( CModuleDataPtr( module.release() ) );
}

void CProgramBuilder::BuildProgram()
{
	CInternalProgramBuilder::Build( modules, *this );
}

//-----------------------------------------------------------------------------

} // end of namespace Refal2
<|endoftext|>


<commit_before>#include <nan.h>
#include "Packers.h"
#include "Memory.h"

namespace streampunk {

void dumpPGroupRaw (uint8_t *pgbuf, uint32_t width, uint32_t numLines) {
  uint8_t *buf = pgbuf;
  for (uint32_t i = 0; i < numLines; ++i) {
    printf("PGroup Line%02d: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n",
      i, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9]);
    buf += width * 5 / 2;
  }
}

void dump420P (uint8_t *buf, uint32_t width, uint32_t height, uint32_t numLines) {
  uint8_t *ybuf = buf;
  uint8_t *ubuf = ybuf + width * height;
  uint8_t *vbuf = ubuf + width * height / 4;
  for (uint32_t i = 0; i < numLines; ++i) {
    printf("420P Line %02d: Y: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n",
      i, ybuf[0], ybuf[1], ybuf[2], ybuf[3], ybuf[4], ybuf[5], ybuf[6], ybuf[7]);
    ybuf += width;
    if ((i & 1) == 0) {
      printf("420P Line %02d: U: %02x,     %02x,     %02x,     %02x\n",
        i, ubuf[0], ubuf[1], ubuf[2], ubuf[3]);
      printf("420P Line %02d: V: %02x,     %02x,     %02x,     %02x\n",
        i, vbuf[0], vbuf[1], vbuf[2], vbuf[3]);
      ubuf += width / 2;
      vbuf += width / 2;
    }
  }
}

Packers::Packers(uint32_t srcWidth, uint32_t srcHeight, const std::string& srcFmtCode, uint32_t srcBytes, const std::string& dstFmtCode)
  : mSrcWidth(srcWidth), mSrcHeight(srcHeight), mSrcFmtCode(srcFmtCode), mSrcBytes(srcBytes), mDstFmtCode(dstFmtCode) {

  if (0 == mSrcFmtCode.compare("4175")) {
    uint32_t srcPitchBytes = mSrcWidth * 5 / 2;
    if (srcPitchBytes * mSrcHeight > mSrcBytes) {
      Nan::ThrowError("insufficient source buffer for conversion\n");
    }
  }
  else if (0 == mSrcFmtCode.compare("v210")) {
    uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3;
    if ((mSrcWidth * 5 / 2) * mSrcHeight > mSrcBytes) {
      Nan::ThrowError("insufficient source buffer for conversion\n");
    }
  }
  else
    Nan::ThrowError("unsupported source packing type\n");

  if (0 != mDstFmtCode.compare("420P"))
    Nan::ThrowError("unsupported destination packing type\n");
}

std::shared_ptr<Memory> Packers::concatBuffers(const tBufVec& bufVec) {
  std::shared_ptr<Memory> concatBuf = Memory::makeNew(mSrcBytes);
  uint32_t concatBufOffset = 0;
  for (tBufVec::const_iterator it = bufVec.begin(); it != bufVec.end(); ++it) {
    const uint8_t* buf = it->first;
    uint32_t len = it->second;
    memcpy (concatBuf->buf() + concatBufOffset, buf, len);
    concatBufOffset += len;
  }
  return concatBuf;
}

std::shared_ptr<Memory> Packers::convert(std::shared_ptr<Memory> srcBuf) {
  // only 420P supported currently
  uint32_t lumaBytes = mSrcWidth * mSrcHeight;
  std::shared_ptr<Memory> convertBuf = Memory::makeNew(lumaBytes * 3 / 2);
  if (0 == mSrcFmtCode.compare("4175")) {
    convertPGroupto420P (srcBuf->buf(), convertBuf->buf());
  }
  else if (0 == mSrcFmtCode.compare("v210")) {
    convertV210to420P (srcBuf->buf(), convertBuf->buf());
  }
  return convertBuf;
}

// private
void Packers::convertPGroupto420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) {
  uint32_t srcPitchBytes = mSrcWidth * 5 / 2;
  uint32_t dstLumaPitchBytes = mSrcWidth;
  uint32_t dstChromaPitchBytes = mSrcWidth / 2;
  uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight;

  const uint8_t *srcLine = srcBuf;
  uint8_t *dstYLine = dstBuf;
  uint8_t *dstULine = dstBuf + dstLumaPlaneBytes;
  uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4;

  for (uint32_t y=0; y<mSrcHeight; ++y) {
    const uint8_t *srcBytes = srcLine;
    uint8_t *dstYBytes = dstYLine;
    uint8_t *dstUBytes = dstULine;
    uint8_t *dstVBytes = dstVLine;
    bool evenLine = (y & 1) == 0;

    // read 5 source bytes / 2 source pixels at a time
    for (uint32_t x=0; x<mSrcWidth; x+=2) {
      uint8_t s0 = srcBytes[0];
      uint8_t s1 = srcBytes[1];
      uint8_t s2 = srcBytes[2];
      uint8_t s3 = srcBytes[3];
      uint8_t s4 = srcBytes[4];
      srcBytes += 5;

      dstYBytes[0] = ((s1 & 0x3f) << 2) | ((s2 & 0xc0) >> 6);
      dstYBytes[1] = ((s3 & 0x03) << 6) | ((s4 & 0xfc) >> 2);
      dstYBytes += 2;

      // chroma interp between lines
      dstUBytes[0] = evenLine ? s0 : (s0 + dstUBytes[0]) >> 1;
      dstUBytes += 1;
      uint32_t v0 = ((s2 & 0x0f) << 4) | ((s3 & 0xf0) >> 4);
      dstVBytes[0] = evenLine ? v0 : (v0 + dstVBytes[0]) >> 1;
      dstVBytes += 1;
    }

    srcLine += srcPitchBytes;
    dstYLine += dstLumaPitchBytes;
    if (evenLine) {
      dstULine += dstChromaPitchBytes;
      dstVLine += dstChromaPitchBytes;
    }
  }
}

void Packers::convertV210to420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) {
// V210: https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG8-V210__4_2_2_COMPRESSION_TYPE
// 420P: https://en.wikipedia.org/wiki/YUV
  uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3;
  uint32_t dstLumaPitchBytes = mSrcWidth;
  uint32_t dstChromaPitchBytes = mSrcWidth / 2;
  uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight;

  const uint8_t *srcLine = srcBuf;
  uint8_t *dstYLine = dstBuf;
  uint8_t *dstULine = dstBuf + dstLumaPlaneBytes;
  uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4;

  for (uint32_t y=0; y<mSrcHeight; ++y) {
    uint32_t *srcInts = (uint32_t *)srcLine;
    uint8_t *dstYBytes = dstYLine;
    uint8_t *dstUBytes = dstULine;
    uint8_t *dstVBytes = dstVLine;
    bool evenLine = (y & 1) == 0;

    // read 4 source ints / 6 source pixels at a time
    for (uint32_t x=0; x<mSrcWidth; x+=6) {
      uint32_t s0 = srcInts[0];
      uint32_t s1 = srcInts[1];
      uint32_t s2 = srcInts[2];
      uint32_t s3 = srcInts[3];
      srcInts += 4;

      dstYBytes[0] = (s0 >> 12) & 0xff;
      dstYBytes[1] = (s1 >>  2) & 0xff;
      dstYBytes[2] = (s1 >> 22) & 0xff;
      dstYBytes[3] = (s2 >> 12) & 0xff;
      dstYBytes[4] = (s3 >>  2) & 0xff;
      dstYBytes[5] = (s3 >> 22) & 0xff;
      dstYBytes += 6;

      dstUBytes[0] = evenLine ? ((s0 >>  2) & 0xff) : (((s0 >>  2) & 0xff) + dstUBytes[0]) >> 1;
      dstUBytes[1] = evenLine ? ((s1 >> 12) & 0xff) : (((s1 >> 12) & 0xff) + dstUBytes[1]) >> 1;
      dstUBytes[2] = evenLine ? ((s2 >> 22) & 0xff) : (((s2 >> 22) & 0xff) + dstUBytes[2]) >> 1;
      dstUBytes += 3;

      dstVBytes[0] = evenLine ? ((s0 >> 22) & 0xff) : (((s0 >> 22) & 0xff) + dstVBytes[0]) >> 1;
      dstVBytes[1] = evenLine ? ((s2 >>  2) & 0xff) : (((s2 >>  2) & 0xff) + dstVBytes[1]) >> 1;
      dstVBytes[2] = evenLine ? ((s3 >> 12) & 0xff) : (((s3 >> 12) & 0xff) + dstVBytes[2]) >> 1;
      dstVBytes += 3;
    }

    srcLine += srcPitchBytes;
    dstYLine += dstLumaPitchBytes;
    if (evenLine) {
      dstULine += dstChromaPitchBytes;
      dstVLine += dstChromaPitchBytes;
    }
  }
}

} // namespace streampunk
<commit_msg>Fix buffer size check<commit_after>#include <nan.h>
#include "Packers.h"
#include "Memory.h"

namespace streampunk {

void dumpPGroupRaw (uint8_t *pgbuf, uint32_t width, uint32_t numLines) {
  uint8_t *buf = pgbuf;
  for (uint32_t i = 0; i < numLines; ++i) {
    printf("PGroup Line%02d: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n",
      i, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9]);
    buf += width * 5 / 2;
  }
}

void dump420P (uint8_t *buf, uint32_t width, uint32_t height, uint32_t numLines) {
  uint8_t *ybuf = buf;
  uint8_t *ubuf = ybuf + width * height;
  uint8_t *vbuf = ubuf + width * height / 4;
  for (uint32_t i = 0; i < numLines; ++i) {
    printf("420P Line %02d: Y: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n",
      i, ybuf[0], ybuf[1], ybuf[2], ybuf[3], ybuf[4], ybuf[5], ybuf[6], ybuf[7]);
    ybuf += width;
    if ((i & 1) == 0) {
      printf("420P Line %02d: U: %02x,     %02x,     %02x,     %02x\n",
        i, ubuf[0], ubuf[1], ubuf[2], ubuf[3]);
      printf("420P Line %02d: V: %02x,     %02x,     %02x,     %02x\n",
        i, vbuf[0], vbuf[1], vbuf[2], vbuf[3]);
      ubuf += width / 2;
      vbuf += width / 2;
    }
  }
}

Packers::Packers(uint32_t srcWidth, uint32_t srcHeight, const std::string& srcFmtCode, uint32_t srcBytes, const std::string& dstFmtCode)
  : mSrcWidth(srcWidth), mSrcHeight(srcHeight), mSrcFmtCode(srcFmtCode), mSrcBytes(srcBytes), mDstFmtCode(dstFmtCode) {

  if (0 == mSrcFmtCode.compare("4175")) {
    uint32_t srcPitchBytes = mSrcWidth * 5 / 2;
    if (srcPitchBytes * mSrcHeight > mSrcBytes) {
      Nan::ThrowError("insufficient source buffer for conversion\n");
    }
  }
  else if (0 == mSrcFmtCode.compare("v210")) {
    uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3;
    if (srcPitchBytes * mSrcHeight > mSrcBytes) {
      Nan::ThrowError("insufficient source buffer for conversion\n");
    }
  }
  else
    Nan::ThrowError("unsupported source packing type\n");

  if (0 != mDstFmtCode.compare("420P"))
    Nan::ThrowError("unsupported destination packing type\n");
}

std::shared_ptr<Memory> Packers::concatBuffers(const tBufVec& bufVec) {
  std::shared_ptr<Memory> concatBuf = Memory::makeNew(mSrcBytes);
  uint32_t concatBufOffset = 0;
  for (tBufVec::const_iterator it = bufVec.begin(); it != bufVec.end(); ++it) {
    const uint8_t* buf = it->first;
    uint32_t len = it->second;
    memcpy (concatBuf->buf() + concatBufOffset, buf, len);
    concatBufOffset += len;
  }
  return concatBuf;
}

std::shared_ptr<Memory> Packers::convert(std::shared_ptr<Memory> srcBuf) {
  // only 420P supported currently
  uint32_t lumaBytes = mSrcWidth * mSrcHeight;
  std::shared_ptr<Memory> convertBuf = Memory::makeNew(lumaBytes * 3 / 2);
  if (0 == mSrcFmtCode.compare("4175")) {
    convertPGroupto420P (srcBuf->buf(), convertBuf->buf());
  }
  else if (0 == mSrcFmtCode.compare("v210")) {
    convertV210to420P (srcBuf->buf(), convertBuf->buf());
  }
  return convertBuf;
}

// private
void Packers::convertPGroupto420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) {
  uint32_t srcPitchBytes = mSrcWidth * 5 / 2;
  uint32_t dstLumaPitchBytes = mSrcWidth;
  uint32_t dstChromaPitchBytes = mSrcWidth / 2;
  uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight;

  const uint8_t *srcLine = srcBuf;
  uint8_t *dstYLine = dstBuf;
  uint8_t *dstULine = dstBuf + dstLumaPlaneBytes;
  uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4;

  for (uint32_t y=0; y<mSrcHeight; ++y) {
    const uint8_t *srcBytes = srcLine;
    uint8_t *dstYBytes = dstYLine;
    uint8_t *dstUBytes = dstULine;
    uint8_t *dstVBytes = dstVLine;
    bool evenLine = (y & 1) == 0;

    // read 5 source bytes / 2 source pixels at a time
    for (uint32_t x=0; x<mSrcWidth; x+=2) {
      uint8_t s0 = srcBytes[0];
      uint8_t s1 = srcBytes[1];
      uint8_t s2 = srcBytes[2];
      uint8_t s3 = srcBytes[3];
      uint8_t s4 = srcBytes[4];
      srcBytes += 5;

      dstYBytes[0] = ((s1 & 0x3f) << 2) | ((s2 & 0xc0) >> 6);
      dstYBytes[1] = ((s3 & 0x03) << 6) | ((s4 & 0xfc) >> 2);
      dstYBytes += 2;

      // chroma interp between lines
      dstUBytes[0] = evenLine ? s0 : (s0 + dstUBytes[0]) >> 1;
      dstUBytes += 1;
      uint32_t v0 = ((s2 & 0x0f) << 4) | ((s3 & 0xf0) >> 4);
      dstVBytes[0] = evenLine ? v0 : (v0 + dstVBytes[0]) >> 1;
      dstVBytes += 1;
    }

    srcLine += srcPitchBytes;
    dstYLine += dstLumaPitchBytes;
    if (evenLine) {
      dstULine += dstChromaPitchBytes;
      dstVLine += dstChromaPitchBytes;
    }
  }
}

void Packers::convertV210to420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) {
// V210: https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG8-V210__4_2_2_COMPRESSION_TYPE
// 420P: https://en.wikipedia.org/wiki/YUV
  uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3;
  uint32_t dstLumaPitchBytes = mSrcWidth;
  uint32_t dstChromaPitchBytes = mSrcWidth / 2;
  uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight;

  const uint8_t *srcLine = srcBuf;
  uint8_t *dstYLine = dstBuf;
  uint8_t *dstULine = dstBuf + dstLumaPlaneBytes;
  uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4;

  for (uint32_t y=0; y<mSrcHeight; ++y) {
    uint32_t *srcInts = (uint32_t *)srcLine;
    uint8_t *dstYBytes = dstYLine;
    uint8_t *dstUBytes = dstULine;
    uint8_t *dstVBytes = dstVLine;
    bool evenLine = (y & 1) == 0;

    // read 4 source ints / 6 source pixels at a time
    for (uint32_t x=0; x<mSrcWidth; x+=6) {
      uint32_t s0 = srcInts[0];
      uint32_t s1 = srcInts[1];
      uint32_t s2 = srcInts[2];
      uint32_t s3 = srcInts[3];
      srcInts += 4;

      dstYBytes[0] = (s0 >> 12) & 0xff;
      dstYBytes[1] = (s1 >>  2) & 0xff;
      dstYBytes[2] = (s1 >> 22) & 0xff;
      dstYBytes[3] = (s2 >> 12) & 0xff;
      dstYBytes[4] = (s3 >>  2) & 0xff;
      dstYBytes[5] = (s3 >> 22) & 0xff;
      dstYBytes += 6;

      dstUBytes[0] = evenLine ? ((s0 >>  2) & 0xff) : (((s0 >>  2) & 0xff) + dstUBytes[0]) >> 1;
      dstUBytes[1] = evenLine ? ((s1 >> 12) & 0xff) : (((s1 >> 12) & 0xff) + dstUBytes[1]) >> 1;
      dstUBytes[2] = evenLine ? ((s2 >> 22) & 0xff) : (((s2 >> 22) & 0xff) + dstUBytes[2]) >> 1;
      dstUBytes += 3;

      dstVBytes[0] = evenLine ? ((s0 >> 22) & 0xff) : (((s0 >> 22) & 0xff) + dstVBytes[0]) >> 1;
      dstVBytes[1] = evenLine ? ((s2 >>  2) & 0xff) : (((s2 >>  2) & 0xff) + dstVBytes[1]) >> 1;
      dstVBytes[2] = evenLine ? ((s3 >> 12) & 0xff) : (((s3 >> 12) & 0xff) + dstVBytes[2]) >> 1;
      dstVBytes += 3;
    }

    srcLine += srcPitchBytes;
    dstYLine += dstLumaPitchBytes;
    if (evenLine) {
      dstULine += dstChromaPitchBytes;
      dstVLine += dstChromaPitchBytes;
    }
  }
}

} // namespace streampunk
<|endoftext|>


<commit_before>//===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take.
//
//===----------------------------------------------------------------------===//

#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include <cctype>
#include <cstring>
using namespace llvm;

TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm)
  : TM(tm)
{
  BSSSection = "\t.bss";
  BSSSection_ = 0;
  ReadOnlySection = 0;
  TLSDataSection = 0;
  TLSBSSSection = 0;
  ZeroFillDirective = 0;
  NonexecutableStackDirective = 0;
  NeedsSet = false;
  MaxInstLength = 4;
  PCSymbol = "$";
  SeparatorChar = ';';
  CommentColumn = 60;
  CommentString = "#";
  FirstOperandColumn = 0;
  MaxOperandLength = 0;
  GlobalPrefix = "";
  PrivateGlobalPrefix = ".";
  LinkerPrivateGlobalPrefix = "";
  JumpTableSpecialLabelPrefix = 0;
  GlobalVarAddrPrefix = "";
  GlobalVarAddrSuffix = "";
  FunctionAddrPrefix = "";
  FunctionAddrSuffix = "";
  PersonalityPrefix = "";
  PersonalitySuffix = "";
  NeedsIndirectEncoding = false;
  InlineAsmStart = "#APP";
  InlineAsmEnd = "#NO_APP";
  AssemblerDialect = 0;
  AllowQuotesInName = false;
  ZeroDirective = "\t.zero\t";
  ZeroDirectiveSuffix = 0;
  AsciiDirective = "\t.ascii\t";
  AscizDirective = "\t.asciz\t";
  Data8bitsDirective = "\t.byte\t";
  Data16bitsDirective = "\t.short\t";
  Data32bitsDirective = "\t.long\t";
  Data64bitsDirective = "\t.quad\t";
  AlignDirective = "\t.align\t";
  AlignmentIsInBytes = true;
  TextAlignFillValue = 0;
  SwitchToSectionDirective = "\t.section\t";
  TextSectionStartSuffix = "";
  DataSectionStartSuffix = "";
  SectionEndDirectiveSuffix = 0;
  ConstantPoolSection = "\t.section .rodata";
  JumpTableDataSection = "\t.section .rodata";
  JumpTableDirective = 0;
  CStringSection = 0;
  CStringSection_ = 0;
  // FIXME: Flags are ELFish - replace with normal section stuff.
  StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
  StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
  GlobalDirective = "\t.globl\t";
  SetDirective = 0;
  LCOMMDirective = 0;
  COMMDirective = "\t.comm\t";
  COMMDirectiveTakesAlignment = true;
  HasDotTypeDotSizeDirective = true;
  HasSingleParameterDotFile = true;
  UsedDirective = 0;
  WeakRefDirective = 0;
  WeakDefDirective = 0;
  // FIXME: These are ELFish - move to ELFTAI.
  HiddenDirective = "\t.hidden\t";
  ProtectedDirective = "\t.protected\t";
  AbsoluteDebugSectionOffsets = false;
  AbsoluteEHSectionOffsets = false;
  HasLEB128 = false;
  HasDotLocAndDotFile = false;
  SupportsDebugInformation = false;
  SupportsExceptionHandling = false;
  DwarfRequiresFrameSection = true;
  DwarfUsesInlineInfoSection = false;
  Is_EHSymbolPrivate = true;
  GlobalEHDirective = 0;
  SupportsWeakOmittedEHFrame = true;
  DwarfSectionOffsetDirective = 0;
  DwarfAbbrevSection = ".debug_abbrev";
  DwarfInfoSection = ".debug_info";
  DwarfLineSection = ".debug_line";
  DwarfFrameSection = ".debug_frame";
  DwarfPubNamesSection = ".debug_pubnames";
  DwarfPubTypesSection = ".debug_pubtypes";
  DwarfDebugInlineSection = ".debug_inlined";
  DwarfStrSection = ".debug_str";
  DwarfLocSection = ".debug_loc";
  DwarfARangesSection = ".debug_aranges";
  DwarfRangesSection = ".debug_ranges";
  DwarfMacroInfoSection = ".debug_macinfo";
  DwarfEHFrameSection = ".eh_frame";
  DwarfExceptionSection = ".gcc_except_table";
  AsmTransCBE = 0;
  TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
  DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable);
}

TargetAsmInfo::~TargetAsmInfo() {
}

/// Measure the specified inline asm to determine an approximation of its
/// length.
/// Comments (which run till the next SeparatorChar or newline) do not
/// count as an instruction.
/// Any other non-whitespace text is considered an instruction, with
/// multiple instructions separated by SeparatorChar or newlines.
/// Variable-length instructions are not handled here; this function
/// may be overloaded in the target code to do that.
unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
  // Count the number of instructions in the asm.
  bool atInsnStart = true;
  unsigned Length = 0;
  for (; *Str; ++Str) {
    if (*Str == '\n' || *Str == SeparatorChar)
      atInsnStart = true;
    if (atInsnStart && !isspace(*Str)) {
      Length += MaxInstLength;
      atInsnStart = false;
    }
    if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
      atInsnStart = false;
  }

  return Length;
}

unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
                                              bool Global) const {
  return dwarf::DW_EH_PE_absptr;
}

static bool isSuitableForBSS(const GlobalVariable *GV) {
  if (!GV->hasInitializer())
    return true;

  // Leave constant zeros in readonly constant sections, so they can be shared
  Constant *C = GV->getInitializer();
  return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
}

static bool isConstantString(const Constant *C) {
  // First check: is we have constant array of i8 terminated with zero
  const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
  // Check, if initializer is a null-terminated string
  if (CVA && CVA->isCString())
    return true;

  // Another possibility: [1 x i8] zeroinitializer
  if (isa<ConstantAggregateZero>(C)) {
    if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) {
      return (Ty->getElementType() == Type::Int8Ty &&
              Ty->getNumElements() == 1);
    }
  }

  return false;
}

static unsigned SectionFlagsForGlobal(const GlobalValue *GV,
                                      SectionKind::Kind Kind,
                                      const char *Name = 0) {
  unsigned Flags = SectionFlags::None;

  // Decode flags from global itself.
  switch (Kind) {
  case SectionKind::Text:
    Flags |= SectionFlags::Code;
    break;
  case SectionKind::ThreadData:
  case SectionKind::ThreadBSS:
    Flags |= SectionFlags::TLS;
    // FALLS THROUGH
  case SectionKind::Data:
  case SectionKind::DataRel:
  case SectionKind::DataRelLocal:
  case SectionKind::DataRelRO:
  case SectionKind::DataRelROLocal:
  case SectionKind::BSS:
    Flags |= SectionFlags::Writeable;
    break;
  case SectionKind::ROData:
  case SectionKind::RODataMergeStr:
  case SectionKind::RODataMergeConst:
    // No additional flags here
    break;
  default:
    llvm_unreachable("Unexpected section kind!");
  }

  if (GV->isWeakForLinker())
    Flags |= SectionFlags::Linkonce;

  // Add flags from sections, if any.
  if (Name && *Name != '\0') {
    Flags |= SectionFlags::Named;

    // Some lame default implementation based on some magic section names.
    if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
        strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
        strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
        strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
      Flags |= SectionFlags::BSS;
    else if (strcmp(Name, ".tdata") == 0 ||
             strncmp(Name, ".tdata.", 7) == 0 ||
             strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
             strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
      Flags |= SectionFlags::TLS;
    else if (strcmp(Name, ".tbss") == 0 ||
             strncmp(Name, ".tbss.", 6) == 0 ||
             strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
             strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
      Flags |= SectionFlags::BSS | SectionFlags::TLS;
  }

  return Flags;
}

SectionKind::Kind
TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
  // Early exit - functions should be always in text sections.
  if (isa<Function>(GV))
    return SectionKind::Text;

  const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
  bool isThreadLocal = GVar->isThreadLocal();
  assert(GVar && "Invalid global value for section selection");

  if (isSuitableForBSS(GVar)) {
    // Variable can be easily put to BSS section.
    return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS;
  } else if (GVar->isConstant() && !isThreadLocal) {
    // Now we know, that variable has initializer and it is constant. We need to
    // check its initializer to decide, which section to output it into. Also
    // note, there is no thread-local r/o section.
    Constant *C = GVar->getInitializer();
    if (C->getRelocationInfo() != 0) {
      // Decide whether it is still possible to put symbol into r/o section.
      if (TM.getRelocationModel() != Reloc::Static)
        return SectionKind::Data;
      else
        return SectionKind::ROData;
    } else {
      // Check, if initializer is a null-terminated string
      if (isConstantString(C))
        return SectionKind::RODataMergeStr;
      else
        return SectionKind::RODataMergeConst;
    }
  }

  // Variable either is not constant or thread-local - output to data section.
  return isThreadLocal ? SectionKind::ThreadData : SectionKind::Data;
}

const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
  // Select section name
  if (GV->hasSection()) {
    // Honour section already set, if any.
    unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV),
                                           GV->getSection().c_str());
    return getNamedSection(GV->getSection().c_str(), Flags);
  }

  // If this global is linkonce/weak and the target handles this by emitting it
  // into a 'uniqued' section name, create and return the section now.
  if (GV->isWeakForLinker()) {
    if (const char *Prefix =
          getSectionPrefixForUniqueGlobal(SectionKindForGlobal(GV))) {
      // FIXME: Use mangler interface (PR4584).
      std::string Name = Prefix+GV->getNameStr();
      unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV));
      return getNamedSection(Name.c_str(), Flags);
    }
  }

  // Use default section depending on the 'type' of global
  return SelectSectionForGlobal(GV);
}

// Lame default implementation. Calculate the section name for global.
const Section*
TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
  SectionKind::Kind Kind = SectionKindForGlobal(GV);

  if (Kind == SectionKind::Text)
    return getTextSection();

  if (isBSS(Kind))
    if (const Section *S = getBSSSection_())
      return S;

  if (SectionKind::isReadOnly(Kind))
    if (const Section *S = getReadOnlySection())
      return S;

  return getDataSection();
}

/// getSectionForMergableConstant - Given a mergable constant with the
/// specified size and relocation information, return a section that it
/// should be placed in.
const Section *
TargetAsmInfo::getSectionForMergableConstant(uint64_t Size,
                                             unsigned ReloInfo) const {
  // FIXME: Support data.rel stuff someday
  // Lame default implementation. Calculate the section name for machine const.
  return getDataSection();
}

const char *
TargetAsmInfo::getSectionPrefixForUniqueGlobal(SectionKind::Kind Kind) const {
  switch (Kind) {
  default: llvm_unreachable("Unknown section kind");
  case SectionKind::Text:             return ".gnu.linkonce.t.";
  case SectionKind::Data:             return ".gnu.linkonce.d.";
  case SectionKind::DataRel:          return ".gnu.linkonce.d.rel.";
  case SectionKind::DataRelLocal:     return ".gnu.linkonce.d.rel.local.";
  case SectionKind::DataRelRO:        return ".gnu.linkonce.d.rel.ro.";
  case SectionKind::DataRelROLocal:   return ".gnu.linkonce.d.rel.ro.local.";
  case SectionKind::BSS:              return ".gnu.linkonce.b.";
  case SectionKind::ROData:
  case SectionKind::RODataMergeConst:
  case SectionKind::RODataMergeStr:   return ".gnu.linkonce.r.";
  case SectionKind::ThreadData:       return ".gnu.linkonce.td.";
  case SectionKind::ThreadBSS:        return ".gnu.linkonce.tb.";
  }
}

const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
                                              bool Override) const {
  Section &S = Sections[Name];

  // This is newly-created section, set it up properly.
  if (S.Flags == SectionFlags::Invalid || Override) {
    S.Flags = Flags | SectionFlags::Named;
    S.Name = Name;
  }

  return &S;
}

const Section*
TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
                                 bool Override) const {
  Section& S = Sections[Directive];

  // This is newly-created section, set it up properly.
  if (S.Flags == SectionFlags::Invalid || Override) {
    S.Flags = Flags & ~SectionFlags::Named;
    S.Name = Directive;
  }

  return &S;
}

const std::string&
TargetAsmInfo::getSectionFlags(unsigned Flags) const {
  SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);

  // We didn't print these flags yet, print and save them to map. This reduces
  // amount of heap trashing due to std::string construction / concatenation.
  if (I == FlagsStrings.end())
    I = FlagsStrings.insert(std::make_pair(Flags,
                                           printSectionFlags(Flags))).first;

  return I->second;
}

unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
  unsigned Size = 0;
  do {
    Value >>= 7;
    Size += sizeof(int8_t);
  } while (Value);
  return Size;
}

unsigned TargetAsmInfo::getSLEB128Size(int Value) {
  unsigned Size = 0;
  int Sign = Value >> (8 * sizeof(Value) - 1);
  bool IsMore;

  do {
    unsigned Byte = Value & 0x7f;
    Value >>= 7;
    IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
    Size += sizeof(int8_t);
  } while (IsMore);
  return Size;
}
<commit_msg>split the ELF-specific section flag inference-from-name code out into its own helper function.<commit_after>//===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take.
//
//===----------------------------------------------------------------------===//

#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include <cctype>
#include <cstring>
using namespace llvm;

TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm)
  : TM(tm)
{
  BSSSection = "\t.bss";
  BSSSection_ = 0;
  ReadOnlySection = 0;
  TLSDataSection = 0;
  TLSBSSSection = 0;
  ZeroFillDirective = 0;
  NonexecutableStackDirective = 0;
  NeedsSet = false;
  MaxInstLength = 4;
  PCSymbol = "$";
  SeparatorChar = ';';
  CommentColumn = 60;
  CommentString = "#";
  FirstOperandColumn = 0;
  MaxOperandLength = 0;
  GlobalPrefix = "";
  PrivateGlobalPrefix = ".";
  LinkerPrivateGlobalPrefix = "";
  JumpTableSpecialLabelPrefix = 0;
  GlobalVarAddrPrefix = "";
  GlobalVarAddrSuffix = "";
  FunctionAddrPrefix = "";
  FunctionAddrSuffix = "";
  PersonalityPrefix = "";
  PersonalitySuffix = "";
  NeedsIndirectEncoding = false;
  InlineAsmStart = "#APP";
  InlineAsmEnd = "#NO_APP";
  AssemblerDialect = 0;
  AllowQuotesInName = false;
  ZeroDirective = "\t.zero\t";
  ZeroDirectiveSuffix = 0;
  AsciiDirective = "\t.ascii\t";
  AscizDirective = "\t.asciz\t";
  Data8bitsDirective = "\t.byte\t";
  Data16bitsDirective = "\t.short\t";
  Data32bitsDirective = "\t.long\t";
  Data64bitsDirective = "\t.quad\t";
  AlignDirective = "\t.align\t";
  AlignmentIsInBytes = true;
  TextAlignFillValue = 0;
  SwitchToSectionDirective = "\t.section\t";
  TextSectionStartSuffix = "";
  DataSectionStartSuffix = "";
  SectionEndDirectiveSuffix = 0;
  ConstantPoolSection = "\t.section .rodata";
  JumpTableDataSection = "\t.section .rodata";
  JumpTableDirective = 0;
  CStringSection = 0;
  CStringSection_ = 0;
  // FIXME: Flags are ELFish - replace with normal section stuff.
  StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits";
  StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits";
  GlobalDirective = "\t.globl\t";
  SetDirective = 0;
  LCOMMDirective = 0;
  COMMDirective = "\t.comm\t";
  COMMDirectiveTakesAlignment = true;
  HasDotTypeDotSizeDirective = true;
  HasSingleParameterDotFile = true;
  UsedDirective = 0;
  WeakRefDirective = 0;
  WeakDefDirective = 0;
  // FIXME: These are ELFish - move to ELFTAI.
  HiddenDirective = "\t.hidden\t";
  ProtectedDirective = "\t.protected\t";
  AbsoluteDebugSectionOffsets = false;
  AbsoluteEHSectionOffsets = false;
  HasLEB128 = false;
  HasDotLocAndDotFile = false;
  SupportsDebugInformation = false;
  SupportsExceptionHandling = false;
  DwarfRequiresFrameSection = true;
  DwarfUsesInlineInfoSection = false;
  Is_EHSymbolPrivate = true;
  GlobalEHDirective = 0;
  SupportsWeakOmittedEHFrame = true;
  DwarfSectionOffsetDirective = 0;
  DwarfAbbrevSection = ".debug_abbrev";
  DwarfInfoSection = ".debug_info";
  DwarfLineSection = ".debug_line";
  DwarfFrameSection = ".debug_frame";
  DwarfPubNamesSection = ".debug_pubnames";
  DwarfPubTypesSection = ".debug_pubtypes";
  DwarfDebugInlineSection = ".debug_inlined";
  DwarfStrSection = ".debug_str";
  DwarfLocSection = ".debug_loc";
  DwarfARangesSection = ".debug_aranges";
  DwarfRangesSection = ".debug_ranges";
  DwarfMacroInfoSection = ".debug_macinfo";
  DwarfEHFrameSection = ".eh_frame";
  DwarfExceptionSection = ".gcc_except_table";
  AsmTransCBE = 0;
  TextSection = getUnnamedSection("\t.text", SectionFlags::Code);
  DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable);
}

TargetAsmInfo::~TargetAsmInfo() {
}

/// Measure the specified inline asm to determine an approximation of its
/// length.
/// Comments (which run till the next SeparatorChar or newline) do not
/// count as an instruction.
/// Any other non-whitespace text is considered an instruction, with
/// multiple instructions separated by SeparatorChar or newlines.
/// Variable-length instructions are not handled here; this function
/// may be overloaded in the target code to do that.
unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const {
  // Count the number of instructions in the asm.
  bool atInsnStart = true;
  unsigned Length = 0;
  for (; *Str; ++Str) {
    if (*Str == '\n' || *Str == SeparatorChar)
      atInsnStart = true;
    if (atInsnStart && !isspace(*Str)) {
      Length += MaxInstLength;
      atInsnStart = false;
    }
    if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0)
      atInsnStart = false;
  }

  return Length;
}

unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
                                              bool Global) const {
  return dwarf::DW_EH_PE_absptr;
}

static bool isSuitableForBSS(const GlobalVariable *GV) {
  if (!GV->hasInitializer())
    return true;

  // Leave constant zeros in readonly constant sections, so they can be shared
  Constant *C = GV->getInitializer();
  return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
}

static bool isConstantString(const Constant *C) {
  // First check: is we have constant array of i8 terminated with zero
  const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
  // Check, if initializer is a null-terminated string
  if (CVA && CVA->isCString())
    return true;

  // Another possibility: [1 x i8] zeroinitializer
  if (isa<ConstantAggregateZero>(C)) {
    if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) {
      return (Ty->getElementType() == Type::Int8Ty &&
              Ty->getNumElements() == 1);
    }
  }

  return false;
}

static unsigned SectionFlagsForGlobal(const GlobalValue *GV,
                                      SectionKind::Kind Kind) {
  unsigned Flags = SectionFlags::None;

  // Decode flags from global itself.
  switch (Kind) {
  case SectionKind::Text:
    Flags |= SectionFlags::Code;
    break;
  case SectionKind::ThreadData:
  case SectionKind::ThreadBSS:
    Flags |= SectionFlags::TLS;
    // FALLS THROUGH
  case SectionKind::Data:
  case SectionKind::DataRel:
  case SectionKind::DataRelLocal:
  case SectionKind::DataRelRO:
  case SectionKind::DataRelROLocal:
  case SectionKind::BSS:
    Flags |= SectionFlags::Writeable;
    break;
  case SectionKind::ROData:
  case SectionKind::RODataMergeStr:
  case SectionKind::RODataMergeConst:
    // No additional flags here
    break;
  default:
    llvm_unreachable("Unexpected section kind!");
  }

  if (GV->isWeakForLinker())
    Flags |= SectionFlags::Linkonce;

  return Flags;
}

static unsigned GetSectionFlagsForNamedELFSection(const char *Name) {
  unsigned Flags = 0;
  // Some lame default implementation based on some magic section names.
  if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
      strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
      strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
      strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
    Flags |= SectionFlags::BSS;
  else if (strcmp(Name, ".tdata") == 0 ||
           strncmp(Name, ".tdata.", 7) == 0 ||
           strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
           strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
    Flags |= SectionFlags::TLS;
  else if (strcmp(Name, ".tbss") == 0 ||
           strncmp(Name, ".tbss.", 6) == 0 ||
           strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
           strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
    Flags |= SectionFlags::BSS | SectionFlags::TLS;

  return Flags;
}

SectionKind::Kind
TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {
  // Early exit - functions should be always in text sections.
  if (isa<Function>(GV))
    return SectionKind::Text;

  const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);
  bool isThreadLocal = GVar->isThreadLocal();
  assert(GVar && "Invalid global value for section selection");

  if (isSuitableForBSS(GVar)) {
    // Variable can be easily put to BSS section.
    return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS;
  } else if (GVar->isConstant() && !isThreadLocal) {
    // Now we know, that variable has initializer and it is constant. We need to
    // check its initializer to decide, which section to output it into. Also
    // note, there is no thread-local r/o section.
    Constant *C = GVar->getInitializer();
    if (C->getRelocationInfo() != 0) {
      // Decide whether it is still possible to put symbol into r/o section.
      if (TM.getRelocationModel() != Reloc::Static)
        return SectionKind::Data;
      else
        return SectionKind::ROData;
    } else {
      // Check, if initializer is a null-terminated string
      if (isConstantString(C))
        return SectionKind::RODataMergeStr;
      else
        return SectionKind::RODataMergeConst;
    }
  }

  // Variable either is not constant or thread-local - output to data section.
  return isThreadLocal ? SectionKind::ThreadData : SectionKind::Data;
}

const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
  // Select section name
  if (GV->hasSection()) {
    // Honour section already set, if any.
    unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV));

    // This is an explicitly named section.
    Flags |= SectionFlags::Named;

    // If the target has magic semantics for certain section names, make sure to
    // pick up the flags.  This allows the user to write things with attribute
    // section and still get the appropriate section flags printed.
    Flags |= GetSectionFlagsForNamedELFSection(GV->getSection().c_str());

    return getNamedSection(GV->getSection().c_str(), Flags);
  }

  // If this global is linkonce/weak and the target handles this by emitting it
  // into a 'uniqued' section name, create and return the section now.
  if (GV->isWeakForLinker()) {
    if (const char *Prefix =
          getSectionPrefixForUniqueGlobal(SectionKindForGlobal(GV))) {
      // FIXME: Use mangler interface (PR4584).
      std::string Name = Prefix+GV->getNameStr();
      unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV));
      return getNamedSection(Name.c_str(), Flags);
    }
  }

  // Use default section depending on the 'type' of global
  return SelectSectionForGlobal(GV);
}

// Lame default implementation. Calculate the section name for global.
const Section*
TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {
  SectionKind::Kind Kind = SectionKindForGlobal(GV);

  if (Kind == SectionKind::Text)
    return getTextSection();

  if (isBSS(Kind))
    if (const Section *S = getBSSSection_())
      return S;

  if (SectionKind::isReadOnly(Kind))
    if (const Section *S = getReadOnlySection())
      return S;

  return getDataSection();
}

/// getSectionForMergableConstant - Given a mergable constant with the
/// specified size and relocation information, return a section that it
/// should be placed in.
const Section *
TargetAsmInfo::getSectionForMergableConstant(uint64_t Size,
                                             unsigned ReloInfo) const {
  // FIXME: Support data.rel stuff someday
  // Lame default implementation. Calculate the section name for machine const.
  return getDataSection();
}

const char *
TargetAsmInfo::getSectionPrefixForUniqueGlobal(SectionKind::Kind Kind) const {
  switch (Kind) {
  default: llvm_unreachable("Unknown section kind");
  case SectionKind::Text:             return ".gnu.linkonce.t.";
  case SectionKind::Data:             return ".gnu.linkonce.d.";
  case SectionKind::DataRel:          return ".gnu.linkonce.d.rel.";
  case SectionKind::DataRelLocal:     return ".gnu.linkonce.d.rel.local.";
  case SectionKind::DataRelRO:        return ".gnu.linkonce.d.rel.ro.";
  case SectionKind::DataRelROLocal:   return ".gnu.linkonce.d.rel.ro.local.";
  case SectionKind::BSS:              return ".gnu.linkonce.b.";
  case SectionKind::ROData:
  case SectionKind::RODataMergeConst:
  case SectionKind::RODataMergeStr:   return ".gnu.linkonce.r.";
  case SectionKind::ThreadData:       return ".gnu.linkonce.td.";
  case SectionKind::ThreadBSS:        return ".gnu.linkonce.tb.";
  }
}

const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags,
                                              bool Override) const {
  Section &S = Sections[Name];

  // This is newly-created section, set it up properly.
  if (S.Flags == SectionFlags::Invalid || Override) {
    S.Flags = Flags | SectionFlags::Named;
    S.Name = Name;
  }

  return &S;
}

const Section*
TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags,
                                 bool Override) const {
  Section& S = Sections[Directive];

  // This is newly-created section, set it up properly.
  if (S.Flags == SectionFlags::Invalid || Override) {
    S.Flags = Flags & ~SectionFlags::Named;
    S.Name = Directive;
  }

  return &S;
}

const std::string&
TargetAsmInfo::getSectionFlags(unsigned Flags) const {
  SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags);

  // We didn't print these flags yet, print and save them to map. This reduces
  // amount of heap trashing due to std::string construction / concatenation.
  if (I == FlagsStrings.end())
    I = FlagsStrings.insert(std::make_pair(Flags,
                                           printSectionFlags(Flags))).first;

  return I->second;
}

unsigned TargetAsmInfo::getULEB128Size(unsigned Value) {
  unsigned Size = 0;
  do {
    Value >>= 7;
    Size += sizeof(int8_t);
  } while (Value);
  return Size;
}

unsigned TargetAsmInfo::getSLEB128Size(int Value) {
  unsigned Size = 0;
  int Sign = Value >> (8 * sizeof(Value) - 1);
  bool IsMore;

  do {
    unsigned Byte = Value & 0x7f;
    Value >>= 7;
    IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
    Size += sizeof(int8_t);
  } while (IsMore);
  return Size;
}
<|endoftext|>


<commit_before>#include <cstddef>

#include "Smooth.h"
#include "PollardRho.h"

namespace Math {
  namespace Fac {
    bool isSmooth(const mpz_t n, const mpz_t B, mpz_t *C) {
      vector<mpz_t*> facs;
      pollardRhoFactor(n, facs);

      mpz_t max;
      mpz_init(max);
      mpz_set_ui(max, 0);
      for (size_t i = 0; i < facs.size(); i++) {
        mpz_t *fac = facs[i];
        if (mpz_cmp(*fac, max) > 0) {
          mpz_set(max, *fac);
        }
      }

      if (mpz_cmp(max, B) <= 0) {
        mpz_clear(max);
        return true;
      }

      if (C) mpz_set(*C, max);

      mpz_clear(max);
      return false;
    }

    bool isSmoothI(int n, int B, int *C) {
      vector<int> facs;
      pollardRhoFactorI(n, facs);

      int max = 0;
      for (size_t i = 0; i < facs.size(); i++) {
        int fac = facs[i];
        if (fac > max) max = fac;
      }

      if (max <= B) return true;

      if (C) *C = max;
      return false;
    }
  }
}
<commit_msg>Added cleanup of discovered factors in isSmooth.<commit_after>#include <cstddef>

#include "Smooth.h"
#include "PollardRho.h"

namespace Math {
  namespace Fac {
    bool isSmooth(const mpz_t n, const mpz_t B, mpz_t *C) {
      vector<mpz_t*> facs;
      pollardRhoFactor(n, facs);

      mpz_t max;
      mpz_init(max);
      mpz_set_ui(max, 0);
      for (size_t i = 0; i < facs.size(); i++) {
        mpz_t *fac = facs[i];
        if (mpz_cmp(*fac, max) > 0) {
          mpz_set(max, *fac);
        }

        mpz_clear(*fac);
        delete[] fac;
      }

      if (mpz_cmp(max, B) <= 0) {
        mpz_clear(max);
        return true;
      }

      if (C) mpz_set(*C, max);

      mpz_clear(max);
      return false;
    }

    bool isSmoothI(int n, int B, int *C) {
      vector<int> facs;
      pollardRhoFactorI(n, facs);

      int max = 0;
      for (size_t i = 0; i < facs.size(); i++) {
        int fac = facs[i];
        if (fac > max) max = fac;
      }

      if (max <= B) return true;

      if (C) *C = max;
      return false;
    }
  }
}
<|endoftext|>


<commit_before>#include <node.h>
#include <initializer_list>

#include "../amo-library/Pump.h"
#include "../amo-library/calculator/PumpEfficiency.h"
#include "../amo-library/calculator/OptimalPumpEfficiency.h"
#include "../amo-library/calculator/MotorRatedPower.h"
#include "../amo-library/calculator/OptimalMotorRatedPower.h"
#include "../amo-library/calculator/MotorShaftPower.h"
#include "../amo-library/calculator/OptimalMotorShaftPower.h"
#include "../amo-library/calculator/PumpShaftPower.h"
#include "../amo-library/calculator/OptimalPumpShaftPower.h"
#include "../amo-library/calculator/MotorEfficiency.h"
#include "../amo-library/calculator/OptimalMotorEfficiency.h"
#include "../amo-library/calculator/MotorPowerFactor.h"
#include "../amo-library/calculator/OptimalMotorPowerFactor.h"
#include "../amo-library/calculator/MotorCurrent.h"
#include "../amo-library/calculator/OptimalMotorCurrent.h"
#include "../amo-library/calculator/MotorPower.h"
#include "../amo-library/calculator/OptimalMotorPower.h"
#include "../amo-library/AnnualEnergy.h"
#include "../amo-library/AnnualCost.h"
#include "../amo-library/AnnualSavingsPotential.h"
#include "../amo-library/OptimizationRating.h"

using namespace v8;

Local<Array> r;
Isolate* iso;
Local<Object> inp;

void set(std::initializer_list <double> args) {
  for (auto d : args) {
    r->Set(r->Length(),Number::New(iso,d));
  }
}
double get(const char * nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);
  inp = args[0]->ToObject();
  set({
    (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),get("power_rating")))->calculate(),
    (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rpm"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),
    (new MotorRatedPower(0))->calculate(),
    (new OptimalMotorRatedPower(0,0))->calculate(),
    (new MotorShaftPower(0,0))->calculate(),
    (new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(),
    (new PumpShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(),
    (new OptimalPumpShaftPower(0,0,0,0))->calculate(),
    (new MotorEfficiency(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(),
    (new OptimalMotorEfficiency(0,0))->calculate(),
    (new MotorPowerFactor(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(),
    (new OptimalMotorPowerFactor(0,0))->calculate(),
    (new MotorCurrent(0,0,0))->calculate(),
    (new OptimalMotorCurrent(0,0))->calculate(),
    (new MotorPower(0,0,0,0))->calculate(),
    (new OptimalMotorPower(0,0))->calculate(),
    (new AnnualEnergy(0,0))->calculate(),
    (new AnnualEnergy(0,0))->calculate(),
    (new AnnualCost(0,0))->calculate(),
    (new AnnualCost(0,0))->calculate(),
    -1,
    (new AnnualSavingsPotential(0,0))->calculate(),
    -1,
    (new OptimizationRating(0,0))->calculate()
  });
  args.GetReturnValue().Set(r);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, init)

<commit_msg>no message<commit_after>#include <node.h>
#include <initializer_list>

#include "../amo-library/Pump.h"
#include "../amo-library/calculator/PumpEfficiency.h"
#include "../amo-library/calculator/OptimalPumpEfficiency.h"
#include "../amo-library/calculator/MotorRatedPower.h"
#include "../amo-library/calculator/OptimalMotorRatedPower.h"
#include "../amo-library/calculator/MotorShaftPower.h"
#include "../amo-library/calculator/OptimalMotorShaftPower.h"
#include "../amo-library/calculator/PumpShaftPower.h"
#include "../amo-library/calculator/OptimalPumpShaftPower.h"
#include "../amo-library/calculator/MotorEfficiency.h"
#include "../amo-library/calculator/OptimalMotorEfficiency.h"
#include "../amo-library/calculator/MotorPowerFactor.h"
#include "../amo-library/calculator/OptimalMotorPowerFactor.h"
#include "../amo-library/calculator/MotorCurrent.h"
#include "../amo-library/calculator/OptimalMotorCurrent.h"
#include "../amo-library/calculator/MotorPower.h"
#include "../amo-library/calculator/OptimalMotorPower.h"
#include "../amo-library/AnnualEnergy.h"
#include "../amo-library/AnnualCost.h"
#include "../amo-library/AnnualSavingsPotential.h"
#include "../amo-library/OptimizationRating.h"

using namespace v8;

Local<Array> r;
Isolate* iso;
Local<Object> inp;

void set(std::initializer_list <double> args) {
  for (auto d : args) {
    r->Set(r->Length(),Number::New(iso,d));
  }
}
double get(const char * nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);
  inp = args[0]->ToObject();

  set({
    (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),
    (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rpm"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),
    (new MotorRatedPower(get("power_rating")))->calculate(),
    (new OptimalMotorRatedPower(0,get("margin")))->calculate(),
    (new MotorShaftPower(0,0))->calculate(),
    (new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(),
    (new PumpShaftPower(0,static_cast<Pump::Drive>(get("drive"))))))->calculate(),
    (new OptimalPumpShaftPower(0,0,0,0))->calculate(),
    (new MotorEfficiency(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(),
    (new OptimalMotorEfficiency(0,0))->calculate(),
    (new MotorPowerFactor(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(),
    (new OptimalMotorPowerFactor(0,0))->calculate(),
    (new MotorCurrent(0,0,0))->calculate(),
    (new OptimalMotorCurrent(0,0))->calculate(),
    (new MotorPower(0,0,0,0))->calculate(),
    (new OptimalMotorPower(0,0))->calculate(),
    (new AnnualEnergy(0,0))->calculate(),
    (new AnnualEnergy(0,0))->calculate(),
    (new AnnualCost(0,0))->calculate(),
    (new AnnualCost(0,0))->calculate(),
    -1,
    (new AnnualSavingsPotential(0,0))->calculate(),
    -1,
    (new OptimizationRating(0,0))->calculate()
  });
  args.GetReturnValue().Set(r);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, init)

<|endoftext|>


<commit_before>//
//  vertex.cpp
//  regex
//
//  Created by leviathan on 16/7/19.
//  Copyright © 2016年 leviathan. All rights reserved.
//

#include <iostream>

#include "vertex.hpp"

<commit_msg>Delete Vertex.cpp<commit_after><|endoftext|>


<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS

#include "libtorrent/config.hpp"

#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif

#include <string>
#include <cstring>
#include <stdlib.h>

// uClibc++ doesn't have cxxabi.h
#if defined __GNUC__ && __GNUC__ >= 3 \
	&& !defined __UCLIBCXX_MAJOR__

#include <cxxabi.h>

std::string demangle(char const* name)
{
// in case this string comes
	// this is needed on linux
	char const* start = strchr(name, '(');
	if (start != 0)
	{
		++start;
	}
	else
	{
		// this is needed on macos x
		start = strstr(name, "0x");
		if (start != 0)
		{
			start = strchr(start, ' ');
			if (start != 0) ++start;
			else start = name;
		}
		else start = name;
	}

	char const* end = strchr(start, '+');
	if (end) while (*(end-1) == ' ') --end;

	std::string in;
	if (end == 0) in.assign(start);
	else in.assign(start, end);

	size_t len;
	int status;
	char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status);
	if (unmangled == 0) return in;
	std::string ret(unmangled);
	free(unmangled);
	return ret;
}
#elif defined WIN32

#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP

#include "windows.h"
#include "dbghelp.h"

std::string demangle(char const* name)
{
	char demangled_name[256];
	if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0)
		demangled_name[0] = 0;
	return demangled_name;
}

#else
std::string demangle(char const* name) { return name; }
#endif

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include "libtorrent/version.hpp"

// execinfo.h is available in the MacOS X 10.5 SDK.
#if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
#include <execinfo.h>

void print_backtrace(char* out, int len)
{
	void* stack[50];
	int size = backtrace(stack, 50);
	char** symbols = backtrace_symbols(stack, size);

	for (int i = 1; i < size && len > 0; ++i)
	{
		int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str());
		out += ret;
		len -= ret;
	}

	free(symbols);
}

#elif defined WIN32

#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP

#include "windows.h"
#include "libtorrent/utf8.hpp"

#include "winbase.h"
#include "dbghelp.h"

void print_backtrace(char* out, int len)
{
	typedef USHORT (*RtlCaptureStackBackTrace_t)(
		__in ULONG FramesToSkip,
		__in ULONG FramesToCapture,
		__out PVOID *BackTrace,
		__out_opt PULONG BackTraceHash);

	static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0;

	if (RtlCaptureStackBackTrace == 0)
	{
		// we don't actually have to free this library, everyone has it loaded
		HMODULE lib = LoadLibrary(TEXT("kernel32.dll"));
		RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace");
		if (RtlCaptureStackBackTrace == 0)
		{
			out[0] = 0;
			return;
		}
	}

	int i;
	void* stack[50];
	int size = CaptureStackBackTrace(0, 50, stack, 0);

	SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1);
	symbol->MaxNameLen = MAX_SYM_NAME;
	symbol->SizeOfStruct = sizeof(SYMBOL_INFO);

	HANDLE p = GetCurrentProcess();
	static bool sym_initialized = false;
	if (!sym_initialized)
	{
		sym_initialized = true;
		SymInitialize(p, NULL, true);
	}
	for (i = 0; i < size && len > 0; ++i)
	{
		int ret;
		if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol))
			ret = snprintf(out, len, "%d: %s\n", i, symbol->Name);
		else
			ret = snprintf(out, len, "%d: <unknown>\n", i);

		out += ret;
		len -= ret;
	}
	free(symbol);
}

#else

void print_backtrace(char* out, int len) {}

#endif

#if TORRENT_PRODUCTION_ASSERTS
char const* libtorrent_assert_log = "asserts.log";
#endif

TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file
	, char const* function, char const* value)
{
#if TORRENT_PRODUCTION_ASSERTS
	FILE* out = fopen(libtorrent_assert_log, "a+");
	if (out == 0) out = stderr;
#else
	FILE* out = stderr;
#endif

	char stack[8192];
	print_backtrace(stack, sizeof(stack));

	fprintf(out, "assertion failed. Please file a bugreport at "
		"http://code.rasterbar.com/libtorrent/newticket\n"
		"Please include the following information:\n\n"
		"version: " LIBTORRENT_VERSION "\n"
		"%s\n"
		"file: '%s'\n"
		"line: %d\n"
		"function: %s\n"
		"expression: %s\n"
		"%s%s\n"
		"stack:\n"
		"%s\n"
		, LIBTORRENT_REVISION, file, line, function, expr
		, value ? value : "", value ? "\n" : ""
		, stack);

	// if production asserts are defined, don't abort, just print the error
#if TORRENT_PRODUCTION_ASSERTS
	if (out != stderr) fclose(out);
#else
 	// send SIGINT to the current process
 	// to break into the debugger
 	raise(SIGINT);
 	abort();
#endif
}

#else

void assert_fail(char const* expr, int line, char const* file, char const* function) {}

#endif

<commit_msg>export assert_fail<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS

#include "libtorrent/config.hpp"

#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif

#include <string>
#include <cstring>
#include <stdlib.h>

// uClibc++ doesn't have cxxabi.h
#if defined __GNUC__ && __GNUC__ >= 3 \
	&& !defined __UCLIBCXX_MAJOR__

#include <cxxabi.h>

std::string demangle(char const* name)
{
// in case this string comes
	// this is needed on linux
	char const* start = strchr(name, '(');
	if (start != 0)
	{
		++start;
	}
	else
	{
		// this is needed on macos x
		start = strstr(name, "0x");
		if (start != 0)
		{
			start = strchr(start, ' ');
			if (start != 0) ++start;
			else start = name;
		}
		else start = name;
	}

	char const* end = strchr(start, '+');
	if (end) while (*(end-1) == ' ') --end;

	std::string in;
	if (end == 0) in.assign(start);
	else in.assign(start, end);

	size_t len;
	int status;
	char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status);
	if (unmangled == 0) return in;
	std::string ret(unmangled);
	free(unmangled);
	return ret;
}
#elif defined WIN32

#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP

#include "windows.h"
#include "dbghelp.h"

std::string demangle(char const* name)
{
	char demangled_name[256];
	if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0)
		demangled_name[0] = 0;
	return demangled_name;
}

#else
std::string demangle(char const* name) { return name; }
#endif

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include "libtorrent/version.hpp"

// execinfo.h is available in the MacOS X 10.5 SDK.
#if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
#include <execinfo.h>

void print_backtrace(char* out, int len)
{
	void* stack[50];
	int size = backtrace(stack, 50);
	char** symbols = backtrace_symbols(stack, size);

	for (int i = 1; i < size && len > 0; ++i)
	{
		int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str());
		out += ret;
		len -= ret;
	}

	free(symbols);
}

#elif defined WIN32

#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP

#include "windows.h"
#include "libtorrent/utf8.hpp"

#include "winbase.h"
#include "dbghelp.h"

void print_backtrace(char* out, int len)
{
	typedef USHORT (*RtlCaptureStackBackTrace_t)(
		__in ULONG FramesToSkip,
		__in ULONG FramesToCapture,
		__out PVOID *BackTrace,
		__out_opt PULONG BackTraceHash);

	static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0;

	if (RtlCaptureStackBackTrace == 0)
	{
		// we don't actually have to free this library, everyone has it loaded
		HMODULE lib = LoadLibrary(TEXT("kernel32.dll"));
		RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace");
		if (RtlCaptureStackBackTrace == 0)
		{
			out[0] = 0;
			return;
		}
	}

	int i;
	void* stack[50];
	int size = CaptureStackBackTrace(0, 50, stack, 0);

	SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1);
	symbol->MaxNameLen = MAX_SYM_NAME;
	symbol->SizeOfStruct = sizeof(SYMBOL_INFO);

	HANDLE p = GetCurrentProcess();
	static bool sym_initialized = false;
	if (!sym_initialized)
	{
		sym_initialized = true;
		SymInitialize(p, NULL, true);
	}
	for (i = 0; i < size && len > 0; ++i)
	{
		int ret;
		if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol))
			ret = snprintf(out, len, "%d: %s\n", i, symbol->Name);
		else
			ret = snprintf(out, len, "%d: <unknown>\n", i);

		out += ret;
		len -= ret;
	}
	free(symbol);
}

#else

void print_backtrace(char* out, int len) {}

#endif

#if TORRENT_PRODUCTION_ASSERTS
char const* libtorrent_assert_log = "asserts.log";
#endif

TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file
	, char const* function, char const* value)
{
#if TORRENT_PRODUCTION_ASSERTS
	FILE* out = fopen(libtorrent_assert_log, "a+");
	if (out == 0) out = stderr;
#else
	FILE* out = stderr;
#endif

	char stack[8192];
	print_backtrace(stack, sizeof(stack));

	fprintf(out, "assertion failed. Please file a bugreport at "
		"http://code.rasterbar.com/libtorrent/newticket\n"
		"Please include the following information:\n\n"
		"version: " LIBTORRENT_VERSION "\n"
		"%s\n"
		"file: '%s'\n"
		"line: %d\n"
		"function: %s\n"
		"expression: %s\n"
		"%s%s\n"
		"stack:\n"
		"%s\n"
		, LIBTORRENT_REVISION, file, line, function, expr
		, value ? value : "", value ? "\n" : ""
		, stack);

	// if production asserts are defined, don't abort, just print the error
#if TORRENT_PRODUCTION_ASSERTS
	if (out != stderr) fclose(out);
#else
 	// send SIGINT to the current process
 	// to break into the debugger
 	raise(SIGINT);
 	abort();
#endif
}

#else

TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {}

#endif

<|endoftext|>