code:
/*
   AngelCode Scripting Library
   Copyright (c) 2003-2025 Andreas Jonsson

   This software is provided 'as-is', without any express or implied
   warranty. In no event will the authors be held liable for any
   damages arising from the use of this software.

   Permission is granted to anyone to use this software for any
   purpose, including commercial applications, and to alter it and
   redistribute it freely, subject to the following restrictions:

   1. The origin of this software must not be misrepresented; you
      must not claim that you wrote the original software. If you use
      this software in a product, an acknowledgment in the product
      documentation would be appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and
      must not be misrepresented as being the original software.

   3. This notice may not be removed or altered from any source
      distribution.

   The original version of this library can be located at:
   http://www.angelcode.com/angelscript/

   Andreas Jonsson
   andreas@angelcode.com
*/

//
// as_callfunc.cpp
//
// These functions handle the actual calling of system functions
//

#include "as_config.h"
#include "as_callfunc.h"
#include "as_scriptengine.h"
#include "as_texts.h"
#include "as_context.h"

BEGIN_AS_NAMESPACE

// ref: Member Function Pointers and the Fastest Possible C++ Delegates
//      describes the structure of class method pointers for most compilers
//      http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

// ref: The code comments for ItaniumCXXABI::EmitLoadOfMemberFunctionPointer in the LLVM compiler
//      describes the structure for class method pointers on Itanium and arm64 ABI
//      http://clang.llvm.org/doxygen/CodeGen_2ItaniumCXXABI_8cpp_source.html#l00937

int DetectCallingConvention(bool isMethod, const asSFuncPtr &ptr, int callConv, void *auxiliary, asSSystemFunctionInterface *internal)
{
	internal->Clear();
	internal->func      = ptr.ptr.f.func;
	internal->auxiliary = 0;

	// Was a compatible calling convention specified?
	if( internal->func )
	{
		if( ptr.flag == 1 && callConv != asCALL_GENERIC )
			return asWRONG_CALLING_CONV;
		else if( ptr.flag == 2 && (callConv == asCALL_GENERIC || callConv == asCALL_THISCALL || callConv == asCALL_THISCALL_ASGLOBAL || callConv == asCALL_THISCALL_OBJFIRST || callConv == asCALL_THISCALL_OBJLAST) )
			return asWRONG_CALLING_CONV;
		else if( ptr.flag == 3 && !(callConv == asCALL_THISCALL || callConv == asCALL_THISCALL_ASGLOBAL || callConv == asCALL_THISCALL_OBJFIRST || callConv == asCALL_THISCALL_OBJLAST) )
			return asWRONG_CALLING_CONV;
	}

	asDWORD base = callConv;
	if (base == asCALL_CDECL_OBJFIRST || base == asCALL_CDECL_OBJLAST)
	{
		internal->callConv =
			base == asCALL_CDECL_OBJFIRST ? ICC_CDECL_OBJFIRST : ICC_CDECL_OBJLAST;
		if (!isMethod)
		{
			if (auxiliary == 0)
				return asINVALID_ARG;
			internal->auxiliary = auxiliary;
		}
		return 0;
	}

	if( !isMethod )
	{
		if( base == asCALL_CDECL )
			internal->callConv = ICC_CDECL;
		else if( base == asCALL_STDCALL )
			internal->callConv = ICC_STDCALL;
		else if( base == asCALL_THISCALL_ASGLOBAL )
		{
			if(auxiliary == 0)
				return asINVALID_ARG;
			internal->auxiliary = auxiliary;
			internal->callConv  = ICC_THISCALL;

			// This is really a thiscall, so it is necessary to check for virtual method pointers
			base = asCALL_THISCALL;
			isMethod = true;
		}
		else if (base == asCALL_GENERIC)
		{
			internal->callConv = ICC_GENERIC_FUNC;

			// The auxiliary object is optional for generic calling convention
			internal->auxiliary = auxiliary;
		}
		else
			return asNOT_SUPPORTED;
	}

	if( isMethod )
	{
#ifndef AS_NO_CLASS_METHODS
		if( base == asCALL_THISCALL || base == asCALL_THISCALL_OBJFIRST || base == asCALL_THISCALL_OBJLAST )
		{
			internalCallConv thisCallConv;
			if( base == asCALL_THISCALL )
			{
				if(callConv != asCALL_THISCALL_ASGLOBAL && auxiliary)
					return asINVALID_ARG;

				thisCallConv = ICC_THISCALL;
			}
			else
			{
#ifdef AS_NO_THISCALL_FUNCTOR_METHOD
				return asNOT_SUPPORTED;
#else
				if(auxiliary == 0)
					return asINVALID_ARG;

				internal->auxiliary = auxiliary;
				if( base == asCALL_THISCALL_OBJFIRST )
					thisCallConv = ICC_THISCALL_OBJFIRST;
				else //if( base == asCALL_THISCALL_OBJLAST )
					thisCallConv = ICC_THISCALL_OBJLAST;
#endif
			}

			internal->callConv = thisCallConv;
#ifdef GNU_STYLE_VIRTUAL_METHOD
			if( (size_t(ptr.ptr.f.func) & 1) )
				internal->callConv = (internalCallConv)(thisCallConv + 2);
#endif
			internal->baseOffset = ( int )MULTI_BASE_OFFSET(ptr);
#if (defined(AS_ARM64) || defined(AS_ARM) || defined(AS_MIPS)) && (defined(__GNUC__) || defined(AS_PSVITA))
			// As the least significant bit in func is used to switch to THUMB mode
			// on ARM processors, the LSB in the __delta variable is used instead of
			// the one in __pfn on ARM processors.
			// MIPS also appear to use the base offset to indicate virtual method.
			if( (size_t(internal->baseOffset) & 1) )
				internal->callConv = (internalCallConv)(thisCallConv + 2);
#endif

#ifdef HAVE_VIRTUAL_BASE_OFFSET
			// We don't support virtual inheritance
			if( VIRTUAL_BASE_OFFSET(ptr) != 0 )
				return asNOT_SUPPORTED;
#endif
		}
		else
#endif
		if (base == asCALL_GENERIC)
		{
			internal->callConv = ICC_GENERIC_METHOD;
			internal->auxiliary = auxiliary;
		}
		else
			return asNOT_SUPPORTED;
	}

	return 0;
}

// This function should prepare system functions so that it will be faster to call them
int PrepareSystemFunctionGeneric(asCScriptFunction *func, asSSystemFunctionInterface *internal, asCScriptEngine *engine)
{
	asASSERT(internal->callConv == ICC_GENERIC_METHOD || internal->callConv == ICC_GENERIC_FUNC);

	// Calculate the size needed for the parameters
	internal->paramSize = func->GetSpaceNeededForArguments();

	// Prepare the clean up instructions for the function arguments
	internal->cleanArgs.SetLength(0);
	int offset = 0;
	for( asUINT n = 0; n < func->parameterTypes.GetLength(); n++ )
	{
		asCDataType &dt = func->parameterTypes[n];

		if( (dt.IsObject() || dt.IsFuncdef()) && !dt.IsReference() )
		{
			if (dt.IsFuncdef())
			{
				// If the generic call mode is set to old behaviour then always release handles
				// else only release the handle if the function is declared with auto handles
				if (engine->ep.genericCallMode == 0 || (internal->paramAutoHandles.GetLength() > n && internal->paramAutoHandles[n]))
				{
					asSSystemFunctionInterface::SClean clean;
					clean.op = 0; // call release
					clean.ot = &engine->functionBehaviours;
					clean.off = short(offset);
					internal->cleanArgs.PushLast(clean);
				}
			}
			else if( dt.GetTypeInfo()->flags & asOBJ_REF )
			{
				// If the generic call mode is set to old behaviour then always release handles
				// else only release the handle if the function is declared with auto handles
				if (!dt.IsObjectHandle() ||
					engine->ep.genericCallMode == 0 ||
					(internal->paramAutoHandles.GetLength() > n && internal->paramAutoHandles[n]) )
				{
					asSTypeBehaviour *beh = &CastToObjectType(dt.GetTypeInfo())->beh;
					asASSERT((dt.GetTypeInfo()->flags & asOBJ_NOCOUNT) || beh->release);
					if (beh->release)
					{
						asSSystemFunctionInterface::SClean clean;
						clean.op = 0; // call release
						clean.ot = CastToObjectType(dt.GetTypeInfo());
						clean.off = short(offset);
						internal->cleanArgs.PushLast(clean);
					}
				}
			}
			else
			{
				asSSystemFunctionInterface::SClean clean;
				clean.op  = 1; // call free
				clean.ot  = CastToObjectType(dt.GetTypeInfo());
				clean.off = short(offset);

				// Call the destructor then free the memory
				asSTypeBehaviour *beh = &CastToObjectType(dt.GetTypeInfo())->beh;
				if( beh->destruct )
					clean.op = 2; // call destruct, then free

				internal->cleanArgs.PushLast(clean);
			}
		}

		if( dt.IsObject() && !dt.IsObjectHandle() && !dt.IsReference() )
			offset += AS_PTR_SIZE;
		else
			offset += dt.GetSizeOnStackDWords();
	}

	return 0;
}

// This function should prepare system functions so that it will be faster to call them
int PrepareSystemFunction(asCScriptFunction *func, asSSystemFunctionInterface *internal, asCScriptEngine *engine)
{
#ifdef AS_MAX_PORTABILITY
	UNUSED_VAR(func);
	UNUSED_VAR(internal);
	UNUSED_VAR(engine);

	// This should never happen, as when AS_MAX_PORTABILITY is on, all functions
	// are asCALL_GENERIC, which are prepared by PrepareSystemFunctionGeneric
	asASSERT(false);
#else
	// References are always returned as primitive data
	if( func->returnType.IsReference() || func->returnType.IsObjectHandle() )
	{
		internal->hostReturnInMemory = false;
		internal->hostReturnSize     = sizeof(void*)/4;
		internal->hostReturnFloat    = false;
	}
	// Registered types have special flags that determine how they are returned
	else if( func->returnType.IsObject() )
	{
		asQWORD objType = func->returnType.GetTypeInfo()->flags;

		// Only value types can be returned by value
		asASSERT( objType & asOBJ_VALUE );

		if( !(objType & (asOBJ_APP_CLASS | asOBJ_APP_PRIMITIVE | asOBJ_APP_FLOAT | asOBJ_APP_ARRAY)) )
		{
			// If the return is by value then we need to know the true type
			engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, func->GetDeclarationStr().AddressOf());

			asCString str;
			str.Format(TXT_CANNOT_RET_TYPE_s_BY_VAL, func->returnType.GetTypeInfo()->name.AddressOf());
			engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
			engine->ConfigError(asINVALID_CONFIGURATION, 0, 0, 0);
		}
		else if( objType & asOBJ_APP_ARRAY )
		{
			// Array types are always returned in memory
			internal->hostReturnInMemory = true;
			internal->hostReturnSize     = sizeof(void*)/4;
			internal->hostReturnFloat = false;
		}
		else if( objType & asOBJ_APP_CLASS )
		{
			internal->hostReturnFloat = false;
			if( objType & COMPLEX_RETURN_MASK )
			{
				internal->hostReturnInMemory = true;
				internal->hostReturnSize     = sizeof(void*)/4;
			}
			else
			{
#ifdef RETURN_VALUE_MAX_SIZE
				if( func->returnType.GetSizeInMemoryDWords() > RETURN_VALUE_MAX_SIZE )
#elif defined(HAS_128_BIT_PRIMITIVES)
				if( func->returnType.GetSizeInMemoryDWords() > 4 )
#else
				if( func->returnType.GetSizeInMemoryDWords() > 2 )
#endif
				{
					internal->hostReturnInMemory = true;
					internal->hostReturnSize = sizeof(void*)/4;
				}
				else
				{
					internal->hostReturnInMemory = false;
					internal->hostReturnSize = func->returnType.GetSizeInMemoryDWords();
#ifdef SPLIT_OBJS_BY_MEMBER_TYPES
					if (func->returnType.GetTypeInfo()->flags & asOBJ_APP_CLASS_ALLFLOATS)
					{
						internal->hostReturnFloat = true;
#ifdef AS_RISCV64
						// TODO: There shouldn't be platform specific code in this file. Need to have a better way of controlling this
						//       Perhaps by having a specific RETURN_MAX_FLOAT_REGS in as_config
						// On RISC-V 64bit & Linux only structures with two float or doubles can be returned in fa0:fa1
						if (!(func->returnType.GetTypeInfo()->flags & asOBJ_APP_CLASS_ALIGN8) && func->returnType.GetSizeInMemoryDWords() > 2)
						{
							// Since asOBJ_APP_ALIGN8 is not set we assume it is floats, and only 2 floats can be returned in registers
							// In this case the object will not be split by members, and instead it will be returned in a0:a1
							internal->hostReturnFloat = false;
						}
						// On RISC-V 64bit & Linux floats within unions are not returned in fa0:fa1
						if (func->returnType.GetTypeInfo()->flags & asOBJ_APP_CLASS_UNION)
						{
							internal->hostReturnFloat = false;
						}
#endif
					}
#endif
				}

#ifdef THISCALL_RETURN_SIMPLE_IN_MEMORY
				if((internal->callConv == ICC_THISCALL ||
#ifdef AS_NO_THISCALL_FUNCTOR_METHOD
					internal->callConv == ICC_VIRTUAL_THISCALL) &&
#else
					internal->callConv == ICC_VIRTUAL_THISCALL ||
					internal->callConv == ICC_THISCALL_OBJFIRST ||
					internal->callConv == ICC_THISCALL_OBJLAST) &&
#endif
					func->returnType.GetSizeInMemoryDWords() >= THISCALL_RETURN_SIMPLE_IN_MEMORY_MIN_SIZE)
				{
					internal->hostReturnInMemory = true;
					internal->hostReturnSize     = sizeof(void*)/4;
				}
#endif
#ifdef CDECL_RETURN_SIMPLE_IN_MEMORY
				if((internal->callConv == ICC_CDECL         ||
					internal->callConv == ICC_CDECL_OBJLAST ||
					internal->callConv == ICC_CDECL_OBJFIRST) &&
					func->returnType.GetSizeInMemoryDWords() >= CDECL_RETURN_SIMPLE_IN_MEMORY_MIN_SIZE)
				{
					internal->hostReturnInMemory = true;
					internal->hostReturnSize     = sizeof(void*)/4;
				}
#endif
#ifdef STDCALL_RETURN_SIMPLE_IN_MEMORY
				if( internal->callConv == ICC_STDCALL &&
					func->returnType.GetSizeInMemoryDWords() >= STDCALL_RETURN_SIMPLE_IN_MEMORY_MIN_SIZE)
				{
					internal->hostReturnInMemory = true;
					internal->hostReturnSize     = sizeof(void*)/4;
				}
#endif
			}

#ifdef SPLIT_OBJS_BY_MEMBER_TYPES
			// It's not safe to return objects by value because different registers
			// will be used depending on the memory layout of the object.
			// Ref: http://www.x86-64.org/documentation/abi.pdf
			// Ref: http://www.agner.org/optimize/calling_conventions.pdf
			// If the application informs that the class should be treated as all integers, then we allow it
			if( !internal->hostReturnInMemory &&
			    !(func->returnType.GetTypeInfo()->flags & (asOBJ_APP_CLASS_ALLINTS | asOBJ_APP_CLASS_ALLFLOATS)) )
			{
				engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, func->GetDeclarationStr().AddressOf());

				asCString str;
				str.Format(TXT_DONT_SUPPORT_RET_TYPE_s_BY_VAL, func->returnType.Format(func->nameSpace).AddressOf());
				engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
				engine->ConfigError(asINVALID_CONFIGURATION, 0, 0, 0);
			}
