scalar_replace.c 20.2 KB
Newer Older
Christian Würdig's avatar
Christian Würdig committed
1
/*
Michael Beck's avatar
Michael Beck committed
2
 * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
Christian Würdig's avatar
Christian Würdig committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 *
 * This file is part of libFirm.
 *
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file LICENSE.GPL included in the
 * packaging of this file.
 *
 * Licensees holding valid libFirm Professional Edition licenses may use
 * this file in accordance with the libFirm Commercial License.
 * Agreement provided with the Software.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

Michael Beck's avatar
Michael Beck committed
20
21
22
23
24
/**
 * @file
 * @brief   Scalar replacement of compounds.
 * @author  Beyhan Veliev, Michael Beck
 * @version $Id$
Michael Beck's avatar
Michael Beck committed
25
 */
Michael Beck's avatar
Michael Beck committed
26
27
#include "config.h"

Michael Beck's avatar
Michael Beck committed
28
29
#include <string.h>

30
#include "iroptimize.h"
31
#include "scalar_replace.h"
Michael Beck's avatar
Michael Beck committed
32
33
34
35
36
37
38
39
40
41
42
#include "irflag_t.h"
#include "irouts.h"
#include "set.h"
#include "pset.h"
#include "array.h"
#include "tv.h"
#include "ircons_t.h"
#include "hashptr.h"
#include "irgwalk.h"
#include "irgmod.h"
#include "irnode_t.h"
43
#include "irtools.h"
44
#include "xmalloc.h"
45
46
#include "debug.h"
#include "error.h"
Michael Beck's avatar
Michael Beck committed
47

48
49
#define SET_VNUM(node, vnum) set_irn_link(node, INT_TO_PTR(vnum))
#define GET_VNUM(node)       (unsigned)PTR_TO_INT(get_irn_link(node))
Michael Beck's avatar
Michael Beck committed
50

51
/**
Michael Beck's avatar
Michael Beck committed
52
 * A path element entry: it is either an entity
Michael Beck's avatar
Michael Beck committed
53
 * or a tarval, because we evaluate only constant array
54
55
56
 * accesses like a.b.c[8].d
 */
typedef union {
Michael Beck's avatar
Michael Beck committed
57
58
	ir_entity *ent;
	tarval *tv;
59
} path_elem_t;
Michael Beck's avatar
Michael Beck committed
60

61
62
/**
 * An access path, used to assign value numbers
63
 * to variables that will be scalar replaced.
64
65
 */
typedef struct _path_t {
Michael Beck's avatar
Michael Beck committed
66
67
68
	unsigned    vnum;      /**< The value number. */
	unsigned    path_len;  /**< The length of the access path. */
	path_elem_t path[1];   /**< The path. */
69
70
} path_t;

71
/** The size of a path in bytes. */
Michael Beck's avatar
Michael Beck committed
72
73
#define PATH_SIZE(p)  (sizeof(*(p)) + sizeof((p)->path[0]) * ((p)->path_len - 1))

Michael Beck's avatar
Michael Beck committed
74
typedef struct _scalars_t {
Michael Beck's avatar
Michael Beck committed
75
76
	ir_entity *ent;              /**< A entity for scalar replacement. */
	ir_type *ent_owner;          /**< The owner of this entity. */
77
78
} scalars_t;

79
DEBUG_ONLY(static firm_dbg_module_t *dbg;)
80
81

/**
Michael Beck's avatar
Michael Beck committed
82
83
84
 * Compare two pathes.
 *
 * @return 0 if they are identically
85
 */
Michael Beck's avatar
Michael Beck committed
86
87
88
89
static int path_cmp(const void *elt, const void *key, size_t size) {
	const path_t *p1 = elt;
	const path_t *p2 = key;
	(void) size;
90

Michael Beck's avatar
Michael Beck committed
91
92
	/* we can use memcmp here, because identical tarvals should have identical addresses */
	return memcmp(p1->path, p2->path, p1->path_len * sizeof(p1->path[0]));
93
94
95
}

/**
Michael Beck's avatar
Michael Beck committed
96
97
98
 * Compare two elements of the scalars_t set.
 *
 * @return 0 if they are identically
99
 */
