xref: /php-src/Zend/Optimizer/dce.c (revision 631bc816)
1 /*
2    +----------------------------------------------------------------------+
3    | Zend Engine, DCE - Dead Code Elimination                             |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | https://www.php.net/license/3_01.txt                                 |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Nikita Popov <nikic@php.net>                                |
16    |          Dmitry Stogov <dmitry@php.net>                              |
17    +----------------------------------------------------------------------+
18 */
19 
20 #include "Optimizer/zend_optimizer_internal.h"
21 #include "Optimizer/zend_inference.h"
22 #include "Optimizer/zend_ssa.h"
23 #include "Optimizer/zend_func_info.h"
24 #include "Optimizer/zend_call_graph.h"
25 #include "zend_bitset.h"
26 
27 /* This pass implements a form of dead code elimination (DCE). The algorithm optimistically assumes
28  * that all instructions and phis are dead. Instructions with immediate side-effects are then marked
29  * as live. We then recursively (using a worklist) propagate liveness to the instructions that def
30  * the used operands.
31  *
32  * Notes:
33  *  * This pass does not perform unreachable code elimination. This happens as part of the SCCP
34  *    pass.
35  *  * The DCE is performed without taking control-dependence into account, i.e. all conditional
36  *    branches are assumed to be live. It's possible to take control-dependence into account using
37  *    the DCE algorithm described by Cytron et al., however it requires the construction of a
38  *    postdominator tree and of postdominance frontiers, which does not seem worthwhile at this
39  *    point.
40  *  * We separate intrinsic side-effects from potential side-effects in the form of notices thrown
41  *    by the instruction (in case we want to make this configurable). See may_have_side_effects() and
42  *    zend_may_throw().
43  *  * We often cannot DCE assignments and unsets while guaranteeing that dtors run in the same
44  *    order. There is an optimization option to allow reordering of dtor effects.
45  *  * The algorithm is able to eliminate dead modifications of non-escaping arrays
46  *    and objects as well as dead arrays and objects allocations.
47  */
48 
49 typedef struct {
50 	zend_ssa *ssa;
51 	zend_op_array *op_array;
52 	zend_bitset instr_dead;
53 	zend_bitset phi_dead;
54 	zend_bitset instr_worklist;
55 	zend_bitset phi_worklist;
56 	zend_bitset phi_worklist_no_val;
57 	uint32_t instr_worklist_len;
58 	uint32_t phi_worklist_len;
59 	unsigned reorder_dtor_effects : 1;
60 } context;
61 
is_bad_mod(const zend_ssa * ssa,int use,int def)62 static inline bool is_bad_mod(const zend_ssa *ssa, int use, int def) {
63 	if (def < 0) {
64 		/* This modification is not tracked by SSA, assume the worst */
65 		return 1;
66 	}
67 	if (ssa->var_info[use].type & MAY_BE_REF) {
68 		/* Modification of reference may have side-effect */
69 		return 1;
70 	}
71 	return 0;
72 }
73 
may_have_side_effects(zend_op_array * op_array,zend_ssa * ssa,const zend_op * opline,const zend_ssa_op * ssa_op,bool reorder_dtor_effects)74 static inline bool may_have_side_effects(
75 		zend_op_array *op_array, zend_ssa *ssa,
76 		const zend_op *opline, const zend_ssa_op *ssa_op,
77 		bool reorder_dtor_effects) {
78 	switch (opline->opcode) {
79 		case ZEND_NOP:
80 		case ZEND_IS_IDENTICAL:
81 		case ZEND_IS_NOT_IDENTICAL:
82 		case ZEND_QM_ASSIGN:
83 		case ZEND_FREE:
84 		case ZEND_FE_FREE:
85 		case ZEND_TYPE_CHECK:
86 		case ZEND_DEFINED:
87 		case ZEND_ADD:
88 		case ZEND_SUB:
89 		case ZEND_MUL:
90 		case ZEND_POW:
91 		case ZEND_BW_OR:
92 		case ZEND_BW_AND:
93 		case ZEND_BW_XOR:
94 		case ZEND_CONCAT:
95 		case ZEND_FAST_CONCAT:
96 		case ZEND_DIV:
97 		case ZEND_MOD:
98 		case ZEND_BOOL_XOR:
99 		case ZEND_BOOL:
100 		case ZEND_BOOL_NOT:
101 		case ZEND_BW_NOT:
102 		case ZEND_SL:
103 		case ZEND_SR:
104 		case ZEND_IS_EQUAL:
105 		case ZEND_IS_NOT_EQUAL:
106 		case ZEND_IS_SMALLER:
107 		case ZEND_IS_SMALLER_OR_EQUAL:
108 		case ZEND_CASE:
109 		case ZEND_CASE_STRICT:
110 		case ZEND_CAST:
111 		case ZEND_ROPE_INIT:
112 		case ZEND_ROPE_ADD:
113 		case ZEND_INIT_ARRAY:
114 		case ZEND_SPACESHIP:
115 		case ZEND_STRLEN:
116 		case ZEND_COUNT:
117 		case ZEND_GET_TYPE:
118 		case ZEND_ISSET_ISEMPTY_THIS:
119 		case ZEND_ISSET_ISEMPTY_DIM_OBJ:
120 		case ZEND_FETCH_DIM_IS:
121 		case ZEND_ISSET_ISEMPTY_CV:
122 		case ZEND_ISSET_ISEMPTY_VAR:
123 		case ZEND_FETCH_IS:
124 		case ZEND_IN_ARRAY:
125 		case ZEND_FUNC_NUM_ARGS:
126 		case ZEND_FUNC_GET_ARGS:
127 		case ZEND_ARRAY_KEY_EXISTS:
128 			/* No side effects */
129 			return 0;
130 		case ZEND_ADD_ARRAY_ELEMENT:
131 			/* TODO: We can't free two vars. Keep instruction alive. <?php [0, "$a" => "$b"]; */
132 			if ((opline->op1_type & (IS_VAR|IS_TMP_VAR)) && (opline->op2_type & (IS_VAR|IS_TMP_VAR))) {
133 				return 1;
134 			}
135 			return 0;
136 		case ZEND_ROPE_END:
137 			/* TODO: Rope dce optimization, see #76446 */
138 			return 1;
139 		case ZEND_JMP:
140 		case ZEND_JMPZ:
141 		case ZEND_JMPNZ:
142 		case ZEND_JMPZ_EX:
143 		case ZEND_JMPNZ_EX:
144 		case ZEND_JMP_SET:
145 		case ZEND_COALESCE:
146 		case ZEND_ASSERT_CHECK:
147 		case ZEND_JMP_NULL:
148 		case ZEND_BIND_INIT_STATIC_OR_JMP:
149 		case ZEND_JMP_FRAMELESS:
150 			/* For our purposes a jumps and branches are side effects. */
151 			return 1;
152 		case ZEND_BEGIN_SILENCE:
153 		case ZEND_END_SILENCE:
154 		case ZEND_ECHO:
155 		case ZEND_INCLUDE_OR_EVAL:
156 		case ZEND_THROW:
157 		case ZEND_MATCH_ERROR:
158 		case ZEND_EXT_STMT:
159 		case ZEND_EXT_FCALL_BEGIN:
160 		case ZEND_EXT_FCALL_END:
161 		case ZEND_TICKS:
162 		case ZEND_YIELD:
163 		case ZEND_YIELD_FROM:
164 		case ZEND_VERIFY_NEVER_TYPE:
165 			/* Intrinsic side effects */
166 			return 1;
167 		case ZEND_DO_FCALL:
168 		case ZEND_DO_FCALL_BY_NAME:
169 		case ZEND_DO_ICALL:
170 		case ZEND_DO_UCALL:
171 		case ZEND_FRAMELESS_ICALL_0:
172 		case ZEND_FRAMELESS_ICALL_1:
173 		case ZEND_FRAMELESS_ICALL_2:
174 		case ZEND_FRAMELESS_ICALL_3:
175 			/* For now assume all calls have side effects */
176 			return 1;
177 		case ZEND_RECV:
178 		case ZEND_RECV_INIT:
179 			/* Even though RECV_INIT can be side-effect free, these cannot be simply dropped
180 			 * due to the prologue skipping code. */
181 			return 1;
182 		case ZEND_ASSIGN_REF:
183 			return 1;
184 		case ZEND_ASSIGN:
185 		{
186 			if (is_bad_mod(ssa, ssa_op->op1_use, ssa_op->op1_def)) {
187 				return 1;
188 			}
189 			if (!reorder_dtor_effects) {
190 				if (opline->op2_type != IS_CONST
191 					&& (OP2_INFO() & MAY_HAVE_DTOR)
192 					&& ssa->vars[ssa_op->op2_use].escape_state != ESCAPE_STATE_NO_ESCAPE) {
193 					/* DCE might shorten lifetime */
194 					return 1;
195 				}
196 			}
197 			return 0;
198 		}
199 		case ZEND_UNSET_VAR:
200 			return 1;
201 		case ZEND_UNSET_CV:
202 		{
203 			uint32_t t1 = OP1_INFO();
204 			if (t1 & MAY_BE_REF) {
205 				/* We don't consider uses as the LHS of an assignment as real uses during DCE, so
206 				 * an unset may be considered dead even if there is a later assignment to the
207 				 * variable. Removing the unset in this case would not be correct if the variable
208 				 * is a reference, because unset breaks references. */
209 				return 1;
210 			}
211 			return 0;
212 		}
213 		case ZEND_PRE_INC:
214 		case ZEND_POST_INC:
215 		case ZEND_PRE_DEC:
216 		case ZEND_POST_DEC:
217 			return is_bad_mod(ssa, ssa_op->op1_use, ssa_op->op1_def);
218 		case ZEND_ASSIGN_OP:
219 			return is_bad_mod(ssa, ssa_op->op1_use, ssa_op->op1_def)
220 				|| ssa->vars[ssa_op->op1_def].escape_state != ESCAPE_STATE_NO_ESCAPE;
221 		case ZEND_ASSIGN_DIM:
222 		case ZEND_ASSIGN_OBJ:
223 			if (is_bad_mod(ssa, ssa_op->op1_use, ssa_op->op1_def)
224 				|| ssa->vars[ssa_op->op1_def].escape_state != ESCAPE_STATE_NO_ESCAPE) {
225 				return 1;
226 			}
227 			if (!reorder_dtor_effects) {
228 				opline++;
229 				ssa_op++;
230 				if (opline->op1_type != IS_CONST
231 					&& (OP1_INFO() & MAY_HAVE_DTOR)) {
232 					/* DCE might shorten lifetime */
233 					return 1;
234 				}
235 			}
236 			return 0;
237 		case ZEND_PRE_INC_OBJ:
238 		case ZEND_PRE_DEC_OBJ:
239 		case ZEND_POST_INC_OBJ:
240 		case ZEND_POST_DEC_OBJ:
241 			if (is_bad_mod(ssa, ssa_op->op1_use, ssa_op->op1_def)
242 				|| ssa->vars[ssa_op->op1_def].escape_state != ESCAPE_STATE_NO_ESCAPE) {
243 				return 1;
244 			}
245 			return 0;
246 		case ZEND_BIND_STATIC:
247 			if (op_array->static_variables) {
248 				/* Implicit and Explicit bind static is effectively prologue of closure so
249 				   report it has side effects like RECV, RECV_INIT; This allows us to
250 				   reflect on the closure and discover used variable at runtime */
251 				if ((opline->extended_value & (ZEND_BIND_IMPLICIT|ZEND_BIND_EXPLICIT))) {
252 					return 1;
253 				}
254 				/* Modifies static variables which are observable through reflection */
255 				if ((opline->extended_value & ZEND_BIND_REF) && opline->op2_type != IS_UNUSED) {
256 					return 1;
257 				}
258 			}
259 			return 0;
260 		case ZEND_CHECK_VAR:
261 			return (OP1_INFO() & MAY_BE_UNDEF) != 0;
262 		case ZEND_FE_RESET_R:
263 		case ZEND_FE_RESET_RW:
264 			/* Model as not having side-effects -- let the side-effect be introduced by
265 			 * FE_FETCH if the array is not known to be non-empty. */
266 			return (OP1_INFO() & MAY_BE_ANY) != MAY_BE_ARRAY;
267 		default:
268 			/* For everything we didn't handle, assume a side-effect */
269 			return 1;
270 	}
271 }
272 
add_to_worklists(context * ctx,int var_num,int check)273 static zend_always_inline void add_to_worklists(context *ctx, int var_num, int check) {
274 	zend_ssa_var *var = &ctx->ssa->vars[var_num];
275 	if (var->definition >= 0) {
276 		if (!check || zend_bitset_in(ctx->instr_dead, var->definition)) {
277 			zend_bitset_incl(ctx->instr_worklist, var->definition);
278 		}
279 	} else if (var->definition_phi) {
280 		if (!check || zend_bitset_in(ctx->phi_dead, var_num)) {
281 			zend_bitset_incl(ctx->phi_worklist, var_num);
282 		}
283 	}
284 }
285 
add_to_phi_worklist_no_val(context * ctx,int var_num)286 static inline void add_to_phi_worklist_no_val(context *ctx, int var_num) {
287 	zend_ssa_var *var = &ctx->ssa->vars[var_num];
288 	if (var->definition_phi && zend_bitset_in(ctx->phi_dead, var_num)) {
289 		zend_bitset_incl(ctx->phi_worklist_no_val, var_num);
290 	}
291 }
292 
add_operands_to_worklists(context * ctx,zend_op * opline,zend_ssa_op * ssa_op,zend_ssa * ssa,int check)293 static zend_always_inline void add_operands_to_worklists(context *ctx, zend_op *opline, zend_ssa_op *ssa_op, zend_ssa *ssa, int check) {
294 	if (ssa_op->result_use >= 0) {
295 		add_to_worklists(ctx, ssa_op->result_use, check);
296 	}
297 	if (ssa_op->op1_use >= 0) {
298 		if (!zend_ssa_is_no_val_use(opline, ssa_op, ssa_op->op1_use)
299 		 || (opline->opcode == ZEND_ASSIGN
300 		  && (ssa->var_info[ssa_op->op1_use].type & MAY_BE_REF) != 0)) {
301 			add_to_worklists(ctx, ssa_op->op1_use, check);
302 		} else {
303 			add_to_phi_worklist_no_val(ctx, ssa_op->op1_use);
304 		}
305 	}
306 	if (ssa_op->op2_use >= 0) {
307 		if (!zend_ssa_is_no_val_use(opline, ssa_op, ssa_op->op2_use)
308 		 || (opline->opcode == ZEND_FE_FETCH_R
309 		  && (ssa->var_info[ssa_op->op2_use].type & MAY_BE_REF) != 0)) {
310 			add_to_worklists(ctx, ssa_op->op2_use, check);
311 		} else {
312 			add_to_phi_worklist_no_val(ctx, ssa_op->op2_use);
313 		}
314 	}
315 }
316 
add_phi_sources_to_worklists(context * ctx,zend_ssa_phi * phi,int check)317 static zend_always_inline void add_phi_sources_to_worklists(context *ctx, zend_ssa_phi *phi, int check) {
318 	zend_ssa *ssa = ctx->ssa;
319 	int source;
320 	FOREACH_PHI_SOURCE(phi, source) {
321 		add_to_worklists(ctx, source, check);
322 	} FOREACH_PHI_SOURCE_END();
323 }
324 
is_var_dead(context * ctx,int var_num)325 static inline bool is_var_dead(context *ctx, int var_num) {
326 	zend_ssa_var *var = &ctx->ssa->vars[var_num];
327 	if (var->definition_phi) {
328 		return zend_bitset_in(ctx->phi_dead, var_num);
329 	} else if (var->definition >= 0) {
330 		return zend_bitset_in(ctx->instr_dead, var->definition);
331 	} else {
332 		/* Variable has no definition, so either the definition has already been removed (var is
333 		 * dead) or this is one of the implicit variables at the start of the function (for our
334 		 * purposes live) */
335 		return var_num >= ctx->op_array->last_var;
336 	}
337 }
338 
339 // Sometimes we can mark the var as EXT_UNUSED
try_remove_var_def(context * ctx,int free_var,int use_chain,zend_op * opline)340 static bool try_remove_var_def(context *ctx, int free_var, int use_chain, zend_op *opline) {
341 	if (use_chain >= 0) {
342 		return 0;
343 	}
344 	zend_ssa_var *var = &ctx->ssa->vars[free_var];
345 	int def = var->definition;
346 
347 	if (def >= 0) {
348 		zend_ssa_op *def_op = &ctx->ssa->ops[def];
349 
350 		if (def_op->result_def == free_var
351 				&& var->phi_use_chain == NULL
352 				&& var->use_chain == (opline - ctx->op_array->opcodes)) {
353 			zend_op *def_opline = &ctx->op_array->opcodes[def];
354 
355 			switch (def_opline->opcode) {
356 				case ZEND_ASSIGN:
357 				case ZEND_ASSIGN_REF:
358 				case ZEND_ASSIGN_DIM:
359 				case ZEND_ASSIGN_OBJ:
360 				case ZEND_ASSIGN_OBJ_REF:
361 				case ZEND_ASSIGN_STATIC_PROP:
362 				case ZEND_ASSIGN_STATIC_PROP_REF:
363 				case ZEND_ASSIGN_OP:
364 				case ZEND_ASSIGN_DIM_OP:
365 				case ZEND_ASSIGN_OBJ_OP:
366 				case ZEND_ASSIGN_STATIC_PROP_OP:
367 				case ZEND_PRE_INC:
368 				case ZEND_PRE_DEC:
369 				case ZEND_PRE_INC_OBJ:
370 				case ZEND_PRE_DEC_OBJ:
371 				case ZEND_DO_ICALL:
372 				case ZEND_DO_UCALL:
373 				case ZEND_DO_FCALL_BY_NAME:
374 				case ZEND_DO_FCALL:
375 				case ZEND_INCLUDE_OR_EVAL:
376 				case ZEND_YIELD:
377 				case ZEND_YIELD_FROM:
378 				case ZEND_ASSERT_CHECK:
379 					def_opline->result_type = IS_UNUSED;
380 					def_opline->result.var = 0;
381 					def_op->result_def = -1;
382 					var->definition = -1;
383 					return 1;
384 				default:
385 					break;
386 			}
387 		}
388 	}
389 	return 0;
390 }
391 
may_be_refcounted(uint32_t type)392 static zend_always_inline bool may_be_refcounted(uint32_t type) {
393 	return (type & (MAY_BE_STRING|MAY_BE_ARRAY|MAY_BE_OBJECT|MAY_BE_RESOURCE|MAY_BE_REF)) != 0;
394 }
395 
is_free_of_live_var(context * ctx,zend_op * opline,zend_ssa_op * ssa_op)396 static inline bool is_free_of_live_var(context *ctx, zend_op *opline, zend_ssa_op *ssa_op) {
397 	switch (opline->opcode) {
398 		case ZEND_FREE:
399 			/* It is always safe to remove FREEs of non-refcounted values, even if they are live. */
400 			if ((ctx->ssa->var_info[ssa_op->op1_use].type & (MAY_BE_REF|MAY_BE_ANY|MAY_BE_UNDEF)) != 0
401 			 && !may_be_refcounted(ctx->ssa->var_info[ssa_op->op1_use].type)) {
402 				return 0;
403 			}
404 			ZEND_FALLTHROUGH;
405 		case ZEND_FE_FREE:
406 			return !is_var_dead(ctx, ssa_op->op1_use);
407 		default:
408 			return 0;
409 	}
410 }
411 
412 /* Returns whether the instruction has been DCEd */
dce_instr(context * ctx,zend_op * opline,zend_ssa_op * ssa_op)413 static bool dce_instr(context *ctx, zend_op *opline, zend_ssa_op *ssa_op) {
414 	zend_ssa *ssa = ctx->ssa;
415 	int free_var = -1;
416 	uint8_t free_var_type;
417 
418 	if (opline->opcode == ZEND_NOP) {
419 		return 0;
420 	}
421 
422 	/* We mark FREEs as dead, but they're only really dead if the destroyed var is dead */
423 	if (is_free_of_live_var(ctx, opline, ssa_op)) {
424 		return 0;
425 	}
426 
427 	if ((opline->op1_type & (IS_VAR|IS_TMP_VAR))&& !is_var_dead(ctx, ssa_op->op1_use)) {
428 		if (!try_remove_var_def(ctx, ssa_op->op1_use, ssa_op->op1_use_chain, opline)) {
429 			if (may_be_refcounted(ssa->var_info[ssa_op->op1_use].type)
430 					&& opline->opcode != ZEND_CASE && opline->opcode != ZEND_CASE_STRICT) {
431 				free_var = ssa_op->op1_use;
432 				free_var_type = opline->op1_type;
433 			}
434 		}
435 	}
436 	if ((opline->op2_type & (IS_VAR|IS_TMP_VAR)) && !is_var_dead(ctx, ssa_op->op2_use)) {
437 		if (!try_remove_var_def(ctx, ssa_op->op2_use, ssa_op->op2_use_chain, opline)) {
438 			if (may_be_refcounted(ssa->var_info[ssa_op->op2_use].type)) {
439 				if (free_var >= 0) {
440 					// TODO: We can't free two vars. Keep instruction alive.
441 					zend_bitset_excl(ctx->instr_dead, opline - ctx->op_array->opcodes);
442 					return 0;
443 				}
444 				free_var = ssa_op->op2_use;
445 				free_var_type = opline->op2_type;
446 			}
447 		}
448 	}
449 
450 	zend_ssa_rename_defs_of_instr(ctx->ssa, ssa_op);
451 	zend_ssa_remove_instr(ctx->ssa, opline, ssa_op);
452 
453 	if (free_var >= 0) {
454 		opline->opcode = ZEND_FREE;
455 		opline->op1.var = EX_NUM_TO_VAR(ssa->vars[free_var].var);
456 		opline->op1_type = free_var_type;
457 
458 		ssa_op->op1_use = free_var;
459 		ssa_op->op1_use_chain = ssa->vars[free_var].use_chain;
460 		ssa->vars[free_var].use_chain = ssa_op - ssa->ops;
461 		return 0;
462 	}
463 	return 1;
464 }
465 
get_common_phi_source(zend_ssa * ssa,zend_ssa_phi * phi)466 static inline int get_common_phi_source(zend_ssa *ssa, zend_ssa_phi *phi) {
467 	int common_source = -1;
468 	int source;
469 	FOREACH_PHI_SOURCE(phi, source) {
470 		if (source == phi->ssa_var) {
471 			continue;
472 		}
473 		if (common_source == -1) {
474 			common_source = source;
475 		} else if (common_source != source) {
476 			return -1;
477 		}
478 	} FOREACH_PHI_SOURCE_END();
479 
480 	/* If all sources are phi->ssa_var this phi must be in an unreachable cycle.
481 	 * We can't easily drop the phi in that case, as we don't have something to replace it with.
482 	 * Ideally SCCP would eliminate the whole cycle. */
483 	return common_source;
484 }
485 
try_remove_trivial_phi(context * ctx,zend_ssa_phi * phi)486 static void try_remove_trivial_phi(context *ctx, zend_ssa_phi *phi) {
487 	zend_ssa *ssa = ctx->ssa;
488 	if (phi->pi < 0) {
489 		/* Phi assignment with identical source operands */
490 		int common_source = get_common_phi_source(ssa, phi);
491 		if (common_source >= 0) {
492 			zend_ssa_rename_var_uses(ssa, phi->ssa_var, common_source, 1);
493 			zend_ssa_remove_phi(ssa, phi);
494 		}
495 	} else {
496 		/* Pi assignment that is only used in Phi/Pi assignments */
497 		// TODO What if we want to rerun type inference after DCE? Maybe separate this?
498 		/*ZEND_ASSERT(phi->sources[0] != -1);
499 		if (ssa->vars[phi->ssa_var].use_chain < 0) {
500 			zend_ssa_rename_var_uses_keep_types(ssa, phi->ssa_var, phi->sources[0], 1);
501 			zend_ssa_remove_phi(ssa, phi);
502 		}*/
503 	}
504 }
505 
may_break_varargs(const zend_op_array * op_array,const zend_ssa * ssa,const zend_ssa_op * ssa_op)506 static inline bool may_break_varargs(const zend_op_array *op_array, const zend_ssa *ssa, const zend_ssa_op *ssa_op) {
507 	if (ssa_op->op1_def >= 0
508 			&& ssa->vars[ssa_op->op1_def].var < op_array->num_args) {
509 		return 1;
510 	}
511 	if (ssa_op->op2_def >= 0
512 			&& ssa->vars[ssa_op->op2_def].var < op_array->num_args) {
513 		return 1;
514 	}
515 	if (ssa_op->result_def >= 0
516 			&& ssa->vars[ssa_op->result_def].var < op_array->num_args) {
517 		return 1;
518 	}
519 	return 0;
520 }
521 
may_throw_dce_exception(const zend_op * opline)522 static inline bool may_throw_dce_exception(const zend_op *opline) {
523 	return opline->opcode == ZEND_ADD_ARRAY_ELEMENT && opline->op2_type == IS_UNUSED;
524 }
525 
dce_optimize_op_array(zend_op_array * op_array,zend_optimizer_ctx * optimizer_ctx,zend_ssa * ssa,bool reorder_dtor_effects)526 int dce_optimize_op_array(zend_op_array *op_array, zend_optimizer_ctx *optimizer_ctx, zend_ssa *ssa, bool reorder_dtor_effects) {
527 	int i;
528 	zend_ssa_phi *phi;
529 	int removed_ops = 0;
530 
531 	/* DCE of CV operations that changes arguments may affect vararg functions. */
532 	bool has_varargs = (ssa->cfg.flags & ZEND_FUNC_VARARG) != 0;
533 
534 	context ctx;
535 	ctx.ssa = ssa;
536 	ctx.op_array = op_array;
537 	ctx.reorder_dtor_effects = reorder_dtor_effects;
538 
539 	void *checkpoint = zend_arena_checkpoint(optimizer_ctx->arena);
540 	/* We have no dedicated phi vector, so we use the whole ssa var vector instead */
541 	ctx.instr_worklist_len = zend_bitset_len(op_array->last);
542 	ctx.instr_worklist = zend_arena_calloc(&optimizer_ctx->arena, ctx.instr_worklist_len, sizeof(zend_ulong));
543 	ctx.phi_worklist_len = zend_bitset_len(ssa->vars_count);
544 	ctx.phi_worklist = zend_arena_calloc(&optimizer_ctx->arena, ctx.phi_worklist_len, sizeof(zend_ulong));
545 	ctx.phi_worklist_no_val = zend_arena_calloc(&optimizer_ctx->arena, ctx.phi_worklist_len, sizeof(zend_ulong));
546 
547 	/* Optimistically assume all instructions and phis to be dead */
548 	ctx.instr_dead = zend_arena_calloc(&optimizer_ctx->arena, ctx.instr_worklist_len, sizeof(zend_ulong));
549 	ctx.phi_dead = zend_arena_alloc(&optimizer_ctx->arena, ctx.phi_worklist_len * sizeof(zend_ulong));
550 	memset(ctx.phi_dead, 0xff, sizeof(zend_ulong) * ctx.phi_worklist_len);
551 
552 	/* Mark non-CV phis as live. Even if the result is unused, we generally cannot remove one
553 	 * of the producing instructions, as it combines producing the result with control flow.
554 	 * This can be made more precise if there are any cases where this is not the case. */
555 	FOREACH_PHI(phi) {
556 		if (phi->var >= op_array->last_var
557 				&& may_be_refcounted(ssa->var_info[phi->ssa_var].type)) {
558 			zend_bitset_excl(ctx.phi_dead, phi->ssa_var);
559 			add_phi_sources_to_worklists(&ctx, phi, 0);
560 		}
561 	} FOREACH_PHI_END();
562 
563 	/* Mark reachable instruction without side effects as dead */
564 	int b = ssa->cfg.blocks_count;
565 	while (b > 0) {
566 		int	op_data = -1;
567 
568 		b--;
569 		zend_basic_block *block = &ssa->cfg.blocks[b];
570 		if (!(block->flags & ZEND_BB_REACHABLE)) {
571 			continue;
572 		}
573 		i = block->start + block->len;
574 		while (i > block->start) {
575 			i--;
576 
577 			if (op_array->opcodes[i].opcode == ZEND_OP_DATA) {
578 				op_data = i;
579 				continue;
580 			}
581 
582 			if (zend_bitset_in(ctx.instr_worklist, i)) {
583 				zend_bitset_excl(ctx.instr_worklist, i);
584 				add_operands_to_worklists(&ctx, &op_array->opcodes[i], &ssa->ops[i], ssa, 0);
585 				if (op_data >= 0) {
586 					add_operands_to_worklists(&ctx, &op_array->opcodes[op_data], &ssa->ops[op_data], ssa, 0);
587 				}
588 			} else if (may_have_side_effects(op_array, ssa, &op_array->opcodes[i], &ssa->ops[i], ctx.reorder_dtor_effects)
589 					|| (zend_may_throw(&op_array->opcodes[i], &ssa->ops[i], op_array, ssa)
590 						&& !may_throw_dce_exception(&op_array->opcodes[i]))
591 					|| (has_varargs && may_break_varargs(op_array, ssa, &ssa->ops[i]))) {
592 				if (op_array->opcodes[i].opcode == ZEND_NEW
593 						&& op_array->opcodes[i+1].opcode == ZEND_DO_FCALL
594 						&& ssa->ops[i].result_def >= 0
595 						&& ssa->vars[ssa->ops[i].result_def].escape_state == ESCAPE_STATE_NO_ESCAPE) {
596 					zend_bitset_incl(ctx.instr_dead, i);
597 					zend_bitset_incl(ctx.instr_dead, i+1);
598 				} else {
599 					add_operands_to_worklists(&ctx, &op_array->opcodes[i], &ssa->ops[i], ssa, 0);
600 					if (op_data >= 0) {
601 						add_operands_to_worklists(&ctx, &op_array->opcodes[op_data], &ssa->ops[op_data], ssa, 0);
602 					}
603 				}
604 			} else {
605 				zend_bitset_incl(ctx.instr_dead, i);
606 				if (op_data >= 0) {
607 					zend_bitset_incl(ctx.instr_dead, op_data);
608 				}
609 			}
610 			op_data = -1;
611 		}
612 	}
613 
614 	/* Propagate liveness backwards to all definitions of used vars */
615 	while (!zend_bitset_empty(ctx.instr_worklist, ctx.instr_worklist_len)
616 			|| !zend_bitset_empty(ctx.phi_worklist, ctx.phi_worklist_len)) {
617 		while ((i = zend_bitset_pop_first(ctx.instr_worklist, ctx.instr_worklist_len)) >= 0) {
618 			zend_bitset_excl(ctx.instr_dead, i);
619 			add_operands_to_worklists(&ctx, &op_array->opcodes[i], &ssa->ops[i], ssa, 1);
620 			if (i < op_array->last
621 			 && (op_array->opcodes[i+1].opcode == ZEND_OP_DATA
622 			  || (op_array->opcodes[i].opcode == ZEND_NEW
623 			   && op_array->opcodes[i+1].opcode == ZEND_DO_FCALL))) {
624 				zend_bitset_excl(ctx.instr_dead, i+1);
625 				add_operands_to_worklists(&ctx, &op_array->opcodes[i+1], &ssa->ops[i+1], ssa, 1);
626 			}
627 		}
628 		while ((i = zend_bitset_pop_first(ctx.phi_worklist, ctx.phi_worklist_len)) >= 0) {
629 			zend_bitset_excl(ctx.phi_dead, i);
630 			zend_bitset_excl(ctx.phi_worklist_no_val, i);
631 			add_phi_sources_to_worklists(&ctx, ssa->vars[i].definition_phi, 1);
632 		}
633 	}
634 
635 	/* Eliminate dead instructions */
636 	ZEND_BITSET_FOREACH(ctx.instr_dead, ctx.instr_worklist_len, i) {
637 		removed_ops += dce_instr(&ctx, &op_array->opcodes[i], &ssa->ops[i]);
638 	} ZEND_BITSET_FOREACH_END();
639 
640 	/* Improper uses don't count as "uses" for the purpose of instruction elimination,
641 	 * but we have to retain phis defining them.
642 	 * Propagate this information backwards, marking any phi with an improperly used
643 	 * target as non-dead. */
644 	while ((i = zend_bitset_pop_first(ctx.phi_worklist_no_val, ctx.phi_worklist_len)) >= 0) {
645 		zend_ssa_phi *phi = ssa->vars[i].definition_phi;
646 		int source;
647 		zend_bitset_excl(ctx.phi_dead, i);
648 		FOREACH_PHI_SOURCE(phi, source) {
649 			add_to_phi_worklist_no_val(&ctx, source);
650 		} FOREACH_PHI_SOURCE_END();
651 	}
652 
653 	/* Now collect the actually dead phis */
654 	FOREACH_PHI(phi) {
655 		if (zend_bitset_in(ctx.phi_dead, phi->ssa_var)) {
656 			zend_ssa_remove_uses_of_var(ssa, phi->ssa_var);
657 			zend_ssa_remove_phi(ssa, phi);
658 		} else {
659 			/* Remove trivial phis (phis with identical source operands) */
660 			try_remove_trivial_phi(&ctx, phi);
661 		}
662 	} FOREACH_PHI_END();
663 
664 	zend_arena_release(&optimizer_ctx->arena, checkpoint);
665 
666 	return removed_ops;
667 }
668