#endif
		}
		else if( objType & asOBJ_APP_PRIMITIVE )
		{
			internal->hostReturnInMemory = false;
			internal->hostReturnSize     = func->returnType.GetSizeInMemoryDWords();
			internal->hostReturnFloat    = false;
		}
		else if( objType & asOBJ_APP_FLOAT )
		{
			internal->hostReturnInMemory = false;
			internal->hostReturnSize     = func->returnType.GetSizeInMemoryDWords();
			internal->hostReturnFloat    = true;
		}
	}
	// Primitive types can easily be determined
#ifdef HAS_128_BIT_PRIMITIVES
	else if( func->returnType.GetSizeInMemoryDWords() > 4 )
	{
		// Shouldn't be possible to get here
		asASSERT(false);
	}
	else if( func->returnType.GetSizeInMemoryDWords() == 4 )
	{
		internal->hostReturnInMemory = false;
		internal->hostReturnSize     = 4;
		internal->hostReturnFloat    = false;
	}
#else
	else if( func->returnType.GetSizeInMemoryDWords() > 2 )
	{
		// Shouldn't be possible to get here
		asASSERT(false);
	}
#endif
	else if( func->returnType.GetSizeInMemoryDWords() == 2 )
	{
		internal->hostReturnInMemory = false;
		internal->hostReturnSize     = 2;
		internal->hostReturnFloat    = func->returnType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttDouble, true));
	}
	else if( func->returnType.GetSizeInMemoryDWords() == 1 )
	{
		internal->hostReturnInMemory = false;
		internal->hostReturnSize     = 1;
		internal->hostReturnFloat    = func->returnType.IsEqualExceptConst(asCDataType::CreatePrimitive(ttFloat, true));
	}
	else
	{
		internal->hostReturnInMemory = false;
		internal->hostReturnSize     = 0;
		internal->hostReturnFloat    = false;
	}

	// Calculate the size needed for the parameters
	internal->paramSize = func->GetSpaceNeededForArguments();

	// Verify if the function takes any objects by value
	asUINT n;
	internal->takesObjByVal = false;
	for( n = 0; n < func->parameterTypes.GetLength(); n++ )
	{
		if( func->parameterTypes[n].IsObject() && !func->parameterTypes[n].IsObjectHandle() && !func->parameterTypes[n].IsReference() )
		{
			internal->takesObjByVal = true;

			// Can't pass objects by value unless the application type is informed
			if( !(func->parameterTypes[n].GetTypeInfo()->flags & (asOBJ_APP_CLASS | asOBJ_APP_PRIMITIVE | asOBJ_APP_FLOAT | asOBJ_APP_ARRAY)) )
			{
				engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, func->GetDeclarationStr().AddressOf());

				asCString str;
				str.Format(TXT_CANNOT_PASS_TYPE_s_BY_VAL, func->parameterTypes[n].GetTypeInfo()->name.AddressOf());
				engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
				engine->ConfigError(asINVALID_CONFIGURATION, 0, 0, 0);
			}

#ifdef SPLIT_OBJS_BY_MEMBER_TYPES
			// It's not safe to pass objects by value because different registers
			// will be used depending on the memory layout of the object
			// Ref: http://www.x86-64.org/documentation/abi.pdf
			// Ref: http://www.agner.org/optimize/calling_conventions.pdf
			if(
#ifdef COMPLEX_OBJS_PASSED_BY_REF
			    !(func->parameterTypes[n].GetTypeInfo()->flags & COMPLEX_MASK) &&
#endif
#ifdef LARGE_OBJS_PASS_BY_REF
			    func->parameterTypes[n].GetSizeInMemoryDWords() < AS_LARGE_OBJ_MIN_SIZE &&
#endif
			    !(func->parameterTypes[n].GetTypeInfo()->flags & (asOBJ_APP_PRIMITIVE | asOBJ_APP_FLOAT | asOBJ_APP_CLASS_ALLINTS | asOBJ_APP_CLASS_ALLFLOATS)) )
			{
				engine->WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, func->GetDeclarationStr().AddressOf());

				asCString str;
				str.Format(TXT_DONT_SUPPORT_TYPE_s_BY_VAL, func->parameterTypes[n].GetTypeInfo()->name.AddressOf());
				engine->WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
				engine->ConfigError(asINVALID_CONFIGURATION, 0, 0, 0);
			}
#endif
			break;
		}
	}

	// Prepare the clean up instructions for the function arguments
	internal->cleanArgs.SetLength(0);
	int offset = 0;
	for( n = 0; n < func->parameterTypes.GetLength(); n++ )
	{
		asCDataType &dt = func->parameterTypes[n];

#if defined(COMPLEX_OBJS_PASSED_BY_REF) || defined(AS_LARGE_OBJS_PASSED_BY_REF)
		bool needFree = false;
#ifdef COMPLEX_OBJS_PASSED_BY_REF
		if( dt.GetTypeInfo() && dt.GetTypeInfo()->flags & COMPLEX_MASK ) needFree = true;
#endif
#ifdef AS_LARGE_OBJS_PASSED_BY_REF
		if( dt.GetSizeInMemoryDWords() >= AS_LARGE_OBJ_MIN_SIZE ) needFree = true;
#endif
		if( needFree &&
			dt.IsObject() &&
			!dt.IsObjectHandle() &&
			!dt.IsReference() )
		{
			asSSystemFunctionInterface::SClean clean;
			clean.op  = 1; // call free
			clean.ot  = CastToObjectType(dt.GetTypeInfo());
			clean.off = short(offset);

#ifndef AS_CALLEE_DESTROY_OBJ_BY_VAL
			// If the called function doesn't destroy objects passed by value we must do so here
			asSTypeBehaviour *beh = &CastToObjectType(dt.GetTypeInfo())->beh;
			if( beh->destruct )
				clean.op = 2; // call destruct, then free
#endif

			internal->cleanArgs.PushLast(clean);
		}
#endif

		if( n < internal->paramAutoHandles.GetLength() && internal->paramAutoHandles[n] )
		{
			asSSystemFunctionInterface::SClean clean;
			clean.op  = 0; // call release
			if (dt.IsFuncdef())
				clean.ot = &engine->functionBehaviours;
			else
				clean.ot  = CastToObjectType(dt.GetTypeInfo());
			clean.off = short(offset);
			internal->cleanArgs.PushLast(clean);
		}

		if( dt.IsObject() && !dt.IsObjectHandle() && !dt.IsReference() )
			offset += AS_PTR_SIZE;
		else
			offset += dt.GetSizeOnStackDWords();
	}
#endif // !defined(AS_MAX_PORTABILITY)
	return 0;
}

#ifdef AS_MAX_PORTABILITY

int CallSystemFunction(int id, asCContext *context)
{
	asCScriptEngine *engine = context->m_engine;
	asCScriptFunction *func = engine->scriptFunctions[id];
	asSSystemFunctionInterface *sysFunc = func->sysFuncIntf;
	int callConv = sysFunc->callConv;
	if( callConv == ICC_GENERIC_FUNC || callConv == ICC_GENERIC_METHOD )
		return context->CallGeneric(func);

	context->SetInternalException(TXT_INVALID_CALLING_CONVENTION);

	return 0;
}

#else

// TODO: cleanup: Should have only a single CallSystemFunctionNative function signature. However changing it requires retesting all different native platforms :(

#ifndef RETURN_VALUE_MAX_SIZE

//
// CallSystemFunctionNative
//
// This function is implemented for each platform where the native calling conventions is supported.
// See the various as_callfunc_xxx.cpp files for their implementation. It is responsible for preparing
// the arguments for the function call, calling the function, and then retrieving the return value.
//
// Parameters:
//
// context    - This is the context that can be used to retrieve specific information from the engine
// descr      - This is the script function object that holds the information on how to call the function
// obj        - This is the object pointer, if the call is for a class method, otherwise it is null
// args       - This is the function arguments, which are packed as in AngelScript
// retPointer - This points to a the memory buffer where the return object is to be placed, if the function returns the value in memory rather than in registers
// retQW2     - This output parameter should be used if the function returns a value larger than 64bits in registers
// secondObj  - This is the object pointer that the proxy method should invoke its method on when the call convention is THISCALL_OBJFIRST/LAST
//
// Return value:
//
// The function should return the value that is returned in registers.
asQWORD CallSystemFunctionNative(asCContext *context, asCScriptFunction *descr, void *obj, asDWORD *args, void *retPointer, asQWORD &retQW2, void *secondObj);

#else

//
// CallSystemFunctionNative
//
// This function is implemented for each platform where the native calling conventions is supported.
// See the various as_callfunc_xxx.cpp files for their implementation. It is responsible for preparing
// the arguments for the function call, calling the function, and then retrieving the return value.
//
// Parameters:
//
// context    - This is the context that can be used to retrieve specific information from the engine
// descr      - This is the script function object that holds the information on how to call the function
// obj        - This is the object pointer, if the call is for a class method, otherwise it is null
// args       - This is the function arguments, which are packed as in AngelScript
// retPointer - This points to a the memory buffer where the return object is to be placed, if the function returns the value in memory rather than in registers
// retQW      - This output parameter should be used if the function returns a value in registers. This is a pointer to an array of QWORDs
// secondObj  - This is the object pointer that the proxy method should invoke its method on when the call convention is THISCALL_OBJFIRST/LAST
void CallSystemFunctionNative(asCContext *context, asCScriptFunction *descr, void *obj, asDWORD *args, void *retPointer, asQWORD *retQW, void *secondObj);

#endif

