]> git.sur5r.net Git - cc65/blobdiff - src/cc65/function.c
Optimizations, cleanup in codegen
[cc65] / src / cc65 / function.c
index f1a160b6d9115801eb5fc5de61b35ec03bba6f4f..06786e6e8cf16a6fa0f5a7d12f1683db42098f50 100644 (file)
@@ -6,10 +6,10 @@
 /*                                                                           */
 /*                                                                           */
 /*                                                                           */
-/* (C) 2000     Ullrich von Bassewitz                                        */
-/*              Wacholderweg 14                                              */
-/*              D-70597 Stuttgart                                            */
-/* EMail:       uz@musoftware.de                                             */
+/* (C) 2000-2001 Ullrich von Bassewitz                                       */
+/*               Wacholderweg 14                                             */
+/*               D-70597 Stuttgart                                           */
+/* EMail:        uz@cc65.org                                                 */
 /*                                                                           */
 /*                                                                           */
 /* This software is provided 'as-is', without any expressed or implied       */
 
 
 
+/* common */
+#include "check.h"
+#include "xmalloc.h"
+
+/* cc65 */
 #include "asmcode.h"
 #include "asmlabel.h"
 #include "codegen.h"
 #include "error.h"
 #include "funcdesc.h"
+#include "global.h"
 #include "litpool.h"
 #include "locals.h"
-#include "mem.h"
 #include "scanner.h"
+#include "segments.h"
 #include "stmt.h"
 #include "symtab.h"
 #include "function.h"
 /* Structure that holds all data needed for function activation */
 struct Function {
     struct SymEntry*           FuncEntry;      /* Symbol table entry */
-    type*              ReturnType;     /* Function return type */
+    type*              ReturnType;     /* Function return type */
     struct FuncDesc*   Desc;           /* Function descriptor */
-    CodeMark           EntryCode;      /* Backpatch addr for entry code */
-    unsigned           LocalMax;       /* Total space for locals */
-    unsigned                   LocalSize;      /* Current space for locals */
-    unsigned           RetLab;         /* Return code label */
+    int                        Reserved;       /* Reserved local space */
+    unsigned           RetLab;         /* Return code label */
+    int                        TopLevelSP;     /* SP at function top level */
 };
 
 /* Pointer to current function */
@@ -71,7 +76,7 @@ Function* CurrentFunc = 0;
 
 
 /*****************************************************************************/
-/*                                          code                                    */
+/*                Subroutines working with struct Function                  */
 /*****************************************************************************/
 
 