Michael Beck's avatar
Michael Beck committed
100
101
102
103
static int ent_cmp(const void *elt, const void *key, size_t size) {
	const scalars_t *c1 = elt;
	const scalars_t *c2 = key;
	(void) size;
104

Michael Beck's avatar
Michael Beck committed
105
	return c1->ent != c2->ent;
106
107
108
}

/**
Michael Beck's avatar
Michael Beck committed
109
 * Calculate a hash value for a path.
110
 */
Michael Beck's avatar
Michael Beck committed
111
112
113
static unsigned path_hash(const path_t *path) {
	unsigned hash = 0;
	unsigned i;
114

Michael Beck's avatar
Michael Beck committed
115
116
	for (i = 0; i < path->path_len; ++i)
		hash ^= (unsigned)PTR_TO_INT(path->path[i].ent);
117

Michael Beck's avatar
Michael Beck committed
118
	return hash >> 4;
119
120
121
}

/**
Michael Beck's avatar
Michael Beck committed
122
 * Returns non-zero, if all indeces of a Sel node are constants.
123
 *
Michael Beck's avatar
Michael Beck committed
124
 * @param sel  the Sel node that will be checked
125
126
 */
static int is_const_sel(ir_node *sel) {
Michael Beck's avatar
Michael Beck committed
127
	int i, n = get_Sel_n_indexs(sel);
128

Michael Beck's avatar
Michael Beck committed
129
130
	for (i = 0; i < n; ++i) {
		ir_node *idx = get_Sel_index(sel, i);
131

132
		if (!is_Const(idx))
Michael Beck's avatar
Michael Beck committed
133
134
135
			return 0;
	}
	return 1;
136
137
}

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/**
 * Check the mode of a Load/Store with the mode of the entity
 * that is accessed.
 * If the mode of the entity and the Load/Store mode do not match, we
 * have the bad reinterpret case:
 *
 * int i;
 * char b = *(char *)&i;
 *
 * We do NOT count this as one value and return address_taken
 * in that case.
 * However, we support an often used case. If the mode is two-complement
 * we allow casts between signed/unsigned.
 *
 * @param mode     the mode of the Load/Store
 * @param ent_mode the mode of the accessed entity
 */
static int check_load_store_mode(ir_mode *mode, ir_mode *ent_mode) {
Michael Beck's avatar
Michael Beck committed
156
157
158
159
160
161
162
163
164
	if (ent_mode != mode) {
		if (ent_mode == NULL ||
		    get_mode_size_bits(ent_mode) != get_mode_size_bits(mode) ||
		    get_mode_sort(ent_mode) != get_mode_sort(mode) ||
		    get_mode_arithmetic(ent_mode) != irma_twos_complement ||
		    get_mode_arithmetic(mode) != irma_twos_complement)
			return 0;
	}
	return 1;
165
166
}

Michael Beck's avatar
Michael Beck committed
167
/*
Michael Beck's avatar
Michael Beck committed
168
169
 * Returns non-zero, if the address of an entity
 * represented by a Sel node (or it's successor Sels) is taken.
170
 */
