]> git.sur5r.net Git - cc65/blob - src/cc65/function.c
f6d64ffabaa21e3eaaa46ddf7743be0c2e00b80e
[cc65] / src / cc65 / function.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                function.c                                 */
4 /*                                                                           */
5 /*                      Parse function entry/body/exit                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000     Ullrich von Bassewitz                                        */
10 /*              Wacholderweg 14                                              */
11 /*              D-70597 Stuttgart                                            */
12 /* EMail:       uz@musoftware.de                                             */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 /* common */
37 #include "check.h"
38 #include "xmalloc.h"
39
40 /* cc65 */
41 #include "asmcode.h"
42 #include "asmlabel.h"
43 #include "codegen.h"
44 #include "error.h"
45 #include "funcdesc.h"
46 #include "global.h"
47 #include "litpool.h"
48 #include "locals.h"
49 #include "scanner.h"
50 #include "stmt.h"
51 #include "symtab.h"
52 #include "function.h"
53
54
55
56 /*****************************************************************************/
57 /*                                   Data                                    */
58 /*****************************************************************************/
59
60
61
62 /* Structure that holds all data needed for function activation */
63 struct Function {
64     struct SymEntry*    FuncEntry;      /* Symbol table entry */
65     type*               ReturnType;     /* Function return type */
66     struct FuncDesc*    Desc;           /* Function descriptor */
67     int                 Reserved;       /* Reserved local space */
68     unsigned            RetLab;         /* Return code label */
69     int                 TopLevelSP;     /* SP at function top level */
70 };
71
72 /* Pointer to current function */
73 Function* CurrentFunc = 0;
74
75
76
77 /*****************************************************************************/
78 /*                 Subroutines working with struct Function                  */
79 /*****************************************************************************/
80
81
82
83 static Function* NewFunction (struct SymEntry* Sym)
84 /* Create a new function activation structure and return it */
85 {
86     /* Allocate a new structure */
87     Function* F = (Function*) xmalloc (sizeof (Function));
88
89     /* Initialize the fields */
90     F->FuncEntry  = Sym;
91     F->ReturnType = Sym->Type + 1 + DECODE_SIZE;
92     F->Desc       = (FuncDesc*) DecodePtr (Sym->Type + 1);
93     F->Reserved   = 0;
94     F->RetLab     = GetLabel ();
95     F->TopLevelSP = 0;
96
97     /* Return the new structure */
98     return F;
99 }
100
101
102
103 static void FreeFunction (Function* F)
104 /* Free a function activation structure */
105 {
106     xfree (F);
107 }
108
109
110
111 const char* GetFuncName (const Function* F)
112 /* Return the name of the current function */
113 {
114     return F->FuncEntry->Name;
115 }
116
117
118
119 unsigned GetParamCount (const Function* F)
120 /* Return the parameter count for the current function */
121 {
122     return F->Desc->ParamCount;
123 }
124
125
126
127 unsigned GetParamSize (const Function* F)
128 /* Return the parameter size for the current function */
129 {
130     return F->Desc->ParamSize;
131 }
132
133
134
135 type* GetReturnType (Function* F)
136 /* Get the return type for the function */
137 {
138     return F->ReturnType;
139 }
140
141
142
143 int HasVoidReturn (const Function* F)
144 /* Return true if the function does not have a return value */
145 {
146     return IsTypeVoid (F->ReturnType);
147 }
148
149
150
151 int IsVariadic (const Function* F)
152 /* Return true if this is a variadic function */
153 {
154     return (F->Desc->Flags & FD_VARIADIC) != 0;
155 }
156
157
158
159 unsigned GetRetLab (const Function* F)
160 /* Return the return jump label */
161 {
162     return F->RetLab;
163 }
164
165
166
167 int GetTopLevelSP (const Function* F)
168 /* Get the value of the stack pointer on function top level */
169 {
170     return F->TopLevelSP;
171 }
172
173
174
175 int ReserveLocalSpace (Function* F, unsigned Size)
176 /* Reserve (but don't allocate) the given local space and return the stack
177  * offset.
178  */
179 {
180     F->Reserved += Size;
181     return oursp - F->Reserved;
182 }
183
184
185
186 void AllocLocalSpace (Function* F)
187 /* Allocate any local space previously reserved. The function will do
188  * nothing if there is no reserved local space.
189  */
190 {
191     if (F->Reserved > 0) {
192
193         /* Switch to the code segment */
194         g_usecode ();
195
196         /* Create space on the stack */
197         g_space (F->Reserved);
198
199         /* Correct the stack pointer */
200         oursp -= F->Reserved;
201
202         /* Nothing more reserved */
203         F->Reserved = 0;
204     }
205 }
206
207
208
209 /*****************************************************************************/
210 /*                                   code                                    */
211 /*****************************************************************************/
212
213
214
215 void NewFunc (SymEntry* Func)
216 /* Parse argument declarations and function body. */
217 {
218     int HadReturn;
219     int IsVoidFunc;
220     unsigned Flags;
221
222     /* Get the function descriptor from the function entry */
223     FuncDesc* D = (FuncDesc*) DecodePtr (Func->Type+1);
224
225     /* Allocate the function activation record for the function */
226     CurrentFunc = NewFunction (Func);
227
228     /* Reenter the lexical level */
229     ReenterFunctionLevel (D);
230
231     /* Declare two special functions symbols: __fixargs__ and __argsize__.
232      * The latter is different depending on the type of the function (variadic
233      * or not).
234      */
235     AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
236     if (D->Flags & FD_VARIADIC) {
237         /* Variadic function. The variable must be const. */
238         static const type T [] = { T_UCHAR | T_QUAL_CONST, T_END };
239         AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
240     } else {
241         /* Non variadic */
242         AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
243     }
244
245     /* Function body now defined */
246     Func->Flags |= SC_DEF;
247
248     /* Setup register variables */
249     InitRegVars ();
250
251     /* Switch to the code segment and define the function name label */
252     g_usecode ();
253     g_defgloblabel (Func->Name);
254
255     /* If this is a fastcall function, push the last parameter onto the stack */
256     if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
257
258         SymEntry* LastParam;
259         unsigned Flags;
260
261         /* Fastcall functions may never have an ellipsis or the compiler is buggy */
262         CHECK ((D->Flags & FD_VARIADIC) == 0);
263
264         /* Get a pointer to the last parameter entry */
265         LastParam = D->SymTab->SymTail;
266
267         /* Generate the push */
268         if (IsTypeFunc (LastParam->Type)) {
269             /* Pointer to function */
270             Flags = CF_PTR;
271         } else {
272             Flags = TypeOf (LastParam->Type) | CF_FORCECHAR;
273         }
274         g_push (Flags, 0);
275     }
276
277     /* If stack checking code is requested, emit a call to the helper routine */
278     if (CheckStack) {
279         g_stackcheck ();
280     }
281
282     /* Generate function entry code if needed */
283     g_enter (TypeOf (Func->Type), GetParamSize (CurrentFunc));
284
285     /* Setup the stack */
286     oursp = 0;
287
288     /* Need a starting curly brace */
289     ConsumeLCurly ();
290
291     /* Parse local variable declarations if any */
292     DeclareLocals ();
293
294     /* Remember the current stack pointer. All variables allocated elsewhere
295      * must be dropped when doing a return from an inner block.
296      */
297     CurrentFunc->TopLevelSP = oursp;
298
299     /* Now process statements in this block */
300     HadReturn = 0;
301     while (curtok != TOK_RCURLY) {
302         if (curtok != TOK_CEOF) {
303             HadReturn = Statement ();
304         } else {
305             break;
306         }
307     }
308
309     /* If the function has a return type but no return statement, flag
310      * a warning
311      */
312     IsVoidFunc = HasVoidReturn (CurrentFunc);
313 #if 0
314     /* Does not work reliably */
315     if (!IsVoidFunc && !HadReturn) {
316         Warning ("Function `%s' should return a value", Func->Name);
317     }
318 #endif
319
320     /* Output the function exit code label */
321     g_defloclabel (GetRetLab (CurrentFunc));
322
323     /* Restore the register variables */
324     RestoreRegVars (!IsVoidFunc);
325
326     /* Generate the exit code */
327     Flags = IsVoidFunc? CF_NONE : CF_REG;
328     g_leave (Flags, 0);
329
330     /* Eat the closing brace */
331     ConsumeRCurly ();
332
333     /* Emit references to imports/exports */
334     EmitExternals ();
335
336     /* Cleanup register variables */
337     DoneRegVars ();
338
339     /* Leave the lexical level */
340     LeaveFunctionLevel ();
341
342     /* Reset the current function pointer */
343     FreeFunction (CurrentFunc);
344     CurrentFunc = 0;
345 }
346
347
348
349