int CallSystemFunction(int id, asCContext *context)
{
	asCScriptEngine            *engine  = context->m_engine;
	asCScriptFunction          *descr   = engine->scriptFunctions[id];
	asSSystemFunctionInterface *sysFunc = descr->sysFuncIntf;

	int callConv = sysFunc->callConv;
	if( callConv == ICC_GENERIC_FUNC || callConv == ICC_GENERIC_METHOD )
		return context->CallGeneric(descr);

#ifndef RETURN_VALUE_MAX_SIZE
	asQWORD retQW[2] = { 0 };
#else
	asQWORD retQW[(RETURN_VALUE_MAX_SIZE + 1) / 2] = { 0 };
#endif
	asDWORD *args              = context->m_regs.stackPointer;
	void    *retPointer        = 0;
	int      popSize           = sysFunc->paramSize;

	// TODO: clean-up: CallSystemFunctionNative should have two arguments for object pointers
	//                 objForThiscall is the object pointer that should be used for the thiscall
	//                 objForArg is the object pointer that should be passed as argument when using OBJFIRST or OBJLAST

	// Used to save two object pointers with THISCALL_OBJLAST or THISCALL_OBJFIRST
	void *obj = 0;
	void *secondObj = 0;

#ifdef AS_NO_THISCALL_FUNCTOR_METHOD
	if( callConv >= ICC_THISCALL )
	{
		if(sysFunc->auxiliary)
		{
			// This class method is being called as if it is a global function
			obj = sysFunc->auxiliary;
		}
		else
		{
			// The object pointer should be popped from the context stack
			popSize += AS_PTR_SIZE;

			// Check for null pointer
			obj = (void*)*(asPWORD*)(args);
			if( obj == 0 )
			{
				context->SetInternalException(TXT_NULL_POINTER_ACCESS);
				return 0;
			}

			// Skip the object pointer
			args += AS_PTR_SIZE;
		}

		// Add the base offset for multiple inheritance
#if (defined(__GNUC__) && (defined(AS_ARM64) || defined(AS_ARM) || defined(AS_MIPS))) || defined(AS_PSVITA)
		// On GNUC + ARM the lsb of the offset is used to indicate a virtual function
		// and the whole offset is thus shifted one bit left to keep the original
		// offset resolution
		// MIPS also work like ARM in this regard
		obj = (void*)(asPWORD(obj) + (sysFunc->baseOffset>>1));
#else
		obj = (void*)(asPWORD(obj) + sysFunc->baseOffset);
#endif
	}
#else // !defined(AS_NO_THISCALL_FUNCTOR_METHOD)

	if( callConv >= ICC_THISCALL )
	{
		bool continueCheck = true;  // True if need check objectPointer or context stack for object
		int continueCheckIndex = 0; // Index into objectsPtrs to save the object if continueCheck

		if( callConv >= ICC_THISCALL_OBJLAST )
		{
			asASSERT( sysFunc->auxiliary != 0 );
			// This class method is being called as object method (sysFunc->auxiliary must be set).
			obj = sysFunc->auxiliary;
			continueCheckIndex = 1;
		}
		else if(sysFunc->auxiliary)
		{
			// This class method is being called as if it is a global function
			obj = sysFunc->auxiliary;
			continueCheck = false;
		}

		if( obj )
		{
			// For composition we need to add the offset and/or dereference the pointer
			obj = (void*)((char*)obj + sysFunc->compositeOffset);
			if (sysFunc->isCompositeIndirect) obj = *((void**)obj);

			// Add the base offset for multiple inheritance
#if (defined(__GNUC__) && (defined(AS_ARM64) || defined(AS_ARM) || defined(AS_MIPS))) || defined(AS_PSVITA)
			// On GNUC + ARM the lsb of the offset is used to indicate a virtual function
			// and the whole offset is thus shifted one bit left to keep the original
			// offset resolution
			// MIPS also work like ARM in this regard
			obj = (void*)(asPWORD(obj) + (sysFunc->baseOffset>>1));
#else
			obj = (void*)(asPWORD(obj) + sysFunc->baseOffset);
#endif
		}

		if( continueCheck )
		{
			void *tempPtr = 0;

			// The object pointer should be popped from the context stack
			popSize += AS_PTR_SIZE;

			// Check for null pointer
			tempPtr = (void*)*(asPWORD*)(args);
			if( tempPtr == 0 )
			{
				context->SetInternalException(TXT_NULL_POINTER_ACCESS);
				return 0;
			}

			// For composition we need to add the offset and/or dereference the pointer
			tempPtr = (void*)((char*)tempPtr + sysFunc->compositeOffset);
			if (sysFunc->isCompositeIndirect) tempPtr = *((void**)tempPtr);

			// Add the base offset for multiple inheritance
#if (defined(__GNUC__) && (defined(AS_ARM64) || defined(AS_ARM) || defined(AS_MIPS))) || defined(AS_PSVITA)
			// On GNUC + ARM the lsb of the offset is used to indicate a virtual function
			// and the whole offset is thus shifted one bit left to keep the original
			// offset resolution
			// MIPS also work like ARM in this regard
			tempPtr = (void*)(asPWORD(tempPtr) + (sysFunc->baseOffset>>1));
#else
			tempPtr = (void*)(asPWORD(tempPtr) + sysFunc->baseOffset);
#endif

			// Skip the object pointer
			args += AS_PTR_SIZE;

			if( continueCheckIndex )
				secondObj = tempPtr;
			else
			{
				asASSERT( obj == 0 );
				obj = tempPtr;
			}
		}
	}
#endif // AS_NO_THISCALL_FUNCTOR_METHOD

	if( descr->DoesReturnOnStack() )
	{
		// Get the address of the location for the return value from the stack
		retPointer = (void*)*(asPWORD*)(args);
		popSize += AS_PTR_SIZE;
		args += AS_PTR_SIZE;

		// When returning the value on the location allocated by the called
		// we shouldn't set the object type in the register
		context->m_regs.objectType = 0;
	}
	else
	{
		// Set the object type of the reference held in the register
		context->m_regs.objectType = descr->returnType.GetTypeInfo();
	}

	context->m_callingSystemFunction = descr;
	bool cppException = false;
#ifdef AS_NO_EXCEPTIONS
#ifndef RETURN_VALUE_MAX_SIZE
	retQW[0] = CallSystemFunctionNative(context, descr, obj, args, sysFunc->hostReturnInMemory ? retPointer : 0, retQW[1], secondObj);
#else
	CallSystemFunctionNative(context, descr, obj, args, sysFunc->hostReturnInMemory ? retPointer : 0, retQW, secondObj);
#endif
#else
	// This try/catch block is to catch potential exception that may
	// be thrown by the registered function. The implementation of the
	// CallSystemFunctionNative() must make sure not to have any manual
	// clean-up after the call to the real function, or that won't be
	// executed in case of an exception.
	try
	{
#ifndef RETURN_VALUE_MAX_SIZE
		retQW[0] = CallSystemFunctionNative(context, descr, obj, args, sysFunc->hostReturnInMemory ? retPointer : 0, retQW[1], secondObj);
#else
		CallSystemFunctionNative(context, descr, obj, args, sysFunc->hostReturnInMemory ? retPointer : 0, retQW, secondObj);
#endif
	}
	catch(...)
	{
		cppException = true;

		// Convert the exception to a script exception so the VM can
		// properly report the error to the application and then clean up
		context->HandleAppException();
	}
#endif
	context->m_callingSystemFunction = 0;

	// Store the returned value in our stack
	if( (descr->returnType.IsObject() || descr->returnType.IsFuncdef()) && !descr->returnType.IsReference() )
	{
		if (descr->returnType.IsObjectHandle())
		{
#if defined(AS_BIG_ENDIAN) && AS_PTR_SIZE == 1
			// Since we're treating the system function as if it is returning a QWORD we are
			// actually receiving the value in the high DWORD of retQW[0].
			retQW[0] >>= 32;
#endif

			context->m_regs.objectRegister = (void*)(asPWORD)retQW[0];

			if (sysFunc->returnAutoHandle && context->m_regs.objectRegister)
			{
				asASSERT(!(descr->returnType.GetTypeInfo()->flags & asOBJ_NOCOUNT));
				engine->CallObjectMethod(context->m_regs.objectRegister, CastToObjectType(descr->returnType.GetTypeInfo())->beh.addref);
			}
		}
		else if (retPointer)
		{
			if (!sysFunc->hostReturnInMemory)
			{
				// Copy the returned value to the pointer sent by the script engine
				if (sysFunc->hostReturnSize == 1)
				{
#if defined(AS_BIG_ENDIAN) && AS_PTR_SIZE == 1
					// Since we're treating the system function as if it is returning a QWORD we are
					// actually receiving the value in the high DWORD of retQW[0].
					retQW[0] >>= 32;
#endif

					*(asDWORD*)retPointer = (asDWORD)retQW[0];
				}
				else if (sysFunc->hostReturnSize == 2)
					*(asQWORD*)retPointer = retQW[0];
				else if (sysFunc->hostReturnSize == 3)
				{
					*(asQWORD*)retPointer = retQW[0];
					*(((asDWORD*)retPointer) + 2) = (asDWORD)retQW[1];
				}
				else if( sysFunc->hostReturnSize == 4 )
				{
					*(asQWORD*)retPointer = retQW[0];
					*(((asQWORD*)retPointer) + 1) = retQW[1];
				}
				else
				{
					memcpy(retPointer, retQW, sysFunc->hostReturnSize * sizeof(asDWORD));
				}
			}

			if (context->m_status == asEXECUTION_EXCEPTION && !cppException)
			{
				// If the function raised a script exception it really shouldn't have
				// initialized the object. However, as it is a soft exception there is
				// no way for the application to not return a value, so instead we simply
				// destroy it here, to pretend it was never created.
				if (CastToObjectType(descr->returnType.GetTypeInfo())->beh.destruct)
					engine->CallObjectMethod(retPointer, CastToObjectType(descr->returnType.GetTypeInfo())->beh.destruct);
			}
		}
		else
		{
			// Ths should not be possible
			asASSERT(false);
		}
	}
	else
	{
		// Store value in value register
		if( sysFunc->hostReturnSize == 1 )
		{
#if defined(AS_BIG_ENDIAN)
			// Since we're treating the system function as if it is returning a QWORD we are
			// actually receiving the value in the high DWORD of retQW[0].
			retQW[0] >>= 32;

			// Due to endian issues we need to handle return values that are
			// less than a DWORD (32 bits) in size specially
			int numBytes = descr->returnType.GetSizeInMemoryBytes();
			if( descr->returnType.IsReference() ) numBytes = 4;
			switch( numBytes )
			{
			case 1:
				{
					// 8 bits
					asBYTE *val = (asBYTE*)&context->m_regs.valueRegister;
					val[0] = (asBYTE)retQW[0];
					val[1] = 0;
					val[2] = 0;
					val[3] = 0;
					val[4] = 0;
					val[5] = 0;
					val[6] = 0;
					val[7] = 0;
				}
				break;
			case 2:
				{
					// 16 bits
					asWORD *val = (asWORD*)&context->m_regs.valueRegister;
					val[0] = (asWORD)retQW[0];
					val[1] = 0;
					val[2] = 0;
					val[3] = 0;
				}
				break;
			default:
				{
					// 32 bits
					asDWORD *val = (asDWORD*)&context->m_regs.valueRegister;
					val[0] = (asDWORD)retQW[0];
					val[1] = 0;
				}
				break;
			}
#else
			*(asDWORD*)&context->m_regs.valueRegister = (asDWORD)retQW[0];
#endif
		}
		else
			context->m_regs.valueRegister = retQW[0];
	}

	// Clean up arguments
	const asUINT cleanCount = sysFunc->cleanArgs.GetLength();
	if( cleanCount )
	{
		args = context->m_regs.stackPointer;

		// Skip the hidden argument for the return pointer
		// TODO: runtime optimize: This check and increment should have been done in PrepareSystemFunction
		if( descr->DoesReturnOnStack() )
			args += AS_PTR_SIZE;

		// Skip the object pointer on the stack
		// TODO: runtime optimize: This check and increment should have been done in PrepareSystemFunction
		if( callConv >= ICC_THISCALL && sysFunc->auxiliary == 0 )
			args += AS_PTR_SIZE;

		asSSystemFunctionInterface::SClean *clean = sysFunc->cleanArgs.AddressOf();
		for( asUINT n = 0; n < cleanCount; n++, clean++ )
		{
			void **addr = (void**)&args[clean->off];
			if( clean->op == 0 )
			{
				if( *addr != 0 )
				{
					engine->CallObjectMethod(*addr, clean->ot->beh.release);
					*addr = 0;
				}
			}
			else
			{
				asASSERT( clean->op == 1 || clean->op == 2 );
				asASSERT( *addr );

				if( clean->op == 2 )
					engine->CallObjectMethod(*addr, clean->ot->beh.destruct);

				engine->CallFree(*addr);
			}
		}
	}

	return popSize;
}

#endif // AS_MAX_PORTABILITY

END_AS_NAMESPACE


code:
/*
   AngelCode Scripting Library
   Copyright (c) 2003-2021 Andreas Jonsson

   This software is provided 'as-is', without any express or implied
   warranty. In no event will the authors be held liable for any
   damages arising from the use of this software.

   Permission is granted to anyone to use this software for any
   purpose, including commercial applications, and to alter it and
   redistribute it freely, subject to the following restrictions:

   1. The origin of this software must not be misrepresented; you
      must not claim that you wrote the original software. If you use
      this software in a product, an acknowledgment in the product
      documentation would be appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and
      must not be misrepresented as being the original software.

   3. This notice may not be removed or altered from any source
      distribution.

   The original version of this library can be located at:
   http://www.angelcode.com/angelscript/

   Andreas Jonsson
   andreas@angelcode.com
*/

//
// as_callfunc.h
//
// These functions handle the actual calling of system functions
//

#ifndef AS_CALLFUNC_H
#define AS_CALLFUNC_H

#include "as_array.h"

BEGIN_AS_NAMESPACE

class asCContext;
class asCScriptEngine;
class asCScriptFunction;
class asCObjectType;
struct asSSystemFunctionInterface;

int DetectCallingConvention(bool isMethod, const asSFuncPtr &ptr, int callConv, void *auxiliary, asSSystemFunctionInterface *internal);

int PrepareSystemFunctionGeneric(asCScriptFunction *func, asSSystemFunctionInterface *internal, asCScriptEngine *engine);

int PrepareSystemFunction(asCScriptFunction *func, asSSystemFunctionInterface *internal, asCScriptEngine *engine);

int CallSystemFunction(int id, asCContext *context);

inline asPWORD FuncPtrToUInt(asFUNCTION_t func)
{
	// A little trickery as the C++ standard doesn't allow direct
	// conversion between function pointer and data pointer
	union { asFUNCTION_t func; asPWORD idx; } u;
	u.func = func;

	return u.idx;
}