Michael Beck's avatar
Michael Beck committed
171
int is_address_taken(ir_node *sel)
172
{
173
174
175
	int       i, input_nr, k;
	ir_mode   *emode, *mode;
	ir_node   *value;
Michael Beck's avatar
Michael Beck committed
176
177
178
179
180
181
182
183
184
185
	ir_entity *ent;

	if (! is_const_sel(sel))
		return 1;

	for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
		ir_node *succ = get_irn_out(sel, i);

		switch (get_irn_opcode(succ)) {
		case iro_Load:
186
187
188
			/* do not remove volatile variables */
			if (get_Load_volatility(succ) == volatility_is_volatile)
				return 1;
Michael Beck's avatar
Michael Beck committed
189
190
191
192
193
194
195
196
197
198
199
200
201
			/* check if this load is not a hidden conversion */
			mode = get_Load_mode(succ);
			ent = get_Sel_entity(sel);
			emode = get_type_mode(get_entity_type(ent));
			if (! check_load_store_mode(mode, emode))
				return 1;
			break;

		case iro_Store:
			/* check that Sel is not the Store's value */
			value = get_Store_value(succ);
			if (value == sel)
				return 1;
202
203
204
			/* do not remove volatile variables */
			if (get_Store_volatility(succ) == volatility_is_volatile)
				return 1;
Michael Beck's avatar
Michael Beck committed
205
206
207
208
209
210
211
212
213
			/* check if this Store is not a hidden conversion */
			mode = get_irn_mode(value);
			ent = get_Sel_entity(sel);
			emode = get_type_mode(get_entity_type(ent));
			if (! check_load_store_mode(mode, emode))
				return 1;
			break;

		case iro_Sel: {
Michael Beck's avatar
Michael Beck committed
214
215
			int       res;
			ir_entity *entity = get_Sel_entity(succ);
216
217
218
219
			/* we can't handle unions correctly yet -> address taken */
			if (is_Union_type(get_entity_owner(entity)))
				return 1;

Michael Beck's avatar
Michael Beck committed
220
			/* Check the Sel successor of Sel */
Michael Beck's avatar
Michael Beck committed
221
			res = is_address_taken(succ);
Michael Beck's avatar
Michael Beck committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
			if (res)
				return 1;
			break;
		}

		case iro_Call:
			/* The address of an entity is given as a parameter.
			 * As long as we do not have analyses that can tell what
			 * is done with parameters, think is taken.
			 * One special case: If the Call type tells that it's a
			 * value parameter, the address is NOT taken.
			 */
			return 1;

236
237
238
239
240
241
242
		case iro_Id: {
			int res = is_address_taken(succ);
			if (res)
				return 1;
			break;
		}

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
		case iro_Tuple:
			/* Non-optimized Tuple, happens in inlining */
			for (input_nr = get_Tuple_n_preds(succ) - 1; input_nr >= 0; --input_nr) {
				ir_node *pred = get_Tuple_pred(succ, input_nr);

				if (pred == sel) {
					/* we found one input */
					for (k = get_irn_n_outs(succ) - 1; k >= 0; --k) {
						ir_node *proj = get_irn_out(succ, k);

						if (is_Proj(proj) && get_Proj_proj(proj) == input_nr) {
							int res = is_address_taken(proj);
							if (res)
								return 1;
						}
					}
				}
			}
			break;

Michael Beck's avatar
Michael Beck committed
263
264
265
266
267
268
		default:
			/* another op, the address is taken */
			return 1;
		}
	}
	return 0;
269
270
271
}

/**
Michael Beck's avatar
Michael Beck committed
272
 * Link all leave Sels with the entity.
273
274
275
276
 *
 * @param ent  the entity that will be scalar replaced
 * @param sel  a Sel node that selects some fields of this entity
 */
277
278
static int link_all_leave_sels(ir_entity *ent, ir_node *sel) {
	int i, is_leave = 1;
Michael Beck's avatar
Michael Beck committed
279

280
	for (i = get_irn_n_outs(sel) - 1; i >= 0; --i) {
Michael Beck's avatar
Michael Beck committed
281
282
283
		ir_node *succ = get_irn_out(sel, i);

		if (is_Sel(succ)) {
284
285
			/* the current leave has further Sel's, no leave */
			is_leave = 0;
Michael Beck's avatar
Michael Beck committed
286
			link_all_leave_sels(ent, succ);
287
288
		} else if (is_Id(succ)) {
			is_leave &= link_all_leave_sels(ent, succ);
Michael Beck's avatar
Michael Beck committed
289
290
291
		}
	}

292
293
294
	if (is_leave) {
		/* beware of Id's */
		sel = skip_Id(sel);
Michael Beck's avatar
Michael Beck committed
295
296

		/* we know we are at a leave, because this function is only
297
298
		 * called if the address is NOT taken, so sel's successor(s)
		 * must be Loads or Stores
Michael Beck's avatar
Michael Beck committed
299
300
301
302
		 */
		set_irn_link(sel, get_entity_link(ent));
		set_entity_link(ent, sel);
	}
303
	return is_leave;
304
305
}

Michael Beck's avatar
Michael Beck committed
306
/* we need a special address that serves as an address taken marker */
307
308
309
310
static char _x;
static void *ADDRESS_TAKEN = &_x;

/**
Michael Beck's avatar
Michael Beck committed
311
 * Find possible scalar replacements.
312
313
314
315
316
317
 *
 * @param irg  an IR graph
 *
 * This function finds variables on the (members of the) frame type
 * that can be scalar replaced, because their address is never taken.
 * If such a variable is found, it's entity link will hold a list of all
Michael Beck's avatar
Michael Beck committed
318
319
320
321
322
 * Sel nodes, that selects the atomic fields of this entity.
 * Otherwise, the link will be ADDRESS_TAKEN or NULL.
 *
 * @return  non-zero if at least one entity could be replaced
 *          potentially
323
 */
