LCOV - code coverage report
Current view: top level - monetdb5/optimizer - opt_commonTerms.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 128 141 90.8 %
Date: 2024-11-15 19:37:45 Functions: 2 2 100.0 %

          Line data    Source code
       1             : /*
       2             :  * SPDX-License-Identifier: MPL-2.0
       3             :  *
       4             :  * This Source Code Form is subject to the terms of the Mozilla Public
       5             :  * License, v. 2.0.  If a copy of the MPL was not distributed with this
       6             :  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
       7             :  *
       8             :  * Copyright 2024 MonetDB Foundation;
       9             :  * Copyright August 2008 - 2023 MonetDB B.V.;
      10             :  * Copyright 1997 - July 2008 CWI.
      11             :  */
      12             : 
      13             : #include "monetdb_config.h"
      14             : #include "opt_commonTerms.h"
      15             : #include "mal_exception.h"
      16             :  /*
      17             :   * Caveat. A lot of time was lost due to constants that are indistinguisable
      18             :   * at the surface level.  It requires the constant optimizer to be ran first.
      19             :   */
      20             : 
      21             : /* The key for finding common terms is that they share variables.
      22             :  * Therefore we skip all constants, except for a constant only situation.
      23             :  */
      24             : 
      25             : /*
      26             :  * Speed up simple insert operations by skipping the common terms.
      27             : */
      28             : 
      29             : __attribute__((__pure__))
      30             : static inline bool
      31      221173 : isProjectConst(const InstrRecord *p)
      32             : {
      33      221173 :         return (getModuleId(p) == algebraRef && getFunctionId(p) == projectRef);
      34             : }
      35             : 
      36             : static int __attribute__((__pure__))
      37    12318967 : hashInstruction(const MalBlkRecord *mb, const InstrRecord *p)
      38             : {
      39    12318967 :         int i;
      40    31860331 :         for (i = p->argc - 1; i >= p->retc; i--)
      41    31554109 :                 if (!isVarConstant(mb, getArg(p, i)))
      42    12012745 :                         return getArg(p, i);
      43      306222 :         if (isVarConstant(mb, getArg(p, p->retc)))
      44      306222 :                 return p->retc;
      45             :         return -1;
      46             : }
      47             : 
      48             : str
      49      445892 : OPTcommonTermsImplementation(Client cntxt, MalBlkPtr mb, MalStkPtr stk,
      50             :                                                          InstrPtr pci)
      51             : {
      52      445892 :         int i, j, k, barrier = 0, bailout = 0;
      53      445892 :         InstrPtr p, q;
      54      445892 :         int actions = 0;
      55      445892 :         int limit, slimit;
      56      445892 :         int duplicate;
      57      445892 :         int *alias = NULL;
      58      445892 :         int *hash = NULL, h;
      59      445892 :         int *list = NULL;
      60      445892 :         str msg = MAL_SUCCEED;
      61             : 
      62      445892 :         InstrPtr *old = NULL;
      63             : 
      64             :         /* catch simple insert operations */
      65      445892 :         if (isSimpleSQL(mb)) {
      66      283635 :                 goto wrapup;
      67             :         }
      68             : 
      69      162287 :         (void) cntxt;
      70      162287 :         (void) stk;
      71      162287 :         alias = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      72      162300 :         list = (int *) GDKzalloc(sizeof(int) * mb->stop);
      73      162290 :         hash = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      74      162300 :         if (alias == NULL || list == NULL || hash == NULL) {
      75           0 :                 msg = createException(MAL, "optimizer.commonTerms",
      76             :                                                           SQLSTATE(HY013) MAL_MALLOC_FAIL);
      77           0 :                 goto wrapup;
      78             :         }
      79             : 
      80      162300 :         old = mb->stmt;
      81      162300 :         limit = mb->stop;
      82      162300 :         slimit = mb->ssize;
      83      162300 :         if (newMalBlkStmt(mb, mb->ssize) < 0) {
      84           0 :                 msg = createException(MAL, "optimizer.commonTerms",
      85             :                                                           SQLSTATE(HY013) MAL_MALLOC_FAIL);
      86           0 :                 old = NULL;
      87           0 :                 goto wrapup;
      88             :         }
      89             : 
      90    14773079 :         for (i = 0; mb->errors == NULL && i < limit; i++) {
      91    14773079 :                 p = old[i];
      92    14773079 :                 duplicate = 0;
      93             : 
      94    79753106 :                 for (k = 0; k < p->argc; k++)
      95    64980027 :                         if (alias[getArg(p, k)])
      96      276652 :                                 getArg(p, k) = alias[getArg(p, k)];
      97             : 
      98    14773079 :                 if (p->token == ENDsymbol) {
      99      162247 :                         pushInstruction(mb, p);
     100      162264 :                         old[i] = NULL;
     101      162264 :                         break;
     102             :                 }
     103             :                 /*
     104             :                  * Any barrier block signals the end of this optimizer,
     105             :                  * because the impact of the block can affect the common code eliminated.
     106             :                  */
     107    29221664 :                 barrier |= (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     108    14610832 :                                         || p->barrier == RETURNsymbol);
     109             :                 /*
     110             :                  * Also block further optimization when you have seen an assert().
     111             :                  * This works particularly for SQL, because it is not easy to track
     112             :                  * the BAT identifier aliases to look for updates. The sql.assert
     113             :                  * at least tells us that an update is planned.
     114             :                  * Like all optimizer decisions, it is safe to stop.
     115             :                  */
     116    14610832 :                 barrier |= getFunctionId(p) == assertRef;
     117    14610832 :                 if (barrier || p->token == ASSIGNsymbol) {
     118      256190 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d]: %d %d\n", i, barrier,
     119             :                                           p->retc == p->argc);
     120      256190 :                         pushInstruction(mb, p);
     121      256210 :                         old[i] = NULL;
     122      256210 :                         continue;
     123             :                 }
     124             : 
     125             :                 /* when we enter a barrier block, we should ditch all previous instructions from consideration */
     126    14354642 :                 if (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     127    14354642 :                         || p->barrier == RETURNsymbol) {
     128           0 :                         memset(list, 0, sizeof(int) * mb->stop);
     129           0 :                         memset(hash, 0, sizeof(int) * mb->vtop);
     130             :                 }
     131             :                 /* side-effect producing operators can never be replaced */
     132             :                 /* the same holds for function calls without an argument, it is
     133             :                  * unclear where the results comes from (e.g. clock()) */
     134    14354642 :                 if (mayhaveSideEffects(cntxt, mb, p, TRUE) || p->argc == p->retc) {
     135     1150795 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d] side-effect: %d\n", i,
     136             :                                           p->retc == p->argc);
     137     1150795 :                         pushInstruction(mb, p);
     138     1150825 :                         old[i] = NULL;
     139     1150825 :                         continue;
     140             :                 }
     141             :                 /* simple SQL bind operations need not be merged, they are cheap
     142             :                  * and/or can be duplicated eliminated elsewhere cheaper */
     143    13204698 :                 if (getModuleId(p) == sqlRef && (getFunctionId(p) != tidRef && getFunctionId(p) != bindRef)) {
     144      703459 :                         pushInstruction(mb, p);
     145      703459 :                         old[i] = NULL;
     146      703459 :                         continue;
     147             :                 }
     148    12501239 :                 if (getModuleId(p) == matRef) { /* mat.packIncrement has requirement on number of instructions (or that needs an update */
     149      182844 :                         pushInstruction(mb, p);
     150      182844 :                         old[i] = NULL;
     151      182844 :                         continue;
     152             :                 }
     153             : 
     154             :                 /* from here we have a candidate to look for a match */
     155             : 
     156    12318395 :                 h = hashInstruction(mb, p);
     157             : 
     158    12318395 :                 TRC_DEBUG(MAL_OPTIMIZER, "Candidate[%d] look at list[%d] => %d\n", i, h,
     159             :                                   hash[h]);
     160    12318395 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     161             : 
     162    12318574 :                 if (h < 0) {
     163           0 :                         pushInstruction(mb, p);
     164           0 :                         old[i] = NULL;
     165           0 :                         continue;
     166             :                 }
     167             : 
     168    12318574 :                 bailout = 1024;                 // don't run over long collision list
     169             :                 /* Look into the hash structure for matching instructions */
     170    97372489 :                 for (j = hash[h]; j > 0 && bailout-- > 0; j = list[j]) {
     171    85258794 :                         if ((q = getInstrPtr(mb, j))
     172    85258794 :                                 && getFunctionId(q) == getFunctionId(p)
     173    62709002 :                                 && getModuleId(q) == getModuleId(p)) {
     174    62713826 :                                 TRC_DEBUG(MAL_OPTIMIZER,
     175             :                                                   "Candidate[%d->%d] %d %d :%d %d %d=%d %d %d %d\n", j,
     176             :                                                   list[j], hasSameSignature(mb, p, q),
     177             :                                                   hasSameArguments(mb, p, q), q->token != ASSIGNsymbol,
     178             :                                                   list[getArg(q, q->argc - 1)], i, !hasCommonResults(p,
     179             :                                                                                                                                                          q),
     180             :                                                   !isUnsafeFunction(q), !isUpdateInstruction(q),
     181             :                                                   isLinearFlow(q));
     182    62713826 :                                 traceInstruction(MAL_OPTIMIZER, mb, 0, q, LIST_MAL_ALL);
     183             : 
     184             :                                 /*
     185             :                                  * Simple assignments are not replaced either. They should be
     186             :                                  * handled by the alias removal part. All arguments should
     187             :                                  * be assigned their value before instruction p.
     188             :                                  */
     189    62713576 :                                 if (hasSameArguments(mb, p, q)
     190      221191 :                                         && hasSameSignature(mb, p, q)
     191      221173 :                                         && !hasCommonResults(p, q)
     192      221173 :                                         && !isUnsafeFunction(q)
     193      221173 :                                         && !isUpdateInstruction(q)
     194      221173 :                                         && !isProjectConst(q) &&        /* disable project(x,val), as its used for the result of case statements */
     195      202039 :                                         isLinearFlow(q)) {
     196      202039 :                                         if (safetyBarrier(p, q)) {
     197           0 :                                                 TRC_DEBUG(MAL_OPTIMIZER, "Safety barrier reached\n");
     198             :                                                 break;
     199             :                                         }
     200      202039 :                                         duplicate = 1;
     201      202039 :                                         clrFunction(p);
     202      202039 :                                         p->argc = p->retc;
     203      412897 :                                         for (k = 0; k < q->retc; k++) {
     204      210858 :                                                 alias[getArg(p, k)] = getArg(q, k);
     205             :                                                 /* we know the arguments fit so the instruction can safely be patched */
     206      210858 :                                                 p = pushArgument(mb, p, getArg(q, k));
     207             :                                         }
     208             : 
     209      202039 :                                         TRC_DEBUG(MAL_OPTIMIZER, "Modified expression %d -> %d ",
     210             :                                                           getArg(p, 0), getArg(p, 1));
     211      202039 :                                         traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     212             : 
     213      202039 :                                         actions++;
     214      202039 :                                         break;          /* end of search */
     215             :                                 }
     216    22544968 :                         } else if (isUpdateInstruction(p)) {
     217           0 :                                 TRC_DEBUG(MAL_OPTIMIZER, "Skipped: %d %d\n",
     218             :                                                   mayhaveSideEffects(cntxt, mb, q, TRUE),
     219             :                                                   isUpdateInstruction(p));
     220           0 :                                 traceInstruction(MAL_OPTIMIZER, mb, 0, q, LIST_MAL_ALL);
     221             :                         }
     222             :                 }
     223             : 
     224    12315734 :                 if (duplicate) {
     225      202039 :                         pushInstruction(mb, p);
     226      202039 :                         old[i] = NULL;
     227      202039 :                         continue;
     228             :                 }
     229             :                 /* update the hash structure with another candidate for reuse */
     230    12113695 :                 TRC_DEBUG(MAL_OPTIMIZER,
     231             :                                   "Update hash[%d] - look at arg '%d' hash '%d' list '%d'\n", i,
     232             :                                   getArg(p, p->argc - 1), h, hash[h]);
     233    12113695 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     234             : 
     235    12114484 :                 if (!mayhaveSideEffects(cntxt, mb, p, TRUE) && p->argc != p->retc
     236    24230680 :                         && isLinearFlow(p) && !isUnsafeFunction(p)
     237    12115295 :                         && !isUpdateInstruction(p)) {
     238    12115362 :                         list[i] = hash[h];
     239    12115362 :                         hash[h] = i;
     240    12115362 :                         pushInstruction(mb, p);
     241    12115680 :                         old[i] = NULL;
     242             :                 }
     243             :         }
     244    37533229 :         for (; i < slimit; i++)
     245    37370935 :                 if (old[i])
     246     3934902 :                         pushInstruction(mb, old[i]);
     247             :         /* Defense line against incorrect plans */
     248      162294 :         if (actions > 0) {
     249        8284 :                 msg = chkTypes(cntxt->usermodule, mb, FALSE);
     250        8284 :                 if (!msg)
     251        8284 :                         msg = chkFlow(mb);
     252        8284 :                 if (!msg)
     253        8284 :                         msg = chkDeclarations(mb);
     254             :         }
     255      154010 :   wrapup:
     256             :         /* keep actions taken as a fake argument */
     257      445929 :         (void) pushInt(mb, pci, actions);
     258             : 
     259      445922 :         if (alias)
     260      162287 :                 GDKfree(alias);
     261      445939 :         if (list)
     262      162304 :                 GDKfree(list);
     263      445935 :         if (hash)
     264      162300 :                 GDKfree(hash);
     265      445934 :         if (old)
     266      162299 :                 GDKfree(old);
     267      445935 :         return msg;
     268             : }

Generated by: LCOV version 1.14