/**************************************************************************
**
** This file is part of the Coroutine library
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** Copyright (C) 2015-2023 Arm Limited (or its affiliates). All rights reserved.
** Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include <cstdlib>

void
initializeStack(void *const data,
                int const size,
                void (*const entry)(),
                void **const stackBase,
                void **const stackPointer)
{
	void *const dataBottom = static_cast<char *>(data) + size;

	// align to 16 byte
	void *const stackBottom =
		reinterpret_cast<void *>
			(reinterpret_cast<std::size_t>(dataBottom) & ~0xf);
	*stackBase = stackBottom;

	void **p = static_cast<void **>(stackBottom);

	*stackBase = stackBottom;

	*(--p) = reinterpret_cast<void *>(entry); // lr
	*(--p) = stackBottom;                     // fp
	// v8-v15 are callee saved
	*(--p) = 0; //v15
	*(--p) = 0; //v14
	*(--p) = 0; //v13
	*(--p) = 0; //v12
	*(--p) = 0; //v11
	*(--p) = 0; //v10
	*(--p) = 0; //v9
	*(--p) = 0; //v8

	*(--p) = 0; // r28
	*(--p) = 0; // r27
	*(--p) = 0; // r26
	*(--p) = 0; // r25
	*(--p) = 0; // r24
	*(--p) = 0; // r23
	*(--p) = 0; // r22
	*(--p) = 0; // r21
	*(--p) = 0; // r20
	*(--p) = 0; // r19

	*stackPointer = p;
}