Michael Beck's avatar
Michael Beck committed
324
static int find_possible_replacements(ir_graph *irg) {
325
326
	ir_node *irg_frame;
	ir_type *frame_tp;
327
	int     i, j, k, static_link_arg;
328
	int     res = 0;
Michael Beck's avatar
Michael Beck committed
329
330
331
332

	/*
	 * First, clear the link field of all interesting entities.
	 */
333
334
335
336
	frame_tp = get_irg_frame_type(irg);
	for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
		ir_entity *ent = get_class_member(frame_tp, i);
		set_entity_link(ent, NULL);
Michael Beck's avatar
Michael Beck committed
337
338
	}

339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
	/* check for inner functions:
	 * FIXME: need a way to get the argument position for the static link */
	static_link_arg = 0;
	for (i = get_class_n_members(frame_tp) - 1; i >= 0; --i) {
		ir_entity *ent = get_class_member(frame_tp, i);
		if (is_method_entity(ent)) {
			ir_graph *inner_irg = get_entity_irg(ent);
			ir_node  *args;

			assure_irg_outs(inner_irg);
			args = get_irg_args(inner_irg);
			for (j = get_irn_n_outs(args) - 1; j >= 0; --j) {
				ir_node *arg = get_irn_out(args, j);

				if (get_Proj_proj(arg) == static_link_arg) {
					for (k = get_irn_n_outs(arg) - 1; k >= 0; --k) {
						ir_node *succ = get_irn_out(arg, k);

						if (is_Sel(succ)) {
							ir_entity *ent = get_Sel_entity(succ);

							if (get_entity_owner(ent) == frame_tp) {
								/* found an access to the outer frame */
								set_entity_link(ent, ADDRESS_TAKEN);
							}
						}
					}
				}
			}
		}
	}

Michael Beck's avatar
Michael Beck committed
371
372
373
374
375
	/*
	 * Check the ir_graph for Sel nodes. If the entity of Sel
	 * isn't a scalar replacement set the link of this entity
	 * equal ADDRESS_TAKEN.
	 */
376
377
	irg_frame = get_irg_frame(irg);
	for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
Michael Beck's avatar
Michael Beck committed
378
379
380
381
382
383
		ir_node *succ = get_irn_out(irg_frame, i);

		if (is_Sel(succ)) {
			ir_entity *ent = get_Sel_entity(succ);
			ir_type *ent_type;

384
385
386
387
388
			/* we are only interested in entities on the frame, NOT
			   on the value type */
			if (get_entity_owner(ent) != frame_tp)
				continue;

Michael Beck's avatar
Michael Beck committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
			if (get_entity_link(ent) == ADDRESS_TAKEN)
				continue;

			/*
			 * Beware: in rare cases even entities on the frame might be
			 * volatile. This might happen if the entity serves as a store
			 * to a value that must survive a exception. Do not optimize
			 * such entities away.
			 */
			if (get_entity_volatility(ent) == volatility_is_volatile) {
				set_entity_link(ent, ADDRESS_TAKEN);
				continue;
			}

			ent_type = get_entity_type(ent);

			/* we can handle arrays, structs and atomic types yet */
			if (is_Array_type(ent_type) || is_Struct_type(ent_type) || is_atomic_type(ent_type)) {
				if (is_address_taken(succ)) {
408
409
					 /* killing one */
					if (get_entity_link(ent))
Michael Beck's avatar
Michael Beck committed
410
411
412
413
414
415
416
417
418
419
420
421
422
						--res;
					set_entity_link(ent, ADDRESS_TAKEN);
				} else {
					/* possible found one */
					if (get_entity_link(ent) == NULL)
						++res;
					link_all_leave_sels(ent, succ);
				}
			}
		}
	}

	return res;
423
424
425
}

/**
Michael Beck's avatar
Michael Beck committed
426
 * Return a path from the Sel node sel to it's root.
Michael Beck's avatar
Michael Beck committed
427
428
429
 *
 * @param sel  the Sel node
 * @param len  the length of the path so far
430
 */
