1353358Sdim//===----- trampoline_setup.c - Implement __trampoline_setup -------------===//
2353358Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6353358Sdim//
7353358Sdim//===----------------------------------------------------------------------===//
8276789Sdim
9276789Sdim#include "int_lib.h"
10276789Sdim
11353358Sdimextern void __clear_cache(void *start, void *end);
12276789Sdim
13353358Sdim// The ppc compiler generates calls to __trampoline_setup() when creating
14353358Sdim// trampoline functions on the stack for use with nested functions.
15353358Sdim// This function creates a custom 40-byte trampoline function on the stack
16353358Sdim// which loads r11 with a pointer to the outer function's locals
17353358Sdim// and then jumps to the target nested function.
18276789Sdim
19276789Sdim#if __ppc__ && !defined(__powerpc64__)
20353358SdimCOMPILER_RT_ABI void __trampoline_setup(uint32_t *trampOnStack,
21353358Sdim                                        int trampSizeAllocated,
22353358Sdim                                        const void *realFunc, void *localsPtr) {
23353358Sdim  // should never happen, but if compiler did not allocate
24353358Sdim  // enough space on stack for the trampoline, abort
25353358Sdim  if (trampSizeAllocated < 40)
26353358Sdim    compilerrt_abort();
27353358Sdim
28353358Sdim  // create trampoline
29353358Sdim  trampOnStack[0] = 0x7c0802a6; // mflr r0
30353358Sdim  trampOnStack[1] = 0x4800000d; // bl Lbase
31353358Sdim  trampOnStack[2] = (uint32_t)realFunc;
32353358Sdim  trampOnStack[3] = (uint32_t)localsPtr;
33353358Sdim  trampOnStack[4] = 0x7d6802a6; // Lbase: mflr r11
34353358Sdim  trampOnStack[5] = 0x818b0000; // lwz    r12,0(r11)
35353358Sdim  trampOnStack[6] = 0x7c0803a6; // mtlr r0
36353358Sdim  trampOnStack[7] = 0x7d8903a6; // mtctr r12
37353358Sdim  trampOnStack[8] = 0x816b0004; // lwz    r11,4(r11)
38353358Sdim  trampOnStack[9] = 0x4e800420; // bctr
39353358Sdim
40353358Sdim  // clear instruction cache
41353358Sdim  __clear_cache(trampOnStack, &trampOnStack[10]);
42276789Sdim}
43353358Sdim#endif // __ppc__ && !defined(__powerpc64__)
44