@@ -80,16 +85,15 @@ static Function* NewFunction (struct SymEntry* Sym)
 /* Create a new function activation structure and return it */
 {
     /* Allocate a new structure */
-    Function* F = xmalloc (sizeof (Function));
+    Function* F = (Function*) xmalloc (sizeof (Function));
 
     /* Initialize the fields */
     F->FuncEntry  = Sym;
-    F->ReturnType = Sym->Type + 1 + DECODE_SIZE;
-    F->Desc      = DecodePtr (Sym->Type + 1);
-    F->EntryCode  = GetCodePos ();
-    F->LocalMax          = 0;
-    F->LocalSize  = 0;
-    F->RetLab    = GetLabel ();
+    F->ReturnType = GetFuncReturn (Sym->Type);
+    F->Desc      = (FuncDesc*) DecodePtr (Sym->Type + 1);
+    F->Reserved          = 0;
+    F->RetLab    = GetLocalLabel ();
+    F->TopLevelSP = 0;
 
     /* Return the new structure */
     return F;
@@ -113,6 +117,14 @@ const char* GetFuncName (const Function* F)
 
 
 
+unsigned GetParamCount (const Function* F)
+/* Return the parameter count for the current function */
+{
+    return F->Desc->ParamCount;
+}
+
+
+
 unsigned GetParamSize (const Function* F)
 /* Return the parameter size for the current function */
 {
@@ -132,7 +144,15 @@ type* GetReturnType (Function* F)
 int HasVoidReturn (const Function* F)
 /* Return true if the function does not have a return value */
 {
-    return IsVoid (F->ReturnType);
+    return IsTypeVoid (F->ReturnType);
+}
+
+
+
+int IsVariadic (const Function* F)
+/* Return true if this is a variadic function */
+{
+    return (F->Desc->Flags & FD_VARIADIC) != 0;
 }
 
 
@@ -145,39 +165,59 @@ unsigned GetRetLab (const Function* F)
 
 
 
-unsigned AllocLocalSpace (Function* F, unsigned Size)
-/* Allocate space for the function locals, return stack offset */
+int GetTopLevelSP (const Function* F)
+/* Get the value of the stack pointer on function top level */
 {
-    /* Remember the current offset */
-    unsigned Offs = F->LocalSize;
+    return F->TopLevelSP;
+}
 
-    /* Add the size */
-    F->LocalSize += Size;
-    if (F->LocalSize > F->LocalMax) {
-       F->LocalMax = F->LocalSize;
-    }
 
-    /* Return the offset */
-    return Offs;
+
+int ReserveLocalSpace (Function* F, unsigned Size)
+/* Reserve (but don't allocate) the given local space and return the stack
+ * offset.
+ */
+{
+    F->Reserved += Size;
+    return oursp - F->Reserved;
 }
 
 
 
-void FreeLocalSpace (Function* F, unsigned Size)
-/* Free space allocated for function locals */
+void AllocLocalSpace (Function* F)
+/* Allocate any local space previously reserved. The function will do
+ * nothing if there is no reserved local space.
+ */
 {
-    F->LocalSize -= Size;
+    if (F->Reserved > 0) {
+
+       /* Create space on the stack */
+       g_space (F->Reserved);
+
+       /* Correct the stack pointer */
+       oursp -= F->Reserved;
+
+       /* Nothing more reserved */
+       F->Reserved = 0;
+    }
 }
 
 
 
+/*****************************************************************************/
+/*                                          code                                    */
+/*****************************************************************************/
+
+
+
 void NewFunc (SymEntry* Func)
 /* Parse argument declarations and function body. */
 {
-    int isbrk;
+    int HadReturn;
+    int IsVoidFunc;
 
     /* Get the function descriptor from the function entry */
-    FuncDesc* D = DecodePtr (Func->Type+1);
+    FuncDesc* D = Func->V.F.Func;
 
     /* Allocate the function activation record for the function */
     CurrentFunc = NewFunction (Func);
@@ -185,44 +225,108 @@ void NewFunc (SymEntry* Func)
     /* Reenter the lexical level */
     ReenterFunctionLevel (D);
 
+    /* Declare two special functions symbols: __fixargs__ and __argsize__.
+     * The latter is different depending on the type of the function (variadic
+     * or not).
+     */
+    AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
+    if (D->Flags & FD_VARIADIC) {
+       /* Variadic function. The variable must be const. */
+       static const type T [] = { T_UCHAR | T_QUAL_CONST, T_END };
+       AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
+    } else {
+       /* Non variadic */
+               AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
+    }
+
     /* Function body now defined */
     Func->Flags |= SC_DEF;
 
-    /* C functions cannot currently have __fastcall__ calling conventions */
-    if (IsFastCallFunc (Func->Type)) {
-       Error (ERR_FASTCALL);
-    }
+    /* Setup register variables */
+    InitRegVars ();
 
-    /* Need a starting curly brace */
-    if (curtok != LCURLY) {
-       Error (ERR_LCURLY_EXPECTED);
+    /* Allocate code and data segments for this function */
+    Func->V.F.Seg = PushSegments (Func);
+
+    /* If this is a fastcall function, push the last parameter onto the stack */
+    if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
+
+       SymEntry* LastParam;
+       unsigned Flags;
+
+       /* Fastcall functions may never have an ellipsis or the compiler is buggy */
+       CHECK ((D->Flags & FD_VARIADIC) == 0);
+
+       /* Get a pointer to the last parameter entry */
+       LastParam = D->SymTab->SymTail;
+
+       /* Generate the push */
+       if (IsTypeFunc (LastParam->Type)) {
+           /* Pointer to function */
+           Flags = CF_PTR;
+       } else {
+           Flags = TypeOf (LastParam->Type) | CF_FORCECHAR;
+       }
+       g_push (Flags, 0);
     }
 
-    /* Setup register variables */
-    InitRegVars ();
+    /* If stack checking code is requested, emit a call to the helper routine */
+    if (CheckStack) {
+       g_stackcheck ();
+    }
 
-    /* Switch to the code segment and generate function entry code */
-    g_usecode ();
-    g_enter (TypeOf (Func->Type), Func->Name, GetParamSize (CurrentFunc));
+    /* Generate function entry code if needed */
+    g_enter (TypeOf (Func->Type), GetParamSize (CurrentFunc));
 
-    /* Parse the function body */
+    /* Setup the stack */
     oursp = 0;
-    isbrk = compound ();
 
-    /* If the function did not end with an return statement, create exit code */
-    if (!isbrk) {
-#if 0
-       /* If the function has a return type, flag an error */
-       if (!voidfunc) {
-           Error (ERR_MUST_RETURN_VALUE);
+    /* Need a starting curly brace */
+    ConsumeLCurly ();
+
+    /* Parse local variable declarations if any */
+    DeclareLocals ();
+
+    /* Remember the current stack pointer. All variables allocated elsewhere
+     * must be dropped when doing a return from an inner block.
+     */
+    CurrentFunc->TopLevelSP = oursp;
+
+    /* Now process statements in this block */
+    HadReturn = 0;
+    while (CurTok.Tok != TOK_RCURLY) {
+       if (CurTok.Tok != TOK_CEOF) {
+           HadReturn = Statement (0);
+       } else {
+           break;
        }
-#endif
-       RestoreRegVars (0);
-        g_leave (CF_NONE, 0);
     }
 
-    /* Dump literal data created by the function */
-    DumpLiteralPool ();
+    /* If the function has a return type but no return statement, flag
+     * a warning
+     */
+    IsVoidFunc = HasVoidReturn (CurrentFunc);
+#if 0
+    /* Does not work reliably */
+    if (!IsVoidFunc && !HadReturn) {
+       Warning ("Function `%s' should return a value", Func->Name);
+    }
+#endif
+
+    /* Output the function exit code label */
+    g_defcodelabel (GetRetLab (CurrentFunc));
+
+    /* Restore the register variables */
+    RestoreRegVars (!IsVoidFunc);
+
+    /* Generate the exit code */
+    g_leave ();
+
+    /* Eat the closing brace */
+    ConsumeRCurly ();
+
+    /* Emit references to imports/exports */
+    EmitExternals ();
 
     /* Cleanup register variables */
     DoneRegVars ();
@@ -230,6 +334,9 @@ void NewFunc (SymEntry* Func)
     /* Leave the lexical level */
     LeaveFunctionLevel ();
 
+    /* Switch back to the old segments */
+    PopSegments ();
+
     /* Reset the current function pointer */
     FreeFunction (CurrentFunc);
     CurrentFunc = 0;