Michael Beck's avatar
Michael Beck committed
431
432
433
434
static path_t *find_path(ir_node *sel, unsigned len) {
	int pos, i, n;
	path_t *res;
	ir_node *pred = get_Sel_ptr(sel);
Michael Beck's avatar
Michael Beck committed
435

Michael Beck's avatar
Michael Beck committed
436
437
438
	/* the current Sel node will add some path elements */
	n    = get_Sel_n_indexs(sel);
	len += n + 1;
439

Michael Beck's avatar
Michael Beck committed
440
441
	if (! is_Sel(pred)) {
		/* we found the root */
442
		res = XMALLOCF(path_t, path, len);
Michael Beck's avatar
Michael Beck committed
443
444
445
		res->path_len = len;
	} else
		res = find_path(pred, len);
446

Michael Beck's avatar
Michael Beck committed
447
	pos = res->path_len - len;
448

Michael Beck's avatar
Michael Beck committed
449
450
451
	res->path[pos++].ent = get_Sel_entity(sel);
	for (i = 0; i < n; ++i) {
		ir_node *index = get_Sel_index(sel, i);
452

Michael Beck's avatar
Michael Beck committed
453
454
455
		res->path[pos++].tv = get_Const_tarval(index);
	}
	return res;
456
457
458
459
}


/**
Michael Beck's avatar
Michael Beck committed
460
461
 * Allocate value numbers for the leaves
 * in our found entities.
462
 *
Michael Beck's avatar
Michael Beck committed
463
 * @param sels  a set that will contain all Sels that have a value number
464
465
466
467
468
469
470
 * @param ent   the entity that will be scalar replaced
 * @param vnum  the first value number we can assign
 * @param modes a flexible array, containing all the modes of
 *              the value numbers.
 *
 * @return the next free value number
 */
471
static unsigned allocate_value_numbers(pset *sels, ir_entity *ent, unsigned vnum, ir_mode ***modes)
472
{
Michael Beck's avatar
Michael Beck committed
473
474
475
	ir_node *sel, *next;
	path_t *key, *path;
	set *pathes = new_set(path_cmp, 8);
476

477
	DB((dbg, SET_LEVEL_3, "  Visiting Sel nodes of entity %+F\n", ent));
Michael Beck's avatar
Michael Beck committed
478
479
480
	/* visit all Sel nodes in the chain of the entity */
	for (sel = get_entity_link(ent); sel; sel = next) {
		next = get_irn_link(sel);
481

Michael Beck's avatar
Michael Beck committed
482
483
		/* we must mark this sel for later */
		pset_insert_ptr(sels, sel);
Michael Beck's avatar
Michael Beck committed
484

Michael Beck's avatar
Michael Beck committed
485
486
		key  = find_path(sel, 0);
		path = set_find(pathes, key, PATH_SIZE(key), path_hash(key));
487

488
		if (path) {
Michael Beck's avatar
Michael Beck committed
489
			SET_VNUM(sel, path->vnum);
490
491
			DB((dbg, SET_LEVEL_3, "  %+F represents value %u\n", sel, path->vnum));
		} else {
Michael Beck's avatar
Michael Beck committed
492
			key->vnum = vnum++;
493

Michael Beck's avatar
Michael Beck committed
494
			set_insert(pathes, key, PATH_SIZE(key), path_hash(key));
495

Michael Beck's avatar
Michael Beck committed
496
			SET_VNUM(sel, key->vnum);
497
498
			DB((dbg, SET_LEVEL_3, "  %+F represents value %u\n", sel, key->vnum));

Michael Beck's avatar
Michael Beck committed
499
			ARR_EXTO(ir_mode *, *modes, (int)((key->vnum + 15) & ~15));
500

Michael Beck's avatar
Michael Beck committed
501
			(*modes)[key->vnum] = get_type_mode(get_entity_type(get_Sel_entity(sel)));
502

Michael Beck's avatar
Michael Beck committed
503
			assert((*modes)[key->vnum] && "Value is not atomic");
Michael Beck's avatar
Michael Beck committed
504
505

#ifdef DEBUG_libfirm
Michael Beck's avatar
Michael Beck committed
506
			/* Debug output */
507
			{
Michael Beck's avatar
Michael Beck committed
508
				unsigned i;
509
				DB((dbg, SET_LEVEL_2, "  %s", get_entity_name(key->path[0].ent)));
Michael Beck's avatar
Michael Beck committed
510
511
				for (i = 1; i < key->path_len; ++i) {
					if (is_entity(key->path[i].ent))
512
						DB((dbg, SET_LEVEL_2, ".%s", get_entity_name(key->path[i].ent)));
Michael Beck's avatar
Michael Beck committed
513
					else
514
						DB((dbg, SET_LEVEL_2, "[%ld]", get_tarval_long(key->path[i].tv)));
Michael Beck's avatar
Michael Beck committed
515
				}
516
				DB((dbg, SET_LEVEL_2, " = %u (%s)\n", PTR_TO_INT(get_irn_link(sel)), get_mode_name((*modes)[key->vnum])));
Michael Beck's avatar
Michael Beck committed
517
			}
Michael Beck's avatar
Michael Beck committed
518
#endif /* DEBUG_libfirm */
Michael Beck's avatar
Michael Beck committed
519
520
521
		}
		free(key);
	}
522

Michael Beck's avatar
Michael Beck committed
523
524
525
	del_set(pathes);
	set_entity_link(ent, NULL);
	return vnum;
526
527
}