enum internalCallConv
{
	ICC_GENERIC_FUNC,
	ICC_GENERIC_FUNC_RETURNINMEM, // never used
	ICC_CDECL,
	ICC_CDECL_RETURNINMEM,
	ICC_STDCALL,
	ICC_STDCALL_RETURNINMEM,
	ICC_THISCALL,
	ICC_THISCALL_RETURNINMEM,
	ICC_VIRTUAL_THISCALL,
	ICC_VIRTUAL_THISCALL_RETURNINMEM,
	ICC_CDECL_OBJLAST,
	ICC_CDECL_OBJLAST_RETURNINMEM,
	ICC_CDECL_OBJFIRST,
	ICC_CDECL_OBJFIRST_RETURNINMEM,
	ICC_GENERIC_METHOD,
	ICC_GENERIC_METHOD_RETURNINMEM, // never used
	ICC_THISCALL_OBJLAST,
	ICC_THISCALL_OBJLAST_RETURNINMEM,
	ICC_VIRTUAL_THISCALL_OBJLAST,
	ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM,
	ICC_THISCALL_OBJFIRST,
	ICC_THISCALL_OBJFIRST_RETURNINMEM,
	ICC_VIRTUAL_THISCALL_OBJFIRST,
	ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM
};

struct asSSystemFunctionInterface
{
	asFUNCTION_t         func;
	int                  baseOffset;
	internalCallConv     callConv;
	bool                 hostReturnInMemory;
	bool                 hostReturnFloat;
	int                  hostReturnSize;
	int                  paramSize;
	bool                 takesObjByVal;
	asCArray<bool>       paramAutoHandles; // TODO: Should be able to remove this array. Perhaps the flags can be stored together with the inOutFlags in asCScriptFunction?
	bool                 returnAutoHandle;
	int                  compositeOffset;
	bool                 isCompositeIndirect;
	void                *auxiliary; // can be used for functors, e.g. by asCALL_THISCALL_ASGLOBAL or asCALL_THISCALL_OBJFIRST

	struct SClean
	{
		asCObjectType *ot; // argument type for clean up
		short op;          // clean up operation: 0 = release, 1 = free, 2 = destruct then free
		short off;         // argument offset on the stack
	};
	asCArray<SClean>     cleanArgs;

	asSSystemFunctionInterface()
	{
		Clear();
	}

	asSSystemFunctionInterface(const asSSystemFunctionInterface &in)
	{
		*this = in;
	}

	void Clear()
	{
		func                = 0;
		baseOffset          = 0;
		callConv            = ICC_GENERIC_FUNC;
		hostReturnInMemory  = false;
		hostReturnFloat     = false;
		hostReturnSize      = 0;
		paramSize           = 0;
		takesObjByVal       = false;
		returnAutoHandle    = false;
		compositeOffset     = 0;
		isCompositeIndirect = false;
		auxiliary           = 0;

		paramAutoHandles.SetLength(0);
		cleanArgs.SetLength(0);
	}

	asSSystemFunctionInterface &operator=(const asSSystemFunctionInterface &in)
	{
		func                = in.func;
		baseOffset          = in.baseOffset;
		callConv            = in.callConv;
		hostReturnInMemory  = in.hostReturnInMemory;
		hostReturnFloat     = in.hostReturnFloat;
		hostReturnSize      = in.hostReturnSize;
		paramSize           = in.paramSize;
		takesObjByVal       = in.takesObjByVal;
		returnAutoHandle    = in.returnAutoHandle;
		compositeOffset     = in.compositeOffset;
		isCompositeIndirect = in.isCompositeIndirect;
		auxiliary           = in.auxiliary;

		cleanArgs           = in.cleanArgs;
		paramAutoHandles    = in.paramAutoHandles;

		return *this;
	}
};

END_AS_NAMESPACE

#endif

repo_name: Antidote/openrpgeditor

license: mit


code:
/*
   AngelCode Scripting Library
   Copyright (c) 2003-2015 Andreas Jonsson

   This software is provided 'as-is', without any express or implied
   warranty. In no event will the authors be held liable for any
   damages arising from the use of this software.

   Permission is granted to anyone to use this software for any
   purpose, including commercial applications, and to alter it and
   redistribute it freely, subject to the following restrictions:

   1. The origin of this software must not be misrepresented; you
      must not claim that you wrote the original software. If you use
      this software in a product, an acknowledgment in the product
      documentation would be appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and
      must not be misrepresented as being the original software.

   3. This notice may not be removed or altered from any source
      distribution.

   The original version of this library can be located at:
   http://www.angelcode.com/angelscript/

   Andreas Jonsson
   andreas@angelcode.com
*/

//
// as_callfunc_arm.cpp
//
// These functions handle the actual calling of system functions on the arm platform
//
// Written by Fredrik Ehnbom in June 2009, based on as_callfunc_x86.cpp
//
// The code was complemented to support Linux with ARM by Carlos Luna in December, 2012.
//
// Added support for functor methods by Jordi Oliveras Rovira in April, 2014.

// This code has to conform to both AAPCS and the modified ABI for iOS
//
// Reference:
//
// AAPCS: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
// iOS: http://developer.apple.com/library/ios/documentation/Xcode/Conceptual/iPhoneOSABIReference/iPhoneOSABIReference.pdf

#include "as_config.h"

#ifndef AS_MAX_PORTABILITY
#ifdef AS_ARM

#include "as_callfunc.h"
#include "as_scriptengine.h"
#include "as_texts.h"
#include "as_tokendef.h"
#include "as_context.h"

#if defined(AS_SOFTFP)

// This code supports the soft-float ABI, i.e. g++ -mfloat-abi=softfp
//
// The code for iOS, Android, Marmalade and Windows Phone goes here

BEGIN_AS_NAMESPACE

extern "C" asQWORD armFunc          (const asDWORD *, int, asFUNCTION_t);
extern "C" asQWORD armFuncR0        (const asDWORD *, int, asFUNCTION_t, asDWORD r0);
extern "C" asQWORD armFuncR0R1      (const asDWORD *, int, asFUNCTION_t, asDWORD r0, asDWORD r1);
extern "C" asQWORD armFuncObjLast   (const asDWORD *, int, asFUNCTION_t, asDWORD obj);
extern "C" asQWORD armFuncR0ObjLast (const asDWORD *, int, asFUNCTION_t, asDWORD r0, asDWORD obj);

asQWORD CallSystemFunctionNative(asCContext *context, asCScriptFunction *descr, void *obj, asDWORD *args, void *retPointer, asQWORD &/*retQW2*/, void *secondObject)
{
	asCScriptEngine *engine = context->m_engine;
	asSSystemFunctionInterface *sysFunc = descr->sysFuncIntf;
	int callConv = sysFunc->callConv;

	asQWORD       retQW     = 0;
	asFUNCTION_t  func      = sysFunc->func;
	int           paramSize = sysFunc->paramSize;
	asFUNCTION_t *vftable;

	if( sysFunc->hostReturnInMemory )
	{
		// The return is made in memory
		callConv++;
	}
	bool isThisCallMethod = callConv >= ICC_THISCALL_OBJLAST;

	asDWORD paramBuffer[64+2];
	// Android & Linux needs to align 64bit types on even registers, but this isn't done on iOS or Windows Phone
	// TODO: optimize runtime: There should be a check for this in PrepareSystemFunction() so this
	//                         doesn't have to be done for functions that don't have any 64bit types
#if !defined(AS_ANDROID) && !defined(AS_LINUX)
	// In cases of thiscall methods, the callstack is configured as a standard thiscall
	// adding the secondObject as first or last element in callstack
	if( sysFunc->takesObjByVal || isThisCallMethod )
#endif
	{
#if defined(AS_ANDROID) || defined(AS_LINUX)
		// mask is used as a toggler to skip uneven registers.
		int mask = 1;

		if( isThisCallMethod )
		{
			mask = 0;
		}
		else
		{
			// Check for object pointer as first argument
			switch( callConv )
			{
				case ICC_THISCALL:
				case ICC_CDECL_OBJFIRST:
				case ICC_VIRTUAL_THISCALL:
				case ICC_THISCALL_RETURNINMEM:
				case ICC_CDECL_OBJFIRST_RETURNINMEM:
				case ICC_VIRTUAL_THISCALL_RETURNINMEM:
					mask = 0;
					break;
				default:
					break;
			}
		}

		// Check for hidden address in case of return by value
		if( sysFunc->hostReturnInMemory )
			mask = !mask;
#endif
		paramSize = 0;
		int spos = 0;
		int dpos = 2;

		if( isThisCallMethod && (callConv >= ICC_THISCALL_OBJFIRST &&
			callConv <= ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM) )
		{
			// Add the object pointer as the first parameter
			paramBuffer[dpos++] = (asDWORD)secondObject;
			paramSize++;
		}

		for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
		{
			// TODO: runtime optimize: Declare a reference to descr->parameterTypes[n] so the array doesn't have to be access all the time
			if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() && !descr->parameterTypes[n].IsReference() )
			{
#ifdef COMPLEX_OBJS_PASSED_BY_REF
				if( descr->parameterTypes[n].GetTypeInfo()->flags & COMPLEX_MASK )
				{
					paramBuffer[dpos++] = args[spos++];
					paramSize++;
				}
				else
#endif
				{
#if defined(AS_ANDROID) || defined(AS_LINUX)
					if( (descr->parameterTypes[n].GetTypeInfo()->flags & asOBJ_APP_CLASS_ALIGN8) &&
						((dpos & 1) == mask) )
					{
						// 64 bit value align
						dpos++;
						paramSize++;
					}
#endif
					// Copy the object's memory to the buffer
					memcpy(&paramBuffer[dpos], *(void**)(args+spos), descr->parameterTypes[n].GetSizeInMemoryBytes());

					// Delete the original memory
					engine->CallFree(*(char**)(args+spos));
					spos++;
					dpos += descr->parameterTypes[n].GetSizeInMemoryDWords();
					paramSize += descr->parameterTypes[n].GetSizeInMemoryDWords();
				}
			}
			else
			{
#if defined(AS_ANDROID) || defined(AS_LINUX)
				// Should an alignment be performed?
				if( !descr->parameterTypes[n].IsObjectHandle() &&
					!descr->parameterTypes[n].IsReference() &&
					descr->parameterTypes[n].GetSizeOnStackDWords() == 2 &&
					((dpos & 1) == mask) )
				{
					// 64 bit value align
					dpos++;
					paramSize++;
				}
#endif

				// Copy the value directly
				paramBuffer[dpos++] = args[spos++];
				if( descr->parameterTypes[n].GetSizeOnStackDWords() > 1 )
					paramBuffer[dpos++] = args[spos++];
				paramSize += descr->parameterTypes[n].GetSizeOnStackDWords();
			}
		}

		if( isThisCallMethod && (callConv >= ICC_THISCALL_OBJLAST &&
			callConv <= ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM) )
		{
			// Add the object pointer as the last parameter
			paramBuffer[dpos++] = (asDWORD)secondObject;
			paramSize++;
		}

		// Keep a free location at the beginning
		args = &paramBuffer[2];
	}

	switch( callConv )
	{
	case ICC_CDECL_RETURNINMEM:     // fall through
	case ICC_STDCALL_RETURNINMEM:
		retQW = armFuncR0(args, paramSize<<2, func, (asDWORD)retPointer);
		break;
	case ICC_CDECL:     // fall through
	case ICC_STDCALL:
		retQW = armFunc(args, paramSize<<2, func);
		break;
	case ICC_THISCALL:  // fall through
	case ICC_CDECL_OBJFIRST:
	case ICC_THISCALL_OBJFIRST:
	case ICC_THISCALL_OBJLAST:
		retQW = armFuncR0(args, paramSize<<2, func, (asDWORD)obj);
		break;
	case ICC_THISCALL_RETURNINMEM:
	case ICC_THISCALL_OBJFIRST_RETURNINMEM:
	case ICC_THISCALL_OBJLAST_RETURNINMEM:
#ifdef __GNUC__
		// On GNUC the address where the return value will be placed should be put in R0
		retQW = armFuncR0R1(args, paramSize<<2, func, (asDWORD)retPointer, (asDWORD)obj);
#else
		// On Windows the R0 should always hold the object pointer, and the address for the return value comes after
		retQW = armFuncR0R1(args, paramSize<<2, func, (asDWORD)obj, (asDWORD)retPointer);
#endif
		break;
	case ICC_CDECL_OBJFIRST_RETURNINMEM:
		retQW = armFuncR0R1(args, paramSize<<2, func, (asDWORD)retPointer, (asDWORD)obj);
		break;
	case ICC_VIRTUAL_THISCALL:
	case ICC_VIRTUAL_THISCALL_OBJFIRST:
	case ICC_VIRTUAL_THISCALL_OBJLAST:
		// Get virtual function table from the object pointer
		vftable = *(asFUNCTION_t**)obj;
		retQW = armFuncR0(args, paramSize<<2, vftable[FuncPtrToUInt(func)>>2], (asDWORD)obj);
		break;
	case ICC_VIRTUAL_THISCALL_RETURNINMEM:
	case ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM:
	case ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM:
		// Get virtual function table from the object pointer
		vftable = *(asFUNCTION_t**)obj;
#ifdef __GNUC__
		// On GNUC the address where the return value will be placed should be put in R0
		retQW = armFuncR0R1(args, (paramSize+1)<<2, vftable[FuncPtrToUInt(func)>>2], (asDWORD)retPointer, (asDWORD)obj);
#else
		// On Windows the R0 should always hold the object pointer, and the address for the return value comes after
		retQW = armFuncR0R1(args, (paramSize+1)<<2, vftable[FuncPtrToUInt(func)>>2], (asDWORD)obj, (asDWORD)retPointer);
#endif
		break;
	case ICC_CDECL_OBJLAST:
		retQW = armFuncObjLast(args, paramSize<<2, func, (asDWORD)obj);
		break;
	case ICC_CDECL_OBJLAST_RETURNINMEM:
		retQW = armFuncR0ObjLast(args, paramSize<<2, func, (asDWORD)retPointer, (asDWORD)obj);
		break;
	default:
		context->SetInternalException(TXT_INVALID_CALLING_CONVENTION);
	}

	return retQW;
}

