2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
6 * This file may be distributed and/or modified under the terms of the
7 * GNU General Public License version 2 as published by the Free Software
8 * Foundation and appearing in the file LICENSE.GPL included in the
9 * packaging of this file.
11 * Licensees holding valid libFirm Professional Edition licenses may use
12 * this file in accordance with the libFirm Commercial License.
13 * Agreement provided with the Software.
15 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * @brief Procedure cloning.
23 * @author Beyhan Veliev, Michael Beck
27 * The purpose is first to find and analyze functions, that are called
28 * with constant parameter(s).
29 * The second step is to optimize the function that are found from our
30 * analyze. Optimize mean to make a new function with parameters, that
31 * aren't be constant. The constant parameters of the function are placed
32 * in the function graph. They aren't be passed as parameters.
40 #include "iroptimize.h"
46 #include "analyze_irg_args.h"
57 * This struct contains the information quadruple for a Call, which we need to
58 * decide if this function must be cloned.
60 typedef struct quadruple {
61 ir_entity *ent; /**< The entity of our Call. */
62 int pos; /**< Position of a constant argument of our Call. */
63 tarval *tv; /**< The tarval of this argument if Const node. */
64 ir_node **calls; /**< The list of all calls with the same characteristics */
68 * The quadruplets are hold in a sorted list
70 typedef struct entry {
71 quadruple_t q; /**< the quadruple */
72 float weight; /**< its weight */
73 struct entry *next; /**< link to the next one */
76 typedef struct q_set {
77 struct obstack obst; /**< an obstack containing all entries */
78 pset *map; /**< a hash map containing the quadruples */
79 entry_t *heavy_uses; /**< the ordered list of heavy uses */
83 * Compare two quadruplets.
85 * @return zero if they are identically, non-zero else
87 static int entry_cmp(const void *elt, const void *key) {
88 const entry_t *e1 = elt;
89 const entry_t *e2 = key;
91 return (e1->q.ent != e2->q.ent) || (e1->q.pos != e2->q.pos) || (e1->q.tv != e2->q.tv);
95 * Hash an element of type entry_t.
97 * @param entry The element to be hashed.
99 static int hash_entry(const entry_t *entry) {
100 return HASH_PTR(entry->q.ent) ^ HASH_PTR(entry->q.tv) ^ (entry->q.pos * 9);
104 * Free memory associated with a quadruplet.
106 static void kill_entry(entry_t *entry) {
107 if (entry->q.calls) {
108 DEL_ARR_F(entry->q.calls);
109 entry->q.calls = NULL;
114 * Process a call node.
116 * @param call A ir_node to be checked.
117 * @param callee The entity of the callee
118 * @param hmap The quadruple-set containing the calls with constant parameters
120 static void process_call(ir_node *call, ir_entity *callee, q_set *hmap) {
122 entry_t *key, *entry;
126 n_params = get_Call_n_params(call);
128 /* Beware: we cannot clone variadic parameters as well as the
129 * last non-variadic one, which might be needed for the va_start()
132 mtp = get_Call_type(call);
133 if (get_method_variadicity(mtp) != variadicity_non_variadic) {
134 n_params = get_method_first_variadic_param_index(mtp) - 1;
137 /* In this for loop we collect the calls, that have
138 an constant parameter. */
139 for (i = n_params - 1; i >= 0; --i) {
140 call_param = get_Call_param(call, i);
141 if (is_Const(call_param)) {
142 /* we have found a Call to collect and we save the informations,
145 hmap->map = new_pset(entry_cmp, 8);
147 key = obstack_alloc(&hmap->obst, sizeof(*key));
151 key->q.tv = get_Const_tarval(call_param);
156 /* We insert our information in the set, where we collect the calls.*/
157 entry = pset_insert(hmap->map, key, hash_entry(key));
160 obstack_free(&hmap->obst, key);
162 /* add the call to the list */
163 if (! entry->q.calls) {
164 entry->q.calls = NEW_ARR_F(ir_node *, 1);
165 entry->q.calls[0] = call;
167 ARR_APP1(ir_node *, entry->q.calls, call);
173 * Collect all calls in a ir_graph to a set.
175 * @param call A ir_node to be checked.
176 * @param env The quadruple-set containing the calls with constant parameters
178 static void collect_irg_calls(ir_node *call, void *env) {
183 /* We collect just "Call" nodes */
185 call_ptr = get_Call_ptr(call);
187 if (! is_Global(call_ptr))
190 callee = get_Global_entity(call_ptr);
192 /* we can only clone calls to existing entities */
193 if (get_entity_visibility(callee) == visibility_external_allocated)
196 process_call(call, callee, hmap);
201 * Make a name for a clone. The clone name is
202 * the name of the original method suffixed with "_cl_pos_nr".
203 * pos is the pos from our quadruplet and nr is a counter.
205 * @param id The ident of the cloned function.
206 * @param pos The "pos" from our quadruplet.
207 * @param nr A counter for the clones.
209 static ident *get_clone_ident(ident *id, int pos, unsigned nr) {
210 char clone_postfix[32];
212 snprintf(clone_postfix, sizeof(clone_postfix), "_cl_%d_%u", pos, nr);
214 return mangle(id, new_id_from_str(clone_postfix));
218 * Pre-Walker: Copies blocks and nodes from the original method graph
219 * to the cloned graph. Fixes the argument projection numbers for
220 * all arguments behind the removed one.
222 * @param irn A node from the original method graph.
223 * @param env The clone graph.
225 static void copy_nodes(ir_node *irn, void *env) {
226 ir_node *arg, *irg_args, *irn_copy;
228 ir_graph *clone_irg = env;
230 arg = get_irg_link(clone_irg);
231 irg_args = get_Proj_pred(arg);
233 /* Copy all nodes except the arg. */
235 copy_irn_to_irg(irn, clone_irg);
237 irn_copy = get_irn_link(irn);
239 /* Fix argument numbers */
240 if (is_Proj(irn) && get_Proj_pred(irn) == irg_args) {
241 proj_nr = get_Proj_proj(irn);
242 if (get_Proj_proj(arg) < proj_nr)
243 set_Proj_proj(irn_copy, proj_nr - 1);
248 * Post-walker: Set the predecessors of the copied nodes.
249 * The copied nodes are set as link of their original nodes. The links of
250 * "irn" predecessors are the predecessors of copied node.
252 static void set_preds(ir_node *irn, void *env) {
254 ir_node *irn_copy, *pred, *arg;
255 ir_graph *clone_irg = env;
257 arg = get_irg_link(clone_irg);
258 /* Arg is the method argument, that we have replaced by a constant.*/
262 irn_copy = get_irn_link(irn);
265 set_Block_MacroBlock(irn_copy, get_irn_link(get_Block_MacroBlock(irn)));
266 for (i = get_Block_n_cfgpreds(irn) - 1; i >= 0; i--) {
267 pred = get_Block_cfgpred(irn, i);
268 /* "End" block must be handled extra, because it is not matured.*/
269 if (get_irg_end_block(current_ir_graph) == irn)
270 add_immBlock_pred(get_irg_end_block(clone_irg), get_irn_link(pred));
272 set_Block_cfgpred(irn_copy, i, get_irn_link(pred));
275 /* First we set the block our copy if it is not a block.*/
276 set_nodes_block(irn_copy, get_irn_link(get_nodes_block(irn)));
277 if (get_irn_op(irn) == op_End) {
278 /* Handle the keep-alives. This must be done separately, because
279 the End node was NOT copied */
280 for (i = 0; i < get_End_n_keepalives(irn); ++i)
281 add_End_keepalive(irn_copy, get_irn_link(get_End_keepalive(irn, i)));
283 for (i = get_irn_arity(irn) - 1; i >= 0; i--) {
284 pred = get_irn_n(irn, i);
285 set_irn_n(irn_copy, i, get_irn_link(pred));
292 * Get the method argument at the position "pos".
294 * @param irg irg that must be cloned.
295 * @param pos The position of the argument.
297 static ir_node *get_irg_arg(ir_graph *irg, int pos) {
298 ir_node *irg_args = get_irg_args(irg), *arg = NULL;
301 /* Call algorithm that computes the out edges */
302 assure_irg_outs(irg);
304 /* Search the argument with the number pos.*/
305 for (i = get_irn_n_outs(irg_args) - 1; i >= 0; --i) {
306 ir_node *proj = get_irn_out(irg_args, i);
307 if (pos == get_Proj_proj(proj)) {
310 * More than one arg node found:
311 * We rely on the fact the only one arg exists, so do
312 * a cheap CSE in this case.
314 set_irn_out(irg_args, i, arg);
320 assert(arg && "Argument not found");
325 * Create a new graph for the clone of the method,
326 * that we want to clone.
328 * @param ent The entity of the method that must be cloned.
329 * @param q Our quadruplet.
331 static void create_clone_proc_irg(ir_entity *ent, quadruple_t *q) {
332 ir_graph *method_irg, *clone_irg;
333 ir_node *arg, *const_arg;
335 method_irg = get_entity_irg(ent);
337 /* We create the skeleton of the clone irg.*/
338 clone_irg = new_ir_graph(ent, 0);
340 arg = get_irg_arg(get_entity_irg(q->ent), q->pos);
341 /* we will replace the argument in position "q->pos" by this constant. */
342 const_arg = new_r_Const_type(
343 clone_irg, get_nodes_block(arg), get_irn_mode(arg), q->tv,
344 get_method_param_type(get_entity_type(q->ent), q->pos));
346 /* args copy in the cloned graph will be the const. */
347 set_irn_link(arg, const_arg);
349 /* Store the arg that will be replaced here, so we can easily detect it. */
350 set_irg_link(clone_irg, arg);
352 /* We copy the blocks and nodes, that must be in
353 the clone graph and set their predecessors. */
354 irg_walk_graph(method_irg, copy_nodes, set_preds, clone_irg);
356 /* The "cloned" graph must be matured. */
357 mature_immBlock(get_irg_end_block(clone_irg));
358 irg_finalize_cons(clone_irg);
362 * The function create a new entity type
363 * for our clone and set it to clone entity.
365 * @param q Contains information for the method to clone.
366 * @param ent The entity of the clone.
367 * @param nr A pointer to the counter of clones.
369 static void change_entity_type(quadruple_t *q, ir_entity *ent, unsigned *nr) {
370 ir_type *mtp, *new_mtp, *tp;
372 int i, j, n_params, n_ress;
374 mtp = get_entity_type(q->ent);
375 tp_name = get_clone_ident(get_type_ident(mtp), q->pos, (*nr)++);
376 n_params = get_method_n_params(mtp);
377 n_ress = get_method_n_ress(mtp);
379 /* Create the new type for our clone. It must have one parameter
380 less then the original.*/
381 new_mtp = new_type_method(tp_name, n_params - 1, n_ress);
383 /* We must set the type of the methods parameters.*/
384 for (i = j = 0; i < n_params; ++i) {
386 /* This is the position of the argument, that we have
390 tp = get_method_param_type(mtp, i);
391 set_method_param_type(new_mtp, j++, tp);
393 /* Copy the methods result types. */
394 for (i = 0; i < n_ress; ++i) {
395 tp = get_method_res_type(mtp, i);
396 set_method_res_type(new_mtp, i, tp);
398 set_entity_type(ent, new_mtp);
402 * Make a clone of a method.
404 * @param q Contains information for the method to clone.
406 static ir_entity *clone_method(quadruple_t *q) {
407 ir_entity *new_entity;
411 /* A counter for the clones.*/
412 static unsigned nr = 0;
414 /* We get a new ident for our clone method.*/
415 clone_ident = get_clone_ident(get_entity_ident(q->ent), q->pos, nr);
416 /* We get our entity for the clone method. */
417 new_entity = copy_entity_name(q->ent, clone_ident);
419 /* a cloned entity is always local */
420 set_entity_visibility(new_entity, visibility_local);
422 /* set a ld name here: Should we mangle this ? */
423 set_entity_ld_ident(new_entity, get_entity_ident(new_entity));
425 /* set a new type here. */
426 change_entity_type(q, new_entity, &nr);
428 /* We need now a new ir_graph for our clone method. */
429 create_clone_proc_irg(new_entity, q);
431 /* We must set the atomic value of our "new_entity". */
432 sym.entity_p = new_entity;
433 rem = current_ir_graph;
434 current_ir_graph = get_const_code_irg();
435 new_entity->value = new_SymConst(mode_P_code, sym, symconst_addr_ent);
436 current_ir_graph = rem;
438 /* The "new_entity" don't have this information. */
439 new_entity->attr.mtd_attr.param_access = NULL;
440 new_entity->attr.mtd_attr.param_weight = NULL;
446 * Creates a new "cloned" Call node and return it.
448 * @param call The call that must be cloned.
449 * @param new_entity The entity of the cloned function.
450 * @param pos The position of the replaced parameter of this call.
452 static ir_node *new_cl_Call(ir_node *call, ir_entity *new_entity, int pos) {
455 int i, n_params, new_params = 0;
458 ir_graph *irg = get_irn_irg(call);
459 ir_node *bl = get_nodes_block(call);
461 sym.entity_p = new_entity;
462 callee = new_r_SymConst(irg, bl, mode_P_code, sym, symconst_addr_ent);
464 mtp = get_entity_type(new_entity);
465 n_params = get_Call_n_params(call);
466 NEW_ARR_A(ir_node *, in, n_params - 1);
468 /* we save the parameters of the new call in the array "in" without the
469 * parameter in position "pos", that is replaced with a constant.*/
470 for (i = 0; i < n_params; i++){
472 in[new_params++] = get_Call_param(call, i);
474 /* Create and return the new Call. */
475 return new_r_Call(irg, bl, get_Call_mem(call),
476 callee, n_params - 1, in, get_entity_type(new_entity));
480 * Exchange all Calls stored in the quadruplet to Calls of the cloned entity.
482 * @param q The quadruple
483 * @param cloned_ent The entity of the new function that must be called
486 static void exchange_calls(quadruple_t *q, ir_entity *cloned_ent) {
488 ir_node *new_call, *call;
491 /* We iterate the list of the "call".*/
492 for (i = 0; i < ARR_LEN(q->calls); ++i) {
495 /* A clone exist and the copy of "call" in this
496 * clone graph must be exchanged with new one.*/
497 new_call = new_cl_Call(call, cloned_ent, pos);
498 exchange(call, new_call);
503 * The weight formula:
504 * We save one instruction in every caller and param_weight instructions
507 static float calculate_weight(const entry_t *entry) {
508 return ARR_LEN(entry->q.calls) *
509 (float)(get_method_param_weight(entry->q.ent, entry->q.pos) + 1);
513 * After we exchanged all calls, some entries on the list for
514 * the next cloned entity may get invalid, so we have to check
515 * them and may even update the list of heavy uses.
517 static void reorder_weights(q_set *hmap, float threshold) {
518 entry_t **adr, *p, *entry;
523 entry = hmap->heavy_uses;
527 len = ARR_LEN(entry->q.calls);
528 for (i = 0; i < len; ++i) {
529 ir_node *ptr, *call = entry->q.calls[i];
531 /* might be exchanged, so skip Id nodes here. */
532 call = skip_Id(call);
534 /* we know, that a SymConst is here */
535 ptr = get_Call_ptr(call);
536 assert(get_irn_op(ptr) == op_SymConst);
538 callee = get_SymConst_entity(ptr);
539 if (callee != entry->q.ent) {
541 * This call is already changed because of a previous
542 * optimization. Remove it from the list.
545 entry->q.calls[i] = entry->q.calls[len];
546 entry->q.calls[len] = NULL;
548 /* the new call should be processed */
549 process_call(call, callee, hmap);
554 /* the length might be changed */
555 ARR_SHRINKLEN(entry->q.calls, len);
557 /* recalculate the weight and resort the heavy uses map */
558 entry->weight = calculate_weight(entry);
560 if (len <= 0 || entry->weight < threshold) {
561 hmap->heavy_uses = entry->next;
564 /* we have changed the list, check the next one */
569 for (p = entry->next; p && entry->weight < p->weight; p = p->next) {
574 hmap->heavy_uses = entry->next;
577 entry = hmap->heavy_uses;
579 /* we have changed the list, check the next one */
585 * Do the procedure cloning. Evaluate a heuristic weight for every
586 * call(..., Const, ...). If the weight is bigger than threshold,
587 * clone the entity and fix the calls.
589 void proc_cloning(float threshold) {
590 entry_t *entry = NULL, *p;
595 obstack_init(&hmap.obst);
597 hmap.heavy_uses = NULL;
599 /* initially fill our map by visiting all irgs */
600 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
601 irg = get_irp_irg(i);
602 irg_walk_graph(irg, collect_irg_calls, NULL, &hmap);
605 /* We have the "Call" nodes to optimize in set "set_entries". Our algorithm
606 replace one constant parameter and make a new "Call" node for all found "Calls". It exchange the
607 old one with the new one and the algorithm is called with the new "Call".
609 while (hmap.map || hmap.heavy_uses) {
610 /* We iterate the set and arrange the element of the set in a list.
611 The elements are arranged dependent of their value descending.*/
613 foreach_pset(hmap.map, entry) {
614 entry->weight = calculate_weight(entry);
617 * Do not put entry with a weight < threshold in the list
619 if (entry->weight < threshold) {
624 /* put entry in the heavy uses list */
626 if (! hmap.heavy_uses)
627 hmap.heavy_uses = entry;
629 if (entry->weight >= hmap.heavy_uses->weight) {
630 entry->next = hmap.heavy_uses;
631 hmap.heavy_uses = entry;
633 for (p = hmap.heavy_uses; p->next; p = p->next) {
634 if (entry->weight >= p->next->weight) {
635 entry->next = p->next;
649 /* Print some information about the list. */
650 printf("-----------------\n");
651 for (entry = hmap.heavy_uses; entry; entry = entry->next) {
652 printf("\nweight: is %f\n", entry->weight);
653 ir_printf("Call for Method %E\n", entry->q.ent);
654 printf("Position %i\n", entry->q.pos);
655 ir_printf("Value %T\n", entry->q.tv);
658 entry = hmap.heavy_uses;
660 ir_entity *ent = clone_method(&entry->q);
662 hmap.heavy_uses = entry->next;
664 /* We must exchange the copies of this call in all clones too.*/
665 exchange_calls(&entry->q, ent);
669 * after we exchanged all calls, some entries on the list for
670 * the next cloned entity may get invalid, so we have to check
671 * them and may even update the list of heavy uses.
673 reorder_weights(&hmap, threshold);
676 obstack_free(&hmap.obst, NULL);