Michael Beck's avatar
Michael Beck committed
528
529
530
531
/**
 * A list entry for the fixing lists
 */
typedef struct _list_entry_t {
Michael Beck's avatar
Michael Beck committed
532
533
	ir_node  *node;   /**< the node that must be fixed */
	unsigned vnum;    /**< the value number of this node */
Michael Beck's avatar
Michael Beck committed
534
} list_entry_t;
535
536
537
538
539

/**
 * environment for memory walker
 */
typedef struct _env_t {
Michael Beck's avatar
Michael Beck committed
540
541
542
	int          nvals;       /**< number of values */
	ir_mode      **modes;     /**< the modes of the values */
	pset         *sels;       /**< A set of all Sel nodes that have a value number */
543
544
545
} env_t;

/**
546
 * topological post-walker.
547
 */
Michael Beck's avatar
Michael Beck committed
548
549
static void topologic_walker(ir_node *node, void *ctx) {
	env_t        *env = ctx;
550
	ir_node      *adr, *block, *mem, *val;
Michael Beck's avatar
Michael Beck committed
551
552
553
	ir_mode      *mode;
	unsigned     vnum;

554
	if (is_Load(node)) {
Michael Beck's avatar
Michael Beck committed
555
556
557
		/* a load, check if we can resolve it */
		adr = get_Load_ptr(node);

558
559
560
		DB((dbg, SET_LEVEL_3, "  checking %+F for replacement ", node));
		if (! is_Sel(adr)) {
			DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
Michael Beck's avatar
Michael Beck committed
561
			return;
562
		}
Michael Beck's avatar
Michael Beck committed
563

564
565
		if (! pset_find_ptr(env->sels, adr)) {
			DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
Michael Beck's avatar
Michael Beck committed
566
			return;
567
		}
Michael Beck's avatar
Michael Beck committed
568
569
570
571
572

		/* ok, we have a Load that will be replaced */
		vnum = GET_VNUM(adr);
		assert(vnum < (unsigned)env->nvals);

573
		DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
Michael Beck's avatar
Michael Beck committed
574

575
576
577
		block = get_nodes_block(node);
		set_cur_block(block);

Michael Beck's avatar
Michael Beck committed
578
		/* check, if we can replace this Load */
579
		val = get_value(vnum, env->modes[vnum]);
Michael Beck's avatar
Michael Beck committed
580

581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
		/* Beware: A Load can contain a hidden conversion in Firm.
		This happens for instance in the following code:

		 int i;
		 unsigned j = *(unsigned *)&i;

		Handle this here. */
		mode = get_Load_mode(node);
		if (mode != get_irn_mode(val))
			val = new_d_Conv(get_irn_dbg_info(node), val, mode);

		mem = get_Load_mem(node);
		turn_into_tuple(node, pn_Load_max);
		set_Tuple_pred(node, pn_Load_M,         mem);
		set_Tuple_pred(node, pn_Load_res,       val);
596
		set_Tuple_pred(node, pn_Load_X_regular, new_Jmp());
597
		set_Tuple_pred(node, pn_Load_X_except,  new_Bad());
598
	} else if (is_Store(node)) {
599
600
		DB((dbg, SET_LEVEL_3, "  checking %+F for replacement ", node));

Michael Beck's avatar
Michael Beck committed
601
602
603
		/* a Store always can be replaced */
		adr = get_Store_ptr(node);

604
605
		if (! is_Sel(adr)) {
			DB((dbg, SET_LEVEL_3, "no Sel input (%+F)\n", adr));
Michael Beck's avatar
Michael Beck committed
606
			return;
607
		}
Michael Beck's avatar
Michael Beck committed
608

609
610
		if (! pset_find_ptr(env->sels, adr)) {
			DB((dbg, SET_LEVEL_3, "Sel %+F has no VNUM\n", adr));
Michael Beck's avatar
Michael Beck committed
611
			return;
612
		}
Michael Beck's avatar
Michael Beck committed
613
614
615
616

		vnum = GET_VNUM(adr);
		assert(vnum < (unsigned)env->nvals);

617
		DB((dbg, SET_LEVEL_3, "replacing by value %u\n", vnum));
Michael Beck's avatar
Michael Beck committed
618

619
620
621
		block = get_nodes_block(node);
		set_cur_block(block);

Michael Beck's avatar
Michael Beck committed
622
623
624
625
626
		/* Beware: A Store can contain a hidden conversion in Firm. */
		val = get_Store_value(node);
		if (get_irn_mode(val) != env->modes[vnum])
			val = new_d_Conv(get_irn_dbg_info(node), val, env->modes[vnum]);

627
		set_value(vnum, val);
Michael Beck's avatar
Michael Beck committed
628

629
		mem = get_Store_mem(node);
Michael Beck's avatar
Michael Beck committed
630
631
		turn_into_tuple(node, pn_Store_max);
		set_Tuple_pred(node, pn_Store_M,         mem);
632
		set_Tuple_pred(node, pn_Store_X_regular, new_Jmp());
Michael Beck's avatar
Michael Beck committed
633
634
		set_Tuple_pred(node, pn_Store_X_except,  new_Bad());
	}
635
636
637
}