END_AS_NAMESPACE

#elif !defined(AS_SOFTFP)

// This code supports the hard-float ABI, i.e. g++ -mfloat-abi=hard
// The main difference is that the floating point values are passed in the fpu registers

#define VFP_OFFSET 70
#define STACK_OFFSET 6
#define PARAM_BUFFER_SIZE 104

BEGIN_AS_NAMESPACE

extern "C" asQWORD armFunc          (const asDWORD *, int, asFUNCTION_t);
extern "C" asQWORD armFuncR0        (const asDWORD *, int, asFUNCTION_t, asDWORD r0);
extern "C" asQWORD armFuncR0R1      (const asDWORD *, int, asFUNCTION_t, asDWORD r0, asDWORD r1);
extern "C" asQWORD armFuncObjLast   (const asDWORD *, int, asFUNCTION_t, asDWORD obj);
extern "C" asQWORD armFuncR0ObjLast (const asDWORD *, int, asFUNCTION_t, asDWORD r0, asDWORD obj);

asQWORD CallSystemFunctionNative(asCContext *context, asCScriptFunction *descr, void *obj, asDWORD *args, void *retPointer, asQWORD &/*retQW2*/, void *secondObject)
{
	asCScriptEngine *engine = context->m_engine;
	asSSystemFunctionInterface *sysFunc = descr->sysFuncIntf;
	int callConv = sysFunc->callConv;

	asQWORD       retQW     = 0;
	asFUNCTION_t  func      = sysFunc->func;
	int           paramSize = sysFunc->paramSize;
	asFUNCTION_t *vftable;

	//---------------------------------------------------------------------------- RPi
	int freeFloatSlot	= VFP_OFFSET;
	int freeDoubleSlot	= VFP_OFFSET;
	int stackPos		= STACK_OFFSET;
	int stackSize		= 0;
	//----------------------------------------------------------------------------

	//---------------------------------------------------------------------------- RPi
	// We�ll divide paramBuffer into several segments:
	//
	// 0-1							Unused
	// 2-5		(+8   / +0   asm)	values that should be placed in R0 - R3
	// 6-67		(+24  / +16  asm)	values that should be placed on the stack
	// 68		(+272 / +264 asm)	number of values stored in r registers (R0 - R3)
	// 69		(+276 / +268 asm)	number of args stored on the stack
	// 70-85	(+280 / +272 asm)	values that should be placed in VFP registers (16)
	// 86-87	(+344 / +336 asm)	sp original value - sp final value - for debugging
	// 88-103	(+352 / +344 asm)	Check area for free-used VFP registers
	//
	// Total number of elements: 104
	//
	// When passing the paramBuffer to the asm routines via the args pointer we are
	// offsetting the start of the array to being at element # 2. That�s why in asm
	// all addresses must have an offset of -2 words (-8 bytes).
	//---------------------------------------------------------------------------- RPi

	asDWORD paramBuffer[PARAM_BUFFER_SIZE];
	memset(paramBuffer, 0, sizeof(asDWORD) * PARAM_BUFFER_SIZE);

	if( sysFunc->hostReturnInMemory )
	{
		// TODO: runtime optimize: This check should be done in PrepareSystemFunction
		if ( !( descr->returnType.GetTypeInfo()->flags & COMPLEX_RETURN_MASK )		&&
			  ( descr->returnType.GetTypeInfo()->flags & asOBJ_APP_CLASS_ALLFLOATS )	&&
			    descr->returnType.GetSizeInMemoryBytes() <= 8 )
			callConv--;

		// The return is made in memory
		callConv++;
	}

	bool isThisCallMethod = callConv >= ICC_THISCALL_OBJLAST;

	// Linux needs to align 64bit types on even registers, but this isn't done on iOS or Windows Phone
	// TODO: optimize runtime: There should be a check for this in PrepareSystemFunction() so this
	//                         doesn't have to be done for functions that don't have any 64bit types
	{
		// mask is used as a toggler to skip uneven registers.
		int mask = 1;

		if( isThisCallMethod )
		{
			mask = 0;
		}
		else
		{
			// Check for object pointer as first argument
			switch( callConv )
			{
				case ICC_THISCALL:
				case ICC_CDECL_OBJFIRST:
				case ICC_VIRTUAL_THISCALL:
				case ICC_THISCALL_RETURNINMEM:
				case ICC_CDECL_OBJFIRST_RETURNINMEM:
				case ICC_VIRTUAL_THISCALL_RETURNINMEM:
					mask = 0;
					break;
				default:
					break;
			}
		}
		// Check for hidden address in case of return by value
		if( sysFunc->hostReturnInMemory )
			mask = !mask;

		paramSize = 0;
		int spos = 0;
		int dpos = 2;

		if( isThisCallMethod && (callConv >= ICC_THISCALL_OBJFIRST &&
			callConv <= ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM) )
		{
			// Add the object pointer as the first parameter
			paramBuffer[dpos++] = (asDWORD)secondObject;
			paramSize++;
		}

		for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
		{
			// TODO: runtime optimize: Declare a reference to descr->parameterTypes[n] so the array doesn't have to be access all the time
			if( descr->parameterTypes[n].IsObject() && !descr->parameterTypes[n].IsObjectHandle() && !descr->parameterTypes[n].IsReference() &&
				!(descr->parameterTypes[n].GetTypeInfo()->flags & asOBJ_APP_ARRAY) )
			{
#ifdef COMPLEX_OBJS_PASSED_BY_REF
				if( descr->parameterTypes[n].GetTypeInfo()->flags & COMPLEX_MASK )
				{
					paramBuffer[dpos++] = args[spos++];
					paramSize++;
				}
				else
#endif
				{
					if( (descr->parameterTypes[n].GetTypeInfo()->flags & asOBJ_APP_CLASS_ALIGN8) )
					{
						if ( (dpos & 1) == mask )
						{
							// 64 bit value align
							dpos++;
							paramSize++;
						}

						if ( (stackPos & 1) == mask )
						{
							// 64 bit value align
							stackPos++;
							stackSize++;
						}
					}

					// Copy the object's memory to the buffer
					if (descr->parameterTypes[n].GetTypeInfo()->flags & asOBJ_APP_CLASS_ALLFLOATS)
					{
						int target = (freeFloatSlot > freeDoubleSlot) ? freeFloatSlot : freeDoubleSlot;

						if ( descr->parameterTypes[n].GetSizeInMemoryDWords() <= ( (VFP_OFFSET + 16) - target) )
						{
							memcpy(&paramBuffer[target], *(void**)(args+spos), descr->parameterTypes[n].GetSizeInMemoryBytes());
							memset(&paramBuffer[target + 18], (asDWORD)1, descr->parameterTypes[n].GetSizeInMemoryDWords());
							target += descr->parameterTypes[n].GetSizeInMemoryDWords();
							freeFloatSlot = freeDoubleSlot = target;
						}
						else
						{
							memcpy(&paramBuffer[stackPos], *(void**)(args+spos), descr->parameterTypes[n].GetSizeInMemoryBytes());
							stackPos += descr->parameterTypes[n].GetSizeInMemoryDWords();
							stackSize += descr->parameterTypes[n].GetSizeOnStackDWords();
						}
					}
					else
					{
						memcpy(&paramBuffer[dpos], *(void**)(args+spos), descr->parameterTypes[n].GetSizeInMemoryBytes());
						dpos += descr->parameterTypes[n].GetSizeInMemoryDWords();
						paramSize += descr->parameterTypes[n].GetSizeInMemoryDWords();
					}

					// Delete the original memory
					engine->CallFree(*(char**)(args+spos));
					spos++;
				}

				continue;
			}
			else if( descr->parameterTypes[n].IsFloatType() && !descr->parameterTypes[n].IsReference() )
			{
				// Are there any "s" registers available?
				if ( freeFloatSlot < (VFP_OFFSET + 16) )
				{
					if (freeFloatSlot == freeDoubleSlot)
						freeDoubleSlot += 2;

					paramBuffer[freeFloatSlot + 18] = (asDWORD)1;
					paramBuffer[freeFloatSlot++] = args[spos++];

					while(freeFloatSlot < (VFP_OFFSET + 16) && paramBuffer[freeFloatSlot + 18] != 0)
						freeFloatSlot++;
				}
				// If not, then store the float arg in the stack area
				else
				{
					paramBuffer[stackPos++] = args[spos++];
					stackSize++;
				}

				continue;
			}
			else if( descr->parameterTypes[n].IsDoubleType() && !descr->parameterTypes[n].IsReference() )
			{
				// Are there any "d" registers available?
				if ( freeDoubleSlot < (VFP_OFFSET + 15) )
				{
					if (freeFloatSlot == freeDoubleSlot)
						freeFloatSlot += 2;

					// Copy two dwords for the double
					paramBuffer[freeDoubleSlot + 18] = (asDWORD)1;
					paramBuffer[freeDoubleSlot + 19] = (asDWORD)1;
					paramBuffer[freeDoubleSlot++] = args[spos++];
					paramBuffer[freeDoubleSlot++] = args[spos++];

					while(freeDoubleSlot < (VFP_OFFSET + 15) && paramBuffer[freeDoubleSlot + 18] != 0)
						freeDoubleSlot += 2;
				}
				// If not, then store the double arg in the stack area
				else
				{
					if ( (stackPos & 1) == mask )
					{
						// 64 bit value align
						stackPos++;
						stackSize++;
					}

					paramBuffer[stackPos++] = args[spos++];
					paramBuffer[stackPos++] = args[spos++];
					stackSize += 2;
				}

				continue;
			}
			else
			{
				// Copy the value directly to "r" registers or the stack, checking for alignment
				if (paramSize < 4)
				{
					// Should an alignment be performed?
					if( (dpos & 1) == mask && descr->parameterTypes[n].GetSizeOnStackDWords() == 2 &&
						!descr->parameterTypes[n].IsObjectHandle() && !descr->parameterTypes[n].IsReference() &&
						!descr->parameterTypes[n].IsAnyType() )
					{
						// 64 bit value align
						dpos++;
						paramSize++;
					}

					paramBuffer[dpos++] = args[spos++];
					paramSize += descr->parameterTypes[n].GetSizeOnStackDWords();
				}
				else
				{
					// Should an alignment be performed?
					if( (stackPos & 1) == mask && descr->parameterTypes[n].GetSizeOnStackDWords() == 2 &&
						!descr->parameterTypes[n].IsObjectHandle() && !descr->parameterTypes[n].IsReference() &&
						!descr->parameterTypes[n].IsAnyType() )
					{
						// 64 bit value align
						stackPos++;
						stackSize++;
					}

					paramBuffer[stackPos++] = args[spos++];
					stackSize += descr->parameterTypes[n].GetSizeOnStackDWords();
				}

				if( descr->parameterTypes[n].GetSizeOnStackDWords() > 1 )
				{
					if (paramSize < 5)
						paramBuffer[dpos++] = args[spos++];
					else
						paramBuffer[stackPos++] = args[spos++];
				}
			}// else...
		}// Loop

		if( isThisCallMethod && (callConv >= ICC_THISCALL_OBJLAST &&
			callConv <= ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM) )
		{
			if (paramSize < 4)
			{
				paramBuffer[dpos++] = (asDWORD)secondObject;
				paramSize++;
			}
			else
			{
				paramBuffer[stackPos++] = (asDWORD)secondObject;
				stackSize++;
			}
		}

		// Keep a free location at the beginning
		args = &paramBuffer[2];
	}

	paramBuffer[69] = static_cast<asDWORD>(stackSize<<2);

	switch( callConv )
	{
	case ICC_CDECL_RETURNINMEM:     // fall through
	case ICC_STDCALL_RETURNINMEM:
		retQW = armFuncR0(args, paramSize<<2, func, (asDWORD)retPointer);
		break;
	case ICC_CDECL:     // fall through
	case ICC_STDCALL:
		retQW = armFunc(args, paramSize<<2, func);
		break;
	case ICC_THISCALL:  // fall through
	case ICC_CDECL_OBJFIRST:
	case ICC_THISCALL_OBJFIRST:
	case ICC_THISCALL_OBJLAST:
		retQW = armFuncR0(args, paramSize<<2, func, (asDWORD)obj);
		break;
	case ICC_THISCALL_RETURNINMEM:
	case ICC_THISCALL_OBJFIRST_RETURNINMEM:
	case ICC_THISCALL_OBJLAST_RETURNINMEM:
		// On GNUC the address where the return value will be placed should be put in R0
		retQW = armFuncR0R1(args, paramSize<<2, func, (asDWORD)retPointer, (asDWORD)obj);
		break;
	case ICC_CDECL_OBJFIRST_RETURNINMEM:
		retQW = armFuncR0R1(args, paramSize<<2, func, (asDWORD)retPointer, (asDWORD)obj);
		break;
	case ICC_VIRTUAL_THISCALL:
	case ICC_VIRTUAL_THISCALL_OBJFIRST:
	case ICC_VIRTUAL_THISCALL_OBJLAST:
		// Get virtual function table from the object pointer
		vftable = *(asFUNCTION_t**)obj;
		retQW = armFuncR0(args, paramSize<<2, vftable[FuncPtrToUInt(func)>>2], (asDWORD)obj);
		break;
	case ICC_VIRTUAL_THISCALL_RETURNINMEM:
	case ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM:
	case ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM:
		// Get virtual function table from the object pointer
		vftable = *(asFUNCTION_t**)obj;
		// On GNUC the address where the return value will be placed should be put in R0
		retQW = armFuncR0R1(args, (paramSize+1)<<2, vftable[FuncPtrToUInt(func)>>2], (asDWORD)retPointer, (asDWORD)obj);
		break;
	case ICC_CDECL_OBJLAST:
		retQW = armFuncObjLast(args, paramSize<<2, func, (asDWORD)obj);
		break;
	case ICC_CDECL_OBJLAST_RETURNINMEM:
		retQW = armFuncR0ObjLast(args, paramSize<<2, func, (asDWORD)retPointer, (asDWORD)obj);
		break;
	default:
		context->SetInternalException(TXT_INVALID_CALLING_CONVENTION);
	}

	// On Linux with arm the float and double values are returns in the
	// floating point registers, s0 and s1. Objects that contain only
	// float types and are not considered complex are also returned in the
	// floating point registers.
	if( sysFunc->hostReturnFloat )
	{
		retQW = paramBuffer[VFP_OFFSET];

		if ( sysFunc->hostReturnSize > 1 )
			retQW = *( (asQWORD*)&paramBuffer[VFP_OFFSET] );
	}
	else if ( descr->returnType.IsObject() )
	{
		// TODO: runtime optimize: This should be identified with a flag determined in PrepareSystemFunction
		if ( !descr->returnType.IsObjectHandle()									&&
			 !descr->returnType.IsReference()										&&
			 !(descr->returnType.GetTypeInfo()->flags & COMPLEX_RETURN_MASK)		&&
			 (descr->returnType.GetTypeInfo()->flags & asOBJ_APP_CLASS_ALLFLOATS) )
			memcpy( retPointer, &paramBuffer[VFP_OFFSET], descr->returnType.GetSizeInMemoryBytes() );
	}

	return retQW;
}

