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, 2025 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 152805 : isProjectConst(const InstrRecord *p)
32 : {
33 152805 : return (getModuleId(p) == algebraRef && getFunctionId(p) == projectRef);
34 : }
35 :
36 : __attribute__((__pure__))
37 : static int
38 7707897 : hashInstruction(const MalBlkRecord *mb, const InstrRecord *p)
39 : {
40 7707897 : int i;
41 21140716 : for (i = p->argc - 1; i >= p->retc; i--)
42 20791762 : if (!isVarConstant(mb, getArg(p, i)))
43 7358943 : return getArg(p, i);
44 348954 : if (isVarConstant(mb, getArg(p, p->retc)))
45 348954 : return p->retc;
46 : return -1;
47 : }
48 :
49 : str
50 536426 : OPTcommonTermsImplementation(Client cntxt, MalBlkPtr mb, MalStkPtr stk,
51 : InstrPtr pci)
52 : {
53 536426 : int i, j, k, barrier = 0, bailout = 0;
54 536426 : InstrPtr p, q;
55 536426 : int actions = 0;
56 536426 : int limit, slimit;
57 536426 : int duplicate;
58 536426 : int *alias = NULL;
59 536426 : int *hash = NULL, h;
60 536426 : int *list = NULL;
61 536426 : str msg = MAL_SUCCEED;
62 :
63 536426 : InstrPtr *old = NULL;
64 :
65 : /* catch simple insert operations */
66 536426 : if (isSimpleSQL(mb)) {
67 291457 : goto wrapup;
68 : }
69 :
70 244969 : (void) cntxt;
71 244969 : (void) stk;
72 244969 : alias = (int *) GDKzalloc(sizeof(int) * mb->vtop);
73 244968 : list = (int *) GDKzalloc(sizeof(int) * mb->stop);
74 244967 : hash = (int *) GDKzalloc(sizeof(int) * mb->vtop);
75 244968 : if (alias == NULL || list == NULL || hash == NULL) {
76 0 : msg = createException(MAL, "optimizer.commonTerms",
77 : SQLSTATE(HY013) MAL_MALLOC_FAIL);
78 0 : goto wrapup;
79 : }
80 :
81 244968 : old = mb->stmt;
82 244968 : limit = mb->stop;
83 244968 : slimit = mb->ssize;
84 244968 : if (newMalBlkStmt(mb, mb->ssize) < 0) {
85 0 : msg = createException(MAL, "optimizer.commonTerms",
86 : SQLSTATE(HY013) MAL_MALLOC_FAIL);
87 0 : old = NULL;
88 0 : goto wrapup;
89 : }
90 :
91 10586386 : for (i = 0; mb->errors == NULL && i < limit; i++) {
92 10586386 : p = old[i];
93 10586386 : duplicate = 0;
94 :
95 57625920 : for (k = 0; k < p->argc; k++)
96 47039534 : if (alias[getArg(p, k)])
97 186618 : getArg(p, k) = alias[getArg(p, k)];
98 :
99 10586386 : if (p->token == ENDsymbol) {
100 233582 : pushInstruction(mb, p);
101 233581 : old[i] = NULL;
102 233581 : break;
103 : }
104 : /*
105 : * Any barrier block signals the end of this optimizer,
106 : * because the impact of the block can affect the common code eliminated.
107 : */
108 20705608 : barrier |= (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
109 10352804 : || p->barrier == RETURNsymbol);
110 : /*
111 : * Also block further optimization when you have seen an assert().
112 : * This works particularly for SQL, because it is not easy to track
113 : * the BAT identifier aliases to look for updates. The sql.assert
114 : * at least tells us that an update is planned.
115 : * Like all optimizer decisions, it is safe to stop.
116 : */
117 10352804 : barrier |= getFunctionId(p) == assertRef;
118 10352804 : if (barrier || p->token == ASSIGNsymbol) {
119 11381 : TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d]: %d %d\n", i, barrier,
120 : p->retc == p->argc);
121 11381 : pushInstruction(mb, p);
122 11381 : old[i] = NULL;
123 11381 : break;
124 : }
125 :
126 : /* when we enter a barrier block, we should ditch all previous instructions from consideration */
127 10341423 : if (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
128 10341423 : || p->barrier == RETURNsymbol) {
129 0 : memset(list, 0, sizeof(int) * mb->stop);
130 0 : memset(hash, 0, sizeof(int) * mb->vtop);
131 : }
132 : /* side-effect producing operators can never be replaced */
133 : /* the same holds for function calls without an argument, it is
134 : * unclear where the results comes from (e.g. clock()) */
135 10341423 : if (mayhaveSideEffects(cntxt, mb, p, TRUE) || p->argc == p->retc) {
136 1840608 : TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d] side-effect: %d\n", i,
137 : p->retc == p->argc);
138 1840608 : pushInstruction(mb, p);
139 1840580 : old[i] = NULL;
140 1840580 : continue;
141 : }
142 : /* simple SQL bind operations need not be merged, they are cheap
143 : * and/or can be duplicated eliminated elsewhere cheaper */
144 8501088 : if (getModuleId(p) == sqlRef && (getFunctionId(p) != tidRef && getFunctionId(p) != bindRef)) {
145 587741 : pushInstruction(mb, p);
146 587741 : old[i] = NULL;
147 587741 : continue;
148 : }
149 7913347 : if (getModuleId(p) == matRef) { /* mat.packIncrement has requirement on number of instructions (or that needs an update */
150 205659 : pushInstruction(mb, p);
151 205659 : old[i] = NULL;
152 205659 : continue;
153 : }
154 :
155 : /* from here we have a candidate to look for a match */
156 :
157 7707688 : h = hashInstruction(mb, p);
158 :
159 7707688 : TRC_DEBUG(MAL_OPTIMIZER, "Candidate[%d] look at list[%d] => %d\n", i, h,
160 : hash[h]);
161 7707688 : traceInstruction(mb, 0, p, LIST_MAL_ALL);
162 :
163 7707724 : if (h < 0) {
164 0 : pushInstruction(mb, p);
165 0 : old[i] = NULL;
166 0 : continue;
167 : }
168 :
169 7707724 : bailout = 1024; // don't run over long collision list
170 : /* Look into the hash structure for matching instructions */
171 47382741 : for (j = hash[h]; j > 0 && bailout-- > 0; j = list[j]) {
172 39812702 : if ((q = getInstrPtr(mb, j))
173 39812702 : && getFunctionId(q) == getFunctionId(p)
174 28465082 : && getModuleId(q) == getModuleId(p)) {
175 28465076 : TRC_DEBUG(MAL_OPTIMIZER,
176 : "Candidate[%d->%d] %d %d :%d %d %d=%d %d %d %d\n", j,
177 : list[j], hasSameSignature(mb, p, q),
178 : hasSameArguments(mb, p, q), q->token != ASSIGNsymbol,
179 : list[getArg(q, q->argc - 1)], i, !hasCommonResults(p,
180 : q),
181 : !isUnsafeFunction(q), !isUpdateInstruction(q),
182 : isLinearFlow(q));
183 28465076 : traceInstruction(mb, 0, q, LIST_MAL_ALL);
184 :
185 : /*
186 : * Simple assignments are not replaced either. They should be
187 : * handled by the alias removal part. All arguments should
188 : * be assigned their value before instruction p.
189 : */
190 28464556 : if (hasSameArguments(mb, p, q)
191 152823 : && hasSameSignature(mb, p, q)
192 152805 : && !hasCommonResults(p, q)
193 152805 : && !isUnsafeFunction(q)
194 152805 : && !isUpdateInstruction(q)
195 152805 : && !isProjectConst(q) && /* disable project(x,val), as its used for the result of case statements */
196 137686 : isLinearFlow(q)) {
197 137686 : if (safetyBarrier(p, q)) {
198 0 : TRC_DEBUG(MAL_OPTIMIZER, "Safety barrier reached\n");
199 : break;
200 : }
201 137686 : duplicate = 1;
202 137686 : clrFunction(p);
203 137686 : p->argc = p->retc;
204 285284 : for (k = 0; k < q->retc; k++) {
205 147598 : alias[getArg(p, k)] = getArg(q, k);
206 : /* we know the arguments fit so the instruction can safely be patched */
207 147598 : p = pushArgument(mb, p, getArg(q, k));
208 : }
209 :
210 137686 : TRC_DEBUG(MAL_OPTIMIZER, "Modified expression %d -> %d ",
211 : getArg(p, 0), getArg(p, 1));
212 137686 : traceInstruction(mb, 0, p, LIST_MAL_ALL);
213 :
214 137686 : actions++;
215 137686 : break; /* end of search */
216 : }
217 11347626 : } else if (isUpdateInstruction(p)) {
218 0 : TRC_DEBUG(MAL_OPTIMIZER, "Skipped: %d %d\n",
219 : mayhaveSideEffects(cntxt, mb, q, TRUE),
220 : isUpdateInstruction(p));
221 0 : traceInstruction(mb, 0, q, LIST_MAL_ALL);
222 : }
223 : }
224 :
225 7707725 : if (duplicate) {
226 137686 : pushInstruction(mb, p);
227 137686 : old[i] = NULL;
228 137686 : continue;
229 : }
230 : /* update the hash structure with another candidate for reuse */
231 7570039 : TRC_DEBUG(MAL_OPTIMIZER,
232 : "Update hash[%d] - look at arg '%d' hash '%d' list '%d'\n", i,
233 : getArg(p, p->argc - 1), h, hash[h]);
234 7570039 : traceInstruction(mb, 0, p, LIST_MAL_ALL);
235 :
236 7569998 : if (!mayhaveSideEffects(cntxt, mb, p, TRUE) && p->argc != p->retc
237 15139838 : && isLinearFlow(p) && !isUnsafeFunction(p)
238 7569861 : && !isUpdateInstruction(p)) {
239 7569804 : list[i] = hash[h];
240 7569804 : hash[h] = i;
241 7569804 : pushInstruction(mb, p);
242 7569758 : old[i] = NULL;
243 : }
244 : }
245 57968535 : for (; i < slimit; i++)
246 57723572 : if (old[i])
247 6679105 : pushInstruction(mb, old[i]);
248 : /* Defense line against incorrect plans */
249 244963 : if (actions > 0) {
250 10250 : msg = chkTypes(cntxt->usermodule, mb, FALSE);
251 10250 : if (!msg)
252 10250 : msg = chkFlow(mb);
253 10250 : if (!msg)
254 10250 : msg = chkDeclarations(mb);
255 : }
256 234713 : wrapup:
257 : /* keep actions taken as a fake argument */
258 536420 : (void) pushInt(mb, pci, actions);
259 :
260 536420 : if (alias)
261 244963 : GDKfree(alias);
262 536426 : if (list)
263 244969 : GDKfree(list);
264 536426 : if (hash)
265 244969 : GDKfree(hash);
266 536425 : if (old)
267 244968 : GDKfree(old);
268 536426 : return msg;
269 : }
|