/**
638
 * Make scalar replacement.
639
 *
Michael Beck's avatar
Michael Beck committed
640
641
 * @param sels    A set containing all Sel nodes that have a value number
 * @param nvals   The number of scalars.
Michael Beck's avatar
Michael Beck committed
642
643
 * @param modes   A flexible array, containing all the modes of
 *                the value numbers.
644
 */
Michael Beck's avatar
Michael Beck committed
645
646
647
static void do_scalar_replacements(pset *sels, int nvals, ir_mode **modes) {
	env_t env;

648
649
	ssa_cons_start(current_ir_graph, nvals);

Michael Beck's avatar
Michael Beck committed
650
651
652
653
654
655
656
657
	env.nvals     = nvals;
	env.modes     = modes;
	env.sels      = sels;

	/*
	 * second step: walk over the graph blockwise in topological order
	 * and fill the array as much as possible.
	 */
658
	DB((dbg, SET_LEVEL_3, "Substituting Loads and Stores in %+F\n", current_ir_graph));
Michael Beck's avatar
Michael Beck committed
659
660
	irg_walk_blkwise_graph(current_ir_graph, NULL, topologic_walker, &env);

661
	ssa_cons_finish(current_ir_graph);
662
663
664
665
666
}

/*
 * Find possible scalar replacements
 *
Michael Beck's avatar
Michael Beck committed
667
 * @param irg  The current ir graph.
Michael Beck's avatar
Michael Beck committed
668
 */