END_AS_NAMESPACE

#endif // AS_LINUX

#endif // AS_ARM
#endif // AS_MAX_PORTABILITY


code:
/*
   AngelCode Scripting Library
   Copyright (c) 2020-2024 Andreas Jonsson

   This software is provided 'as-is', without any express or implied
   warranty. In no event will the authors be held liable for any
   damages arising from the use of this software.

   Permission is granted to anyone to use this software for any
   purpose, including commercial applications, and to alter it and
   redistribute it freely, subject to the following restrictions:

   1. The origin of this software must not be misrepresented; you
      must not claim that you wrote the original software. If you use
      this software in a product, an acknowledgment in the product
      documentation would be appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and
      must not be misrepresented as being the original software.

   3. This notice may not be removed or altered from any source
      distribution.

   The original version of this library can be located at:
   http://www.angelcode.com/angelscript/

   Andreas Jonsson
   andreas@angelcode.com
*/

//
// as_callfunc_arm64.cpp
//
// These functions handle the actual calling of system functions on the arm64 platform
//
// Written by Max Waine in July 2020, based on as_callfunc_arm.cpp
//
// Adapted for Apple M1/M2 by Sam Tupy in Jan 2024
//
// ref for Apple ABI: https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms
//

#include "as_config.h"

#ifndef AS_MAX_PORTABILITY
#ifdef AS_ARM64

#include "as_callfunc.h"
#include "as_scriptengine.h"
#include "as_texts.h"
#include "as_tokendef.h"
#include "as_context.h"

// ARM64 targets use has no software floating-point ABI, it's all hardware (or totally disabled)

#define HFA_RET_REGISTERS   4 // s0-s3/d0-d3
#define GP_ARG_REGISTERS    8 // x0-x7
#define FLOAT_ARG_REGISTERS 8 // v0-v7

BEGIN_AS_NAMESPACE

// x0-7:   Argument registers (pass params or return results. OK as volatile local variables)
// x8:     Indirect result register (e.g. address of large returned struct)
// x9-15:  Volatile local variable registers
// x16-17: Intra-procedure-call temporary registers
// x18:    Platform register (reserved for use of platform ABIs)
// x19-29: Non-volatile variable registers (must be saved and restored if modified)
// x29:    Frame pointer register
// x30:    Link register (where to return to)

extern "C" void GetHFAReturnDouble(asQWORD *out1, asQWORD *out2, asQWORD returnSize);
extern "C" void GetHFAReturnFloat(asQWORD *out1, asQWORD *out2, asQWORD returnSize);

extern "C" asQWORD CallARM64RetInMemory(
	const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
	const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
	const asQWORD *stackArgs,    asQWORD numStackArgs,
	void *retPointer,            asFUNCTION_t func
);
extern "C" double CallARM64Double(
	const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
	const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
	const asQWORD *stackArgs,    asQWORD numStackArgs,
	asFUNCTION_t func
);
extern "C" float CallARM64Float(
	const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
	const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
	const asQWORD *stackArgs,    asQWORD numStackArgs,
	asFUNCTION_t func
);
extern "C" asQWORD CallARM64(
	const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
	const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
	const asQWORD *stackArgs,    asQWORD numStackArgs,
	asFUNCTION_t func
);
extern "C" asQWORD CallARM64Ret128(
	const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
	const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
	const asQWORD *stackArgs,    asQWORD numStackArgs,
	asQWORD *higherQWORD,        asFUNCTION_t func
);

//
// If it's possible to fit in registers,
// there may not be enough float register space even if true is returned
//
static inline bool IsRegisterHFA(const asCDataType &type)
{
	const asCTypeInfo *const typeInfo = type.GetTypeInfo();

	if( typeInfo == 0 ||
		(typeInfo->flags & asOBJ_APP_CLASS_ALLFLOATS) == 0 ||
		type.IsObjectHandle() || type.IsReference() )
		return false;

	const bool doubles = (typeInfo->flags & asOBJ_APP_CLASS_ALIGN8) != 0;
	const int maxAllowedSize = doubles ? sizeof(double) * HFA_RET_REGISTERS : sizeof(float) * HFA_RET_REGISTERS;

	return type.GetSizeInMemoryBytes() <= maxAllowedSize;
}

//
// If it's possible to fit it in registers,
// if true is returned there is enough space to fit
//
static inline bool IsRegisterHFAParameter(const asCDataType &type, const asQWORD numFloatRegArgs)
{
	if( !IsRegisterHFA(type) )
		return false;

	const bool doubles = (type.GetTypeInfo()->flags & asOBJ_APP_CLASS_ALIGN8) != 0;
	const int registersUsed = type.GetSizeInMemoryDWords() / (doubles ? sizeof(double) : sizeof(float));

	return numFloatRegArgs + registersUsed <= FLOAT_ARG_REGISTERS;
}

#if defined(AS_IPHONE) || defined(AS_MAC)
static inline void PadAppleStack(asQWORD* const argsArray, asQWORD& numArgs, asQWORD& stackDispositionBytes, asUINT argSize)
{
	if(stackDispositionBytes == 0) return;
	asUINT padBytes = argSize - (stackDispositionBytes % argSize);
	if(padBytes > 0 && padBytes != argSize)
	{
		memset( ((asBYTE*)&argsArray[numArgs]) + stackDispositionBytes, 0, padBytes);
		stackDispositionBytes += padBytes;
	}
	numArgs += stackDispositionBytes / sizeof(asQWORD);
	if(stackDispositionBytes >= sizeof(asQWORD))
		stackDispositionBytes -= sizeof(asQWORD) * (stackDispositionBytes / sizeof(asQWORD) );
}
#endif

asQWORD CallSystemFunctionNative(asCContext *context, asCScriptFunction *descr, void *obj, asDWORD *args, void *retPointer, asQWORD &retQW2, void *secondObject)
{
	asCScriptEngine *engine = context->m_engine;
	const asSSystemFunctionInterface *const sysFunc = descr->sysFuncIntf;
	const asCDataType &retType = descr->returnType;
	const asCTypeInfo *const retTypeInfo = retType.GetTypeInfo();
	asFUNCTION_t func = sysFunc->func;
	int callConv = sysFunc->callConv;
	asQWORD       retQW     = 0;

	asQWORD       gpRegArgs[GP_ARG_REGISTERS];
	asQWORD       floatRegArgs[FLOAT_ARG_REGISTERS];
	asQWORD       stackArgs[64]; // It's how many x64 users can have
	asQWORD       numGPRegArgs    = 0;
	asQWORD       numFloatRegArgs = 0;
	asQWORD       numStackArgs    = 0;
#if defined(AS_IPHONE) || defined(AS_MAC)
	asQWORD stackDispositionBytes = 0; // Apple silikin aligns arguments on the stack by the size of their type instead of by 8 bytes like standard arm.
#endif
	asFUNCTION_t *vftable;

	// Optimization to avoid check 12 values (all ICC_ that contains THISCALL)
	if( (callConv >= ICC_THISCALL && callConv <= ICC_VIRTUAL_THISCALL_RETURNINMEM) ||
		(callConv >= ICC_THISCALL_OBJLAST && callConv <= ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM) )
	{
		// Add the object pointer as the first parameter
		gpRegArgs[numGPRegArgs++] = (asQWORD)obj;
	}

	if( callConv == ICC_CDECL_OBJFIRST || callConv == ICC_CDECL_OBJFIRST_RETURNINMEM )
	{
		// Add the object pointer as the first parameter
		gpRegArgs[numGPRegArgs++] = (asQWORD)obj;
	}
	else if( callConv == ICC_THISCALL_OBJFIRST || callConv == ICC_THISCALL_OBJFIRST_RETURNINMEM ||
		callConv == ICC_VIRTUAL_THISCALL_OBJFIRST || callConv == ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM )
	{
		// Add the object pointer as the first parameter
		gpRegArgs[numGPRegArgs++] = (asQWORD)secondObject;
	}

	if( callConv == ICC_VIRTUAL_THISCALL || callConv == ICC_VIRTUAL_THISCALL_RETURNINMEM || callConv == ICC_VIRTUAL_THISCALL_OBJFIRST ||
	callConv == ICC_VIRTUAL_THISCALL_OBJFIRST_RETURNINMEM || callConv == ICC_VIRTUAL_THISCALL_OBJLAST || callConv == ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM )
	{
		// Get virtual function table from the object pointer
		vftable = *(asFUNCTION_t**)obj;
		func = vftable[FuncPtrToUInt(func)/sizeof(void*)];
	}

	asUINT argsPos = 0;
	for( asUINT n = 0; n < descr->parameterTypes.GetLength(); n++ )
	{
		const asCDataType &parmType = descr->parameterTypes[n];
		const asCTypeInfo *const parmTypeInfo = parmType.GetTypeInfo();

		if( parmType.IsObject() && !parmType.IsObjectHandle() && !parmType.IsReference() )
		{
			const asUINT parmDWords = parmType.GetSizeInMemoryDWords();
			const asUINT parmQWords = (parmDWords >> 1) + (parmDWords & 1);

			const bool passedAsPointer = parmQWords <= 2;
			const bool fitsInRegisters = passedAsPointer ? (numGPRegArgs < GP_ARG_REGISTERS) : (numGPRegArgs + parmQWords <= GP_ARG_REGISTERS);
			asQWORD *const argsArray = fitsInRegisters ? gpRegArgs : stackArgs;
			asQWORD &numArgs = fitsInRegisters ? numGPRegArgs : numStackArgs;

			if( (parmTypeInfo->flags & COMPLEX_MASK) )
			{
#if defined(AS_IPHONE) || defined(AS_MAC)
				if(!fitsInRegisters) PadAppleStack(argsArray, numArgs, stackDispositionBytes, sizeof(asQWORD));
#endif
				argsArray[numArgs++] = *(asQWORD*)&args[argsPos];
				argsPos += AS_PTR_SIZE;
			}
			else if( IsRegisterHFAParameter(parmType, numFloatRegArgs) )
			{
				if( (parmTypeInfo->flags & asOBJ_APP_CLASS_ALIGN8) != 0 )
				{
					const asQWORD *const contents = *(asQWORD**)&args[argsPos];
					for( asUINT i = 0; i < parmQWords; i++ )
						floatRegArgs[numFloatRegArgs++] = *(asQWORD*)&contents[i];
				}
				else
				{
					const asDWORD *const contents = *(asDWORD**)&args[argsPos];
					for( asUINT i = 0; i < parmDWords; i++ )
						floatRegArgs[numFloatRegArgs++] = *(asDWORD*)&contents[i];
				}
				engine->CallFree(*(char**)(args+argsPos));
				argsPos += AS_PTR_SIZE;
			}
			else
			{
				// Copy the object's memory to the buffer
				asUINT parmBytes = parmType.GetSizeInMemoryBytes();
#if defined(AS_IPHONE) || defined(AS_MAC)
				if(!fitsInRegisters)
				{
					PadAppleStack(argsArray, numArgs, stackDispositionBytes, parmBytes);
					memcpy( ((asBYTE*)&argsArray[numArgs]) + stackDispositionBytes, *(void**)(args+argsPos), parmBytes);
					stackDispositionBytes += parmBytes;
					// numArgs will be fixed on next call to PadAppleStack.
				}
				else
#endif
				{
					memcpy(&argsArray[numArgs], *(void**)(args+argsPos), parmBytes);
					numArgs += parmQWords;
				}

				// Delete the original memory
				engine->CallFree(*(char**)(args+argsPos));
				argsPos += AS_PTR_SIZE;
			}
		}
		else if( parmType.IsFloatType() && !parmType.IsReference() )
		{
			if( numFloatRegArgs >= FLOAT_ARG_REGISTERS )
#if defined(AS_IPHONE) || defined(AS_MAC)
			{
				PadAppleStack(stackArgs, numStackArgs, stackDispositionBytes, sizeof(float));
				memcpy( ((asBYTE*)&stackArgs[numStackArgs]) + stackDispositionBytes, &args[argsPos], sizeof(float));
				stackDispositionBytes += sizeof(float);
			}
#else
				stackArgs[numStackArgs++] = args[argsPos];
#endif
			else
				floatRegArgs[numFloatRegArgs++] = args[argsPos];
			argsPos++;
		}
		else if( parmType.IsDoubleType() && !parmType.IsReference() )
		{
			if( numFloatRegArgs >= FLOAT_ARG_REGISTERS )
#if defined(AS_IPHONE) || defined(AS_MAC)
			{
				PadAppleStack(stackArgs, numStackArgs, stackDispositionBytes, sizeof(asQWORD));
				memcpy( ((asBYTE*)&stackArgs[numStackArgs]) + stackDispositionBytes, (asQWORD*)&args[argsPos], sizeof(asQWORD));
				stackDispositionBytes += sizeof(asQWORD);
			}
#else
				stackArgs[numStackArgs++] = *(asQWORD*)&args[argsPos];
#endif
			else
				floatRegArgs[numFloatRegArgs++] = *(asQWORD*)&args[argsPos];
			argsPos += 2;
		}
		else if (parmType.GetTokenType() == ttQuestion)
		{
			// Copy the reference and the type id as separate arguments
			//
			// First the reference
			bool fitsInRegisters = numGPRegArgs + 1 <= GP_ARG_REGISTERS;
			asQWORD* argsArray = fitsInRegisters ? gpRegArgs : stackArgs;
			asQWORD* numArgs = fitsInRegisters ? &numGPRegArgs : &numStackArgs;
#if defined(AS_IPHONE) || defined(AS_MAC)
			if (!fitsInRegisters)
			{
				asUINT parmBytes = AS_PTR_SIZE * 4;
				PadAppleStack(argsArray, *numArgs, stackDispositionBytes, parmBytes);
				memcpy(((asBYTE*)&argsArray[*numArgs]) + stackDispositionBytes, (void*)(args + argsPos), parmBytes);
				stackDispositionBytes += parmBytes;
			}
			else
#endif
			{
				memcpy(&argsArray[*numArgs], (void*)(args + argsPos), AS_PTR_SIZE * 4);
				(*numArgs) += 1;
			}
			argsPos += AS_PTR_SIZE;

			// Then the type id
			fitsInRegisters = numGPRegArgs + 1 <= GP_ARG_REGISTERS;
			argsArray = fitsInRegisters ? gpRegArgs : stackArgs;
			numArgs = fitsInRegisters ? &numGPRegArgs : &numStackArgs;
#if defined(AS_IPHONE) || defined(AS_MAC)
			if (!fitsInRegisters)
			{
				asUINT parmBytes = 4;
				PadAppleStack(argsArray, *numArgs, stackDispositionBytes, parmBytes);
				memcpy(((asBYTE*)&argsArray[*numArgs]) + stackDispositionBytes, (void*)(args + argsPos), parmBytes);
				stackDispositionBytes += parmBytes;
			}
			else
#endif
			{
				memcpy(&argsArray[*numArgs], (void*)(args + argsPos), 4);
				(*numArgs) += 1;
			}
			argsPos += 1;
		}
		else
		{
			// Copy the value directly
			const asUINT parmDWords = parmType.GetSizeOnStackDWords();
			const asUINT parmQWords = (parmDWords >> 1) + (parmDWords & 1);

			const bool fitsInRegisters = numGPRegArgs + parmQWords <= GP_ARG_REGISTERS;
			asQWORD *const argsArray = fitsInRegisters ? gpRegArgs : stackArgs;
			asQWORD &numArgs = fitsInRegisters ? numGPRegArgs : numStackArgs;
#if defined(AS_IPHONE) || defined(AS_MAC)
			if(!fitsInRegisters)
			{
				asUINT parmBytes = parmType.GetSizeInMemoryBytes();
				PadAppleStack(argsArray, numArgs, stackDispositionBytes, parmBytes);
				memcpy( ((asBYTE*)&argsArray[numArgs]) + stackDispositionBytes, (void*)(args+argsPos), parmBytes);
				stackDispositionBytes += parmBytes;
			}
			else
#endif
			{
				memcpy(&argsArray[numArgs], (void*)(args+argsPos), parmDWords * 4);
				numArgs += parmQWords;
			}

			argsPos += parmDWords;
		}
	}
#if defined(AS_IPHONE) || defined(AS_MAC)
	PadAppleStack(stackArgs, numStackArgs, stackDispositionBytes, sizeof(asQWORD));
#endif
	if( callConv == ICC_CDECL_OBJLAST || callConv == ICC_CDECL_OBJLAST_RETURNINMEM )
	{
		// Add the object pointer as the last parameter
		if( numGPRegArgs < GP_ARG_REGISTERS )
			gpRegArgs[numGPRegArgs++] = (asQWORD)obj;
		else
			stackArgs[numStackArgs++] = (asQWORD)obj;
	}
	else if( callConv == ICC_THISCALL_OBJLAST || callConv == ICC_THISCALL_OBJLAST_RETURNINMEM ||
		callConv == ICC_VIRTUAL_THISCALL_OBJLAST || callConv == ICC_VIRTUAL_THISCALL_OBJLAST_RETURNINMEM )
	{
		// Add the object pointer as the last parameter
		if( numGPRegArgs < GP_ARG_REGISTERS )
			gpRegArgs[numGPRegArgs++] = (asQWORD)secondObject;
		else
			stackArgs[numStackArgs++] = (asQWORD)secondObject;
	}

	if( IsRegisterHFA(retType) && !(retTypeInfo->flags & COMPLEX_MASK) )
	{
		// This is to deal with HFAs (Homogeneous Floating-point Aggregates):
		// ARM64 will place all-float composite types (of equal precision)
		// with <= 4 members in the float return registers

		const int structSize = retType.GetSizeInMemoryBytes();

		CallARM64(gpRegArgs, numGPRegArgs, floatRegArgs, numFloatRegArgs, stackArgs, numStackArgs, func);
		if( (retTypeInfo->flags & asOBJ_APP_CLASS_ALIGN8) != 0 )
		{
			if( structSize <= sizeof(double) * 2 )
				GetHFAReturnDouble(&retQW, &retQW2, structSize);
			else
				GetHFAReturnDouble((asQWORD*)retPointer, ((asQWORD*)retPointer) + 1, structSize);
		}
		else
			GetHFAReturnFloat(&retQW, &retQW2, structSize);
	}
	else if( sysFunc->hostReturnFloat )
	{
		if( sysFunc->hostReturnSize == 1 )
			*(float*)&retQW = CallARM64Float(gpRegArgs, numGPRegArgs, floatRegArgs, numFloatRegArgs, stackArgs, numStackArgs, func);
		else
			*(double*)&retQW = CallARM64Double(gpRegArgs, numGPRegArgs, floatRegArgs, numFloatRegArgs, stackArgs, numStackArgs, func);
	}
	else if( sysFunc->hostReturnInMemory )
		retQW = CallARM64RetInMemory(gpRegArgs, numGPRegArgs, floatRegArgs, numFloatRegArgs, stackArgs, numStackArgs, retPointer, func);
	else
	{
		if( retType.GetSizeInMemoryBytes() > sizeof(asQWORD) )
			retQW = CallARM64Ret128(gpRegArgs, numGPRegArgs, floatRegArgs, numFloatRegArgs, stackArgs, numStackArgs, &retQW2, func);
		else
			retQW = CallARM64(gpRegArgs, numGPRegArgs, floatRegArgs, numFloatRegArgs, stackArgs, numStackArgs, func);
	}

	return retQW;
}

END_AS_NAMESPACE

#endif // AS_ARM64
#endif // AS_MAX_PORTABILITY


code:
//
//  AngelCode Scripting Library
//  Copyright (c) 2020-2024 Andreas Jonsson
//
//  This software is provided 'as-is', without any express or implied
//  warranty. In no event will the authors be held liable for any
//  damages arising from the use of this software.
//
//  Permission is granted to anyone to use this software for any
//  purpose, including commercial applications, and to alter it and
//  redistribute it freely, subject to the following restrictions:
//
//  1. The origin of this software must not be misrepresented// you
//     must not claim that you wrote the original software. If you use
//     this software in a product, an acknowledgment in the product
//     documentation would be appreciated but is not required.
//
//  2. Altered source versions must be plainly marked as such, and
//     must not be misrepresented as being the original software.
//
//  3. This notice may not be removed or altered from any source
//     distribution.
//
//  The original version of this library can be located at:
//  http://www.angelcode.com/angelscript/
//
//  Andreas Jonsson
//  andreas@angelcode.com
//

// Assembly routines for the ARM64/AArch64 call convention used for Linux
// Written by Max Waine in July 2020, based on as_callfunc_arm_msvc.asm,
// with assistance & guidance provided by Sir Kane

// Compile with GCC/GAS

#if !defined(AS_MAX_PORTABILITY)

#if defined(__aarch64__)

.arch armv8-a
.text

.global GetHFAReturnDouble
.global GetHFAReturnFloat
.global CallARM64Ret128
.global CallARM64RetInMemory
.global CallARM64Double
.global CallARM64Float
.global CallARM64

#if !defined(__MACH__)
.type GetHFAReturnDouble, %function
.type GetHFAReturnFloat, %function
.type CallARM64Ret128, %function
.type CallARM64RetInMemory, %function
.type CallARM64Double, %function
.type CallARM64Float, %function
.type CallARM64, %function
#endif /* __MACH__ */