Michael Beck's avatar
Michael Beck committed
669
int scalar_replacement_opt(ir_graph *irg) {
Michael Beck's avatar
Michael Beck committed
670
671
672
673
674
675
676
	unsigned  nvals;
	int       i;
	scalars_t key, *value;
	ir_node   *irg_frame;
	ir_mode   **modes;
	set       *set_ent;
	pset      *sels;
677
	ir_type   *ent_type, *frame_tp;
Michael Beck's avatar
Michael Beck committed
678
	ir_graph  *rem;
679
	int       res = 0;
Michael Beck's avatar
Michael Beck committed
680
681

	if (! get_opt_scalar_replacement())
682
		return 0;
Michael Beck's avatar
Michael Beck committed
683
684

	rem = current_ir_graph;
685
	current_ir_graph = irg;
Michael Beck's avatar
Michael Beck committed
686
687
688
689

	/* Call algorithm that computes the out edges */
	assure_irg_outs(irg);

690
	/* we use the link field to store the VNUM */
691
	ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
692
	irp_reserve_resources(irp, IR_RESOURCE_ENTITY_LINK);
693

Michael Beck's avatar
Michael Beck committed
694
695
	/* Find possible scalar replacements */
	if (find_possible_replacements(irg)) {
696
		DB((dbg, SET_LEVEL_1, "Scalar Replacement: %+F\n", irg));
Michael Beck's avatar
Michael Beck committed
697
698
699

		/* Insert in set the scalar replacements. */
		irg_frame = get_irg_frame(irg);
700
701
702
703
704
		nvals     = 0;
		modes     = NEW_ARR_F(ir_mode *, 16);
		set_ent   = new_set(ent_cmp, 8);
		sels      = pset_new_ptr(8);
		frame_tp  = get_irg_frame_type(irg);
Michael Beck's avatar
Michael Beck committed
705

706
		for (i = get_irn_n_outs(irg_frame) - 1; i >= 0; --i) {
Michael Beck's avatar
Michael Beck committed
707
708
709
710
711
			ir_node *succ = get_irn_out(irg_frame, i);

			if (is_Sel(succ)) {
				ir_entity *ent = get_Sel_entity(succ);

712
713
714
715
716
				/* we are only interested in entities on the frame, NOT
				   on the value type */
				if (get_entity_owner(ent) != frame_tp)
					continue;

Michael Beck's avatar
Michael Beck committed
717
718
719
720
721
722
723
724
725
				if (get_entity_link(ent) == NULL || get_entity_link(ent) == ADDRESS_TAKEN)
					continue;

				ent_type = get_entity_type(ent);

				key.ent       = ent;
				key.ent_owner = get_entity_owner(ent);
				set_insert(set_ent, &key, sizeof(key), HASH_PTR(key.ent));

726
727
728
729
730
731
732
733
734
#ifdef DEBUG_libfirm
				if (is_Array_type(ent_type)) {
					DB((dbg, SET_LEVEL_1, "  found array %s\n", get_entity_name(ent)));
				} else if (is_Struct_type(ent_type)) {
					DB((dbg, SET_LEVEL_1, "  found struct %s\n", get_entity_name(ent)));
				} else if (is_atomic_type(ent_type))
					DB((dbg, SET_LEVEL_1, "  found atomic value %s\n", get_entity_name(ent)));
				else {
					panic("Neither an array nor a struct or atomic value found in scalar replace");
Michael Beck's avatar
Michael Beck committed
735
				}
736
#endif /* DEBUG_libfirm */
Michael Beck's avatar
Michael Beck committed
737
738
739
740
741

				nvals = allocate_value_numbers(sels, ent, nvals, &modes);
			}
		}

742
		DB((dbg, SET_LEVEL_1, "  %u values will be needed\n", nvals));
Michael Beck's avatar
Michael Beck committed
743
744

		/* If scalars were found. */
745
		if (nvals > 0) {
Michael Beck's avatar
Michael Beck committed
746
747
			do_scalar_replacements(sels, nvals, modes);

748
			foreach_set(set_ent, value) {
Michael Beck's avatar
Michael Beck committed
749
750
751
752
753
754
755
756
757
758
				remove_class_member(value->ent_owner, value->ent);
			}

			/*
			 * We changed the graph, but did NOT introduce new blocks
			 * neither changed control flow, cf-backedges should be still
			 * consistent.
			 */
			set_irg_outs_inconsistent(irg);
			set_irg_loopinfo_inconsistent(irg);
759

Michael Beck's avatar
Michael Beck committed
760
			res = 1;
Michael Beck's avatar
Michael Beck committed
761
		}
762
763
764
		del_pset(sels);
		del_set(set_ent);
		DEL_ARR_F(modes);
Michael Beck's avatar
Michael Beck committed
765
766
	}

767
768
769
	ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
	irp_free_resources(irp, IR_RESOURCE_ENTITY_LINK);

Michael Beck's avatar
Michael Beck committed
770
	current_ir_graph = rem;
771
	return res;
Michael Beck's avatar
Michael Beck committed
772
}
773
774
775
776

void firm_init_scalar_replace(void) {
	FIRM_DBG_REGISTER(dbg, "firm.opt.scalar_replace");
}