.align  2
GetHFAReturnDouble:
    adr     x9, populateDoubles
    sub     x9, x9, x2, lsr 1 // x9 -= returnSize >> 1; (/2 because double is 2x instruction size)
    br      x9

    str     d3, [x0, #0x18]
    str     d2, [x0, #0x10]
    str     d1, [x1]
    str     d0, [x0]
populateDoubles:

    ret

.align  2
GetHFAReturnFloat:
    adr     x9, populateFloats
    sub     x9, x9, x2 // x9 -= returnSize; (already 4 bytes per return)
    br      x9

    str     s3, [x1, #0x4]
    str     s2, [x1]
    str     s1, [x0, #0x4]
    str     s0, [x0]
populateFloats:

    ret

//[returnType] CallARM64[type](
//    const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
//    const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
//    const asQWORD *stackArgs,    asQWORD numStackArgs,
//    asFUNCTION_t func
//)
.align  2
CallARM64Double:
CallARM64Float:
CallARM64:
    .cfi_startproc
    stp     fp, lr, [sp,#-0x20]!
    str     x20, [sp,#0x10]
    .cfi_def_cfa_offset 0x20
    .cfi_offset 20,  0x10
    .cfi_offset fp, -0x20
    .cfi_offset lr, -0x18
    mov     fp, sp

    mov     x20, #0

    cbz     x5, stackArgsLoopEnd

    // Align count to 2, then multiply by 8, resulting in a size aligned to 16
    add x20, x5,  #1
    lsl x20, x20, #3
    and x20, x20, #-0x10
    // Multiply count by 8
    lsl x10, x5, #3
    sub sp, sp, x20
stackArgsLoopStart:
    ldp     x9,x11, [x4],#16
    stp     x9,x11, [sp],#16
    subs    x10, x10, #16
    bgt     stackArgsLoopStart
stackArgsLoopEnd:

    // Calculate amount to jump forward, avoiding pointless instructions
    adr     x9, populateFloatRegisterArgsEnd
    sub     x9, x9, x3, lsl 2 // x9 -= numFloatRegArgs * 4
    br      x9

    ldr     d7, [x2, #0x38]
    ldr     d6, [x2, #0x30]
    ldr     d5, [x2, #0x28]
    ldr     d4, [x2, #0x20]
    ldr     d3, [x2, #0x18]
    ldr     d2, [x2, #0x10]
    ldr     d1, [x2, #0x08]
    ldr     d0, [x2]
populateFloatRegisterArgsEnd:

    mov     x15, x6
    // Calculate amount to jump forward, avoiding pointless instructions
    adr     x9, populateGPRegisterArgsEnd
    sub     x9, x9, x1, lsl 2 // x9 -= numGPRegArgs * 4
    br      x9

    ldr     x7, [x0, #0x38]
    ldr     x6, [x0, #0x30]
    ldr     x5, [x0, #0x28]
    ldr     x4, [x0, #0x20]
    ldr     x3, [x0, #0x18]
    ldr     x2, [x0, #0x10]
    ldr     x1, [x0, #0x08]
    ldr     x0, [x0]
populateGPRegisterArgsEnd:

    // Actually call function
    sub     sp, sp, x20
    blr     x15
    add     sp, sp, x20

    ldr     x20, [sp,#0x10]
    ldp     fp, lr, [sp],#0x20

    .cfi_restore lr
	.cfi_restore fp
    .cfi_restore 20
	.cfi_def_cfa_offset 0
    ret
    .cfi_endproc

.align  2
CallARM64Ret128:
    .cfi_startproc
    stp     fp, lr, [sp,#-0x20]!
    str     x20, [sp,#0x10]
    .cfi_def_cfa_offset 0x20
    .cfi_offset 20,  0x10
    .cfi_offset fp, -0x20
    .cfi_offset lr, -0x18
    mov     fp, sp

    mov     x20, x6
    mov     x6, x7
    mov     x7, #0
    bl      CallARM64

    str     x1, [x20]

    ldr     x20, [sp,#0x10]
    ldp     fp, lr, [sp],#0x20

    .cfi_restore lr
	.cfi_restore fp
    .cfi_restore 20
	.cfi_def_cfa_offset 0
    ret
    .cfi_endproc

.align  2
CallARM64RetInMemory:
    .cfi_startproc
    stp     fp, lr, [sp,#-0x10]!
    mov     fp, sp
    .cfi_def_cfa_offset 0x10
    .cfi_offset fp, -0x10
    .cfi_offset lr, -0x08

    mov     x8, x6
    mov     x6, x7
    mov     x7, #0
    bl      CallARM64

    mov     x0, x8

    ldp     fp, lr, [sp],#0x10

    .cfi_restore lr
	.cfi_restore fp
	.cfi_def_cfa_offset 0
    ret
    .cfi_endproc

#endif /* __aarch64__ */

#endif /* !AS_MAX_PORTABILITY */


code:
;
;  AngelCode Scripting Library
;  Copyright (c) 2020-2024 Andreas Jonsson
;
;  This software is provided 'as-is', without any express or implied
;  warranty. In no event will the authors be held liable for any
;  damages arising from the use of this software.
;
;  Permission is granted to anyone to use this software for any
;  purpose, including commercial applications, and to alter it and
;  redistribute it freely, subject to the following restrictions:
;
;  1. The origin of this software must not be misrepresented; you
;     must not claim that you wrote the original software. If you use
;     this software in a product, an acknowledgment in the product
;     documentation would be appreciated but is not required.
;
;  2. Altered source versions must be plainly marked as such, and
;     must not be misrepresented as being the original software.
;
;  3. This notice may not be removed or altered from any source
;     distribution.
;
;  The original version of this library can be located at:
;  http://www.angelcode.com/angelscript/
;
;  Andreas Jonsson
;  andreas@angelcode.com
;

; Assembly routines for the ARM64/AArch64 call convention used for Windows 10 on ARM
; Written by Max Waine in July 2020, based on as_callfunc_arm_msvc.asm

; MSVC currently doesn't support inline assembly for the ARM64 platform,
; and if they're treating it like x64 /won't/ ever support inline assembly,
; so this separate file is needed.

; Compile with Microsoft ARM64 assembler (armasm64)
; http://msdn.microsoft.com/en-us/library/hh873190.aspx

    AREA    |.rdata|, DATA, READONLY
    EXPORT  GetHFAReturnDouble
    EXPORT  GetHFAReturnFloat
    EXPORT  CallARM64Ret128
    EXPORT  CallARM64RetInMemory
    EXPORT  CallARM64Double
    EXPORT  CallARM64Float
    EXPORT  CallARM64

    AREA    |.text|, CODE, ALIGN=2

    ALIGN   4
GetHFAReturnDouble PROC
    adr     x9, |populateDoubles|
    sub     x9, x9, x1, lsr 1 ; x9 -= returnSize >> 1; (/2 because double is 2x instruction size)
    br      x9

    str     d3, [x0, #0x18]
    str     d2, [x0, #0x10]
    str     d1, [x1]
    str     d0, [x0]
|populateDoubles|

    ret
    ENDP ; GetHFAReturnDouble

    ALIGN   4
GetHFAReturnFloat PROC
    adr     x9, |populateFloats|
    sub     x9, x9, x2 ; x9 -= returnSize; (already 4 bytes per return)
    br      x9

    str     s3, [x1, #0x4]
    str     s2, [x1]
    str     s1, [x0, #0x4]
    str     s0, [x0]
|populateFloats|

    ret
    ENDP ; GetHFAReturnFloat

;[returnType] CallARM64[type](
;    const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
;    const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
;    const asQWORD *stackArgs,    asQWORD numStackArgs,
;    asFUNCTION_t func
;)
    ALIGN   4
CallARM64Double PROC
    stp     fp, lr, [sp,#-0x10]!
    bl      CallARM64
    ldp     fp, lr, [sp,#-0x10]!
    ret
    ENDP ; CallARM64Double

    ALIGN   4
CallARM64Float PROC
    stp     fp, lr, [sp,#-0x10]!
    bl      CallARM64
    ldp     fp, lr, [sp,#-0x10]!
    ret
    ENDP ; CallARM64Float

    ALIGN   4
CallARM64 PROC
    stp     fp, lr, [sp,#-0x20]!
    str     x20, [sp,#0x10]

    mov     x20, #0;

    cbz     x5, |stackArgsLoopEnd|

    ; Align count to 2, then multiply by 8, resulting in a size aligned to 16
    add x20, x5,  #1
    lsl x20, x20, #3
    and x20, x20, #-0x10
    ; Multiply count by 8
    lsl x10, x5, #3
    sub sp, sp, x20
|stackArgsLoopStart|
    ldp     x9,x11, [x4],#16
    stp     x9,x11, [sp],#16
    subs    x10, x10, #16
    bgt     |stackArgsLoopStart|
|stackArgsLoopEnd|

    ; Calculate amount to jump forward, avoiding pointless instructions
    adr     x9, |populateFloatRegisterArgsEnd|
    sub     x9, x9, x3, lsl 2 ; x9 -= numFloatRegArgs * 4
    br      x9

    ldr     d7, [x2, #0x38]
    ldr     d6, [x2, #0x30]
    ldr     d5, [x2, #0x28]
    ldr     d4, [x2, #0x20]
    ldr     d3, [x2, #0x18]
    ldr     d2, [x2, #0x10]
    ldr     d1, [x2, #0x08]
    ldr     d0, [x2]
|populateFloatRegisterArgsEnd|

    mov     x15, x6
    ; Calculate amount to jump forward, avoiding pointless instructions
    adr     x9, |populateGPRegisterArgsEnd|
    sub     x9, x9, x1, lsl 2 ; x9 -= numGPRegArgs * 4
    br      x9

    ldr     x7, [x0, #0x38]
    ldr     x6, [x0, #0x30]
    ldr     x5, [x0, #0x28]
    ldr     x4, [x0, #0x20]
    ldr     x3, [x0, #0x18]
    ldr     x2, [x0, #0x10]
    ldr     x1, [x0, #0x08]
    ldr     x0, [x0]
|populateGPRegisterArgsEnd|

    ; Actually call function
    sub     sp, sp, x20
    blr     x15
    add     sp, sp, x20

    ldr     x20, [sp,#0x10]
    ldp     fp, lr, [sp],#0x20

    ret
    ENDP ; CallARM64

    ALIGN   4
CallARM64Ret128 PROC
    stp     fp, lr, [sp,#-0x20]!
    str     x20, [sp,#0x10]
    mov     fp, sp

    mov     x20, x6
    mov     x6, x7
    mov     x7, #0
    bl      CallARM64

    str     x1, [x20]

    ldr     x20, [sp,#0x10]
    ldp     fp, lr, [sp],#0x20

    ret
    ENDP ; CallARM64Ret128

    ALIGN   4
CallARM64RetInMemory PROC
    stp     fp, lr, [sp,#-0x10]!
    mov     fp, sp

    mov     x8, x6
    mov     x6, x7
    mov     x7, #0
    bl      CallARM64

    mov     x0, x8

    ldp     fp, lr, [sp],#0x10

    ret
    ENDP ; CallARM64RetInMemory

    END


code:
//
//  AngelCode Scripting Library
//  Copyright (c) 2020-2024 Andreas Jonsson
//
//  This software is provided 'as-is', without any express or implied
//  warranty. In no event will the authors be held liable for any
//  damages arising from the use of this software.
//
//  Permission is granted to anyone to use this software for any
//  purpose, including commercial applications, and to alter it and
//  redistribute it freely, subject to the following restrictions:
//
//  1. The origin of this software must not be misrepresented// you
//     must not claim that you wrote the original software. If you use
//     this software in a product, an acknowledgment in the product
//     documentation would be appreciated but is not required.
//
//  2. Altered source versions must be plainly marked as such, and
//     must not be misrepresented as being the original software.
//
//  3. This notice may not be removed or altered from any source
//     distribution.
//
//  The original version of this library can be located at:
//  http://www.angelcode.com/angelscript/
//
//  Andreas Jonsson
//  andreas@angelcode.com
//

// Assembly routines for the ARM64/AArch64 call convention used for Linux
// Written by Max Waine in July 2020, based on as_callfunc_arm_msvc.asm,
// with assistance & guidance provided by Sir Kane

// Compile with GCC/GAS

#if !defined(AS_MAX_PORTABILITY)

#if defined(__aarch64__)

.global _GetHFAReturnDouble
.global _GetHFAReturnFloat
.global _CallARM64Ret128
.global _CallARM64RetInMemory
.global _CallARM64Double
.global _CallARM64Float
.global _CallARM64

.p2align 2
_GetHFAReturnDouble:
    adr     x9, LBL_populateDoubles
    sub     x9, x9, x2, lsr 1 // x9 -= returnSize >> 1; (/2 because double is 2x instruction size)
    br      x9

    str     d3, [x0, #0x18]
    str     d2, [x0, #0x10]
    str     d1, [x1]
    str     d0, [x0]
LBL_populateDoubles:

    ret

.p2align 2
_GetHFAReturnFloat:
    adr     x9, LBL_populateFloats
    sub     x9, x9, x2 // x9 -= returnSize; (already 4 bytes per return)
    br      x9

    str     s3, [x1, #0x4]
    str     s2, [x1]
    str     s1, [x0, #0x4]
    str     s0, [x0]
LBL_populateFloats:
    ret

//[returnType] _CallARM64[type](
//    const asQWORD *gpRegArgs,    asQWORD numGPRegArgs,
//    const asQWORD *floatRegArgs, asQWORD numFloatRegArgs,
//    const asQWORD *stackArgs,    asQWORD numStackArgs,
//    asFUNCTION_t func
//)
.p2align 2
_CallARM64Double:
_CallARM64Float:
_CallARM64:
    .cfi_startproc
    sub sp, sp, #0x20
    .cfi_def_cfa_offset 0x20
    stp fp, lr, [sp,#0x10]
    str x20, [sp,#0x08]
    add fp, sp, #0x10
    .cfi_def_cfa x29, 0x10
    .cfi_offset x30, -0x08
    .cfi_offset x29, -0x10
    .cfi_offset x20, -0x18

    mov     x20, #0

    cbz     x5, LBL_stackArgsLoopEnd

    // Align count to 2, then multiply by 8, resulting in a size aligned to 16
    add x20, x5,  #1
    lsl x20, x20, #3
    and x20, x20, #-0x10
    // Multiply count by 8
    lsl x10, x5, #3
    sub sp, sp, x20
LBL_stackArgsLoopStart:
    ldp     x9,x11, [x4],#16
    stp     x9,x11, [sp],#16
    subs    x10, x10, #16
    bgt     LBL_stackArgsLoopStart
LBL_stackArgsLoopEnd:

    // Calculate amount to jump forward, avoiding pointless instructions
    adr     x9, LBL_populateFloatRegisterArgsEnd
    sub     x9, x9, x3, lsl 2 // x9 -= numFloatRegArgs * 4
    br      x9

    ldr     d7, [x2, #0x38]
    ldr     d6, [x2, #0x30]
    ldr     d5, [x2, #0x28]
    ldr     d4, [x2, #0x20]
    ldr     d3, [x2, #0x18]
    ldr     d2, [x2, #0x10]
    ldr     d1, [x2, #0x08]
    ldr     d0, [x2]
LBL_populateFloatRegisterArgsEnd:

    mov     x15, x6
    // Calculate amount to jump forward, avoiding pointless instructions
    adr     x9, LBL_populateGPRegisterArgsEnd
    sub     x9, x9, x1, lsl 2 // x9 -= numGPRegArgs * 4
    br      x9

    ldr     x7, [x0, #0x38]
    ldr     x6, [x0, #0x30]
    ldr     x5, [x0, #0x28]
    ldr     x4, [x0, #0x20]
    ldr     x3, [x0, #0x18]
    ldr     x2, [x0, #0x10]
    ldr     x1, [x0, #0x08]
    ldr     x0, [x0]
LBL_populateGPRegisterArgsEnd:

    // Actually call function
    sub     sp, sp, x20
    blr     x15
    add     sp, sp, x20

    ldr     x20, [sp,#0x08]
    ldp     fp, lr, [sp, #0x10]
    add sp, sp, #0x20

    ret
    .cfi_endproc

.p2align  2
_CallARM64Ret128:
    .cfi_startproc
    sub sp, sp, #0x20
    .cfi_def_cfa_offset 0x20
    stp     fp, lr, [sp,#0x10]
    str     x20, [sp,#0x08]
    add fp, sp, #0x10
    .cfi_def_cfa x29, 0x10
    .cfi_offset x30, -0x08
    .cfi_offset x29, -0x10
    .cfi_offset x20, -0x18

    mov     x20, x6
    mov     x6, x7
    mov     x7, #0
    bl      _CallARM64

    str     x1, [x20]

    ldr     x20, [sp,#0x08]
    ldp     fp, lr, [sp, #0x10]
    add sp, sp, #0x20

    ret
    .cfi_endproc

.p2align  2
_CallARM64RetInMemory:
    .cfi_startproc
    stp fp, lr, [sp,#-0x10]!
    .cfi_def_cfa_offset 0x10
    mov fp, sp
    .cfi_def_cfa x29, 0x10
    .cfi_offset x30, -0x08
    .cfi_offset x29, -0x10

    mov     x8, x6
    mov     x6, x7
    mov     x7, #0
    bl      _CallARM64

    mov     x0, x8

    ldp     fp, lr, [sp], #0x10

    ret
    .cfi_endproc

.subsections_via_symbols

#endif /* __aarch64__ */

#endif /* !AS_MAX_PORTABILITY */