2009-08-12 Sriraman Tallam <tmsriram@google.com>
[deliverable/binutils-gdb.git] / gold / icf.cc
1 // icf.cc -- Identical Code Folding.
2 //
3 // Copyright 2009 Free Software Foundation, Inc.
4 // Written by Sriraman Tallam <tmsriram@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 // Identical Code Folding Algorithm
24 // ----------------------------------
25 // Detecting identical functions is done here and the basic algorithm
26 // is as follows. A checksum is computed on each .text section using
27 // its contents and relocations. If the symbol name corresponding to
28 // a relocation is known it is used to compute the checksum. If the
29 // symbol name is not known the stringified name of the object and the
30 // section number pointed to by the relocation is used. The checksums
31 // are stored as keys in a hash map and a section is identical to some
32 // other section if its checksum is already present in the hash map.
33 // Checksum collisions are handled by using a multimap and explicitly
34 // checking the contents when two sections have the same checksum.
35 //
36 // However, two functions A and B with identical text but with
37 // relocations pointing to different .text sections can be identical if
38 // the corresponding .text sections to which their relocations point to
39 // turn out to be identical. Hence, this checksumming process must be
40 // done repeatedly until convergence is obtained. Here is an example for
41 // the following case :
42 //
43 // int funcA () int funcB ()
44 // { {
45 // return foo(); return goo();
46 // } }
47 //
48 // The functions funcA and funcB are identical if functions foo() and
49 // goo() are identical.
50 //
51 // Hence, as described above, we repeatedly do the checksumming,
52 // assigning identical functions to the same group, until convergence is
53 // obtained. Now, we have two different ways to do this depending on how
54 // we initialize.
55 //
56 // Algorithm I :
57 // -----------
58 // We can start with marking all functions as different and repeatedly do
59 // the checksumming. This has the advantage that we do not need to wait
60 // for convergence. We can stop at any point and correctness will be
61 // guaranteed although not all cases would have been found. However, this
62 // has a problem that some cases can never be found even if it is run until
63 // convergence. Here is an example with mutually recursive functions :
64 //
65 // int funcA (int a) int funcB (int a)
66 // { {
67 // if (a == 1) if (a == 1)
68 // return 1; return 1;
69 // return 1 + funcB(a - 1); return 1 + funcA(a - 1);
70 // } }
71 //
72 // In this example funcA and funcB are identical and one of them could be
73 // folded into the other. However, if we start with assuming that funcA
74 // and funcB are not identical, the algorithm, even after it is run to
75 // convergence, cannot detect that they are identical. It should be noted
76 // that even if the functions were self-recursive, Algorithm I cannot catch
77 // that they are identical, at least as is.
78 //
79 // Algorithm II :
80 // ------------
81 // Here we start with marking all functions as identical and then repeat
82 // the checksumming until convergence. This can detect the above case
83 // mentioned above. It can detect all cases that Algorithm I can and more.
84 // However, the caveat is that it has to be run to convergence. It cannot
85 // be stopped arbitrarily like Algorithm I as correctness cannot be
86 // guaranteed. Algorithm II is not implemented.
87 //
88 // Algorithm I is used because experiments show that about three
89 // iterations are more than enough to achieve convergence. Algorithm I can
90 // handle recursive calls if it is changed to use a special common symbol
91 // for recursive relocs. This seems to be the most common case that
92 // Algorithm I could not catch as is. Mutually recursive calls are not
93 // frequent and Algorithm I wins because of its ability to be stopped
94 // arbitrarily.
95 //
96 // Caveat with using function pointers :
97 // ------------------------------------
98 //
99 // Programs using function pointer comparisons/checks should use function
100 // folding with caution as the result of such comparisons could be different
101 // when folding takes place. This could lead to unexpected run-time
102 // behaviour.
103 //
104 //
105 // How to run : --icf
106 // Optional parameters : --icf-iterations <num> --print-icf-sections
107 //
108 // Performance : Less than 20 % link-time overhead on industry strength
109 // applications. Up to 6 % text size reductions.
110
111 #include "gold.h"
112 #include "object.h"
113 #include "gc.h"
114 #include "icf.h"
115 #include "symtab.h"
116 #include "libiberty.h"
117
118 namespace gold
119 {
120
121 // This function determines if a section or a group of identical
122 // sections has unique contents. Such unique sections or groups can be
123 // declared final and need not be processed any further.
124 // Parameters :
125 // ID_SECTION : Vector mapping a section index to a Section_id pair.
126 // IS_SECN_OR_GROUP_UNIQUE : To check if a section or a group of identical
127 // sections is already known to be unique.
128 // SECTION_CONTENTS : Contains the section's text and relocs to sections
129 // that cannot be folded. SECTION_CONTENTS are NULL
130 // implies that this function is being called for the
131 // first time before the first iteration of icf.
132
133 static void
134 preprocess_for_unique_sections(const std::vector<Section_id>& id_section,
135 std::vector<bool>* is_secn_or_group_unique,
136 std::vector<std::string>* section_contents)
137 {
138 Unordered_map<uint32_t, unsigned int> uniq_map;
139 std::pair<Unordered_map<uint32_t, unsigned int>::iterator, bool>
140 uniq_map_insert;
141
142 for (unsigned int i = 0; i < id_section.size(); i++)
143 {
144 if ((*is_secn_or_group_unique)[i])
145 continue;
146
147 uint32_t cksum;
148 Section_id secn = id_section[i];
149 section_size_type plen;
150 if (section_contents == NULL)
151 {
152 const unsigned char* contents;
153 contents = secn.first->section_contents(secn.second,
154 &plen,
155 false);
156 cksum = xcrc32(contents, plen, 0xffffffff);
157 }
158 else
159 {
160 const unsigned char* contents_array = reinterpret_cast
161 <const unsigned char*>((*section_contents)[i].c_str());
162 cksum = xcrc32(contents_array, (*section_contents)[i].length(),
163 0xffffffff);
164 }
165 uniq_map_insert = uniq_map.insert(std::make_pair(cksum, i));
166 if (uniq_map_insert.second)
167 {
168 (*is_secn_or_group_unique)[i] = true;
169 }
170 else
171 {
172 (*is_secn_or_group_unique)[i] = false;
173 (*is_secn_or_group_unique)[uniq_map_insert.first->second] = false;
174 }
175 }
176 }
177
178 // This returns the buffer containing the section's contents, both
179 // text and relocs. Relocs are differentiated as those pointing to
180 // sections that could be folded and those that cannot. Only relocs
181 // pointing to sections that could be folded are recomputed on
182 // subsequent invocations of this function.
183 // Parameters :
184 // FIRST_ITERATION : true if it is the first invocation.
185 // SECN : Section for which contents are desired.
186 // SECTION_NUM : Unique section number of this section.
187 // NUM_TRACKED_RELOCS : Vector reference to store the number of relocs
188 // to ICF sections.
189 // KEPT_SECTION_ID : Vector which maps folded sections to kept sections.
190 // SECTION_CONTENTS : Store the section's text and relocs to non-ICF
191 // sections.
192
193 static std::string
194 get_section_contents(bool first_iteration,
195 const Section_id& secn,
196 unsigned int section_num,
197 unsigned int* num_tracked_relocs,
198 Symbol_table* symtab,
199 const std::vector<unsigned int>& kept_section_id,
200 std::vector<std::string>* section_contents)
201 {
202 section_size_type plen;
203 const unsigned char* contents = NULL;
204
205 if (first_iteration)
206 {
207 contents = secn.first->section_contents(secn.second,
208 &plen,
209 false);
210 }
211
212 // The buffer to hold all the contents including relocs. A checksum
213 // is then computed on this buffer.
214 std::string buffer;
215 std::string icf_reloc_buffer;
216
217 if (num_tracked_relocs)
218 *num_tracked_relocs = 0;
219
220 Icf::Section_list& seclist = symtab->icf()->section_reloc_list();
221 Icf::Symbol_list& symlist = symtab->icf()->symbol_reloc_list();
222 Icf::Addend_list& addendlist = symtab->icf()->addend_reloc_list();
223
224 Icf::Section_list::iterator it_seclist = seclist.find(secn);
225 Icf::Symbol_list::iterator it_symlist = symlist.find(secn);
226 Icf::Addend_list::iterator it_addendlist = addendlist.find(secn);
227
228 buffer.clear();
229 icf_reloc_buffer.clear();
230
231 // Process relocs and put them into the buffer.
232
233 if (it_seclist != seclist.end())
234 {
235 gold_assert(it_symlist != symlist.end());
236 gold_assert(it_addendlist != addendlist.end());
237 Icf::Sections_reachable_list v = it_seclist->second;
238 Icf::Symbol_info s = it_symlist->second;
239 Icf::Addend_info a = it_addendlist->second;
240 Icf::Sections_reachable_list::iterator it_v = v.begin();
241 Icf::Symbol_info::iterator it_s = s.begin();
242 Icf::Addend_info::iterator it_a = a.begin();
243
244 for (; it_v != v.end(); ++it_v, ++it_s, ++it_a)
245 {
246 // ADDEND_STR stores the symbol value and addend, each
247 // atmost 16 hex digits long. it_v points to a pair
248 // where first is the symbol value and second is the
249 // addend.
250 char addend_str[34];
251 snprintf(addend_str, sizeof(addend_str), "%llx %llx",
252 (*it_a).first, (*it_a).second);
253 Section_id reloc_secn(it_v->first, it_v->second);
254
255 // If this reloc turns back and points to the same section,
256 // like a recursive call, use a special symbol to mark this.
257 if (reloc_secn.first == secn.first
258 && reloc_secn.second == secn.second)
259 {
260 if (first_iteration)
261 {
262 buffer.append("R");
263 buffer.append(addend_str);
264 buffer.append("@");
265 }
266 continue;
267 }
268 Icf::Uniq_secn_id_map& section_id_map =
269 symtab->icf()->section_to_int_map();
270 Icf::Uniq_secn_id_map::iterator section_id_map_it =
271 section_id_map.find(reloc_secn);
272 if (section_id_map_it != section_id_map.end())
273 {
274 // This is a reloc to a section that might be folded.
275 if (num_tracked_relocs)
276 (*num_tracked_relocs)++;
277
278 char kept_section_str[10];
279 unsigned int secn_id = section_id_map_it->second;
280 snprintf(kept_section_str, sizeof(kept_section_str), "%u",
281 kept_section_id[secn_id]);
282 if (first_iteration)
283 {
284 buffer.append("ICF_R");
285 buffer.append(addend_str);
286 }
287 icf_reloc_buffer.append(kept_section_str);
288 // Append the addend.
289 icf_reloc_buffer.append(addend_str);
290 icf_reloc_buffer.append("@");
291 }
292 else
293 {
294 // This is a reloc to a section that cannot be folded.
295 // Process it only in the first iteration.
296 if (!first_iteration)
297 continue;
298
299 uint64_t secn_flags = (it_v->first)->section_flags(it_v->second);
300 // This reloc points to a merge section. Hash the
301 // contents of this section.
302 if ((secn_flags & elfcpp::SHF_MERGE) != 0)
303 {
304 uint64_t entsize =
305 (it_v->first)->section_entsize(it_v->second);
306 long long offset = it_a->first + it_a->second;
307 section_size_type secn_len;
308 const unsigned char* str_contents =
309 (it_v->first)->section_contents(it_v->second,
310 &secn_len,
311 false) + offset;
312 if ((secn_flags & elfcpp::SHF_STRINGS) != 0)
313 {
314 // String merge section.
315 const char* str_char =
316 reinterpret_cast<const char*>(str_contents);
317 switch(entsize)
318 {
319 case 1:
320 {
321 buffer.append(str_char);
322 break;
323 }
324 case 2:
325 {
326 const uint16_t* ptr_16 =
327 reinterpret_cast<const uint16_t*>(str_char);
328 unsigned int strlen_16 = 0;
329 // Find the NULL character.
330 while(*(ptr_16 + strlen_16) != 0)
331 strlen_16++;
332 buffer.append(str_char, strlen_16 * 2);
333 }
334 break;
335 case 4:
336 {
337 const uint32_t* ptr_32 =
338 reinterpret_cast<const uint32_t*>(str_char);
339 unsigned int strlen_32 = 0;
340 // Find the NULL character.
341 while(*(ptr_32 + strlen_32) != 0)
342 strlen_32++;
343 buffer.append(str_char, strlen_32 * 4);
344 }
345 break;
346 default:
347 gold_unreachable();
348 }
349 }
350 else
351 {
352 // Use the entsize to determine the length.
353 buffer.append(reinterpret_cast<const
354 char*>(str_contents),
355 entsize);
356 }
357 }
358 else if ((*it_s) != NULL)
359 {
360 // If symbol name is available use that.
361 const char *sym_name = (*it_s)->name();
362 buffer.append(sym_name);
363 // Append the addend.
364 buffer.append(addend_str);
365 buffer.append("@");
366 }
367 else
368 {
369 // Symbol name is not available, like for a local symbol,
370 // use object and section id.
371 buffer.append(it_v->first->name());
372 char secn_id[10];
373 snprintf(secn_id, sizeof(secn_id), "%u",it_v->second);
374 buffer.append(secn_id);
375 // Append the addend.
376 buffer.append(addend_str);
377 buffer.append("@");
378 }
379 }
380 }
381 }
382
383 if (first_iteration)
384 {
385 buffer.append("Contents = ");
386 buffer.append(reinterpret_cast<const char*>(contents), plen);
387 // Store the section contents that dont change to avoid recomputing
388 // during the next call to this function.
389 (*section_contents)[section_num] = buffer;
390 }
391 else
392 {
393 gold_assert(buffer.empty());
394 // Reuse the contents computed in the previous iteration.
395 buffer.append((*section_contents)[section_num]);
396 }
397
398 buffer.append(icf_reloc_buffer);
399 return buffer;
400 }
401
402 // This function computes a checksum on each section to detect and form
403 // groups of identical sections. The first iteration does this for all
404 // sections.
405 // Further iterations do this only for the kept sections from each group to
406 // determine if larger groups of identical sections could be formed. The
407 // first section in each group is the kept section for that group.
408 //
409 // CRC32 is the checksumming algorithm and can have collisions. That is,
410 // two sections with different contents can have the same checksum. Hence,
411 // a multimap is used to maintain more than one group of checksum
412 // identical sections. A section is added to a group only after its
413 // contents are explicitly compared with the kept section of the group.
414 //
415 // Parameters :
416 // ITERATION_NUM : Invocation instance of this function.
417 // NUM_TRACKED_RELOCS : Vector reference to store the number of relocs
418 // to ICF sections.
419 // KEPT_SECTION_ID : Vector which maps folded sections to kept sections.
420 // ID_SECTION : Vector mapping a section to an unique integer.
421 // IS_SECN_OR_GROUP_UNIQUE : To check if a section or a group of identical
422 // sectionsis already known to be unique.
423 // SECTION_CONTENTS : Store the section's text and relocs to non-ICF
424 // sections.
425
426 static bool
427 match_sections(unsigned int iteration_num,
428 Symbol_table* symtab,
429 std::vector<unsigned int>* num_tracked_relocs,
430 std::vector<unsigned int>* kept_section_id,
431 const std::vector<Section_id>& id_section,
432 std::vector<bool>* is_secn_or_group_unique,
433 std::vector<std::string>* section_contents)
434 {
435 Unordered_multimap<uint32_t, unsigned int> section_cksum;
436 std::pair<Unordered_multimap<uint32_t, unsigned int>::iterator,
437 Unordered_multimap<uint32_t, unsigned int>::iterator> key_range;
438 bool converged = true;
439
440 if (iteration_num == 1)
441 preprocess_for_unique_sections(id_section,
442 is_secn_or_group_unique,
443 NULL);
444 else
445 preprocess_for_unique_sections(id_section,
446 is_secn_or_group_unique,
447 section_contents);
448
449 std::vector<std::string> full_section_contents;
450
451 for (unsigned int i = 0; i < id_section.size(); i++)
452 {
453 full_section_contents.push_back("");
454 if ((*is_secn_or_group_unique)[i])
455 continue;
456
457 Section_id secn = id_section[i];
458 std::string this_secn_contents;
459 uint32_t cksum;
460 if (iteration_num == 1)
461 {
462 unsigned int num_relocs = 0;
463 this_secn_contents = get_section_contents(true, secn, i, &num_relocs,
464 symtab, (*kept_section_id),
465 section_contents);
466 (*num_tracked_relocs)[i] = num_relocs;
467 }
468 else
469 {
470 if ((*kept_section_id)[i] != i)
471 {
472 // This section is already folded into something. See
473 // if it should point to a different kept section.
474 unsigned int kept_section = (*kept_section_id)[i];
475 if (kept_section != (*kept_section_id)[kept_section])
476 {
477 (*kept_section_id)[i] = (*kept_section_id)[kept_section];
478 }
479 continue;
480 }
481 this_secn_contents = get_section_contents(false, secn, i, NULL,
482 symtab, (*kept_section_id),
483 section_contents);
484 }
485
486 const unsigned char* this_secn_contents_array =
487 reinterpret_cast<const unsigned char*>(this_secn_contents.c_str());
488 cksum = xcrc32(this_secn_contents_array, this_secn_contents.length(),
489 0xffffffff);
490 size_t count = section_cksum.count(cksum);
491
492 if (count == 0)
493 {
494 // Start a group with this cksum.
495 section_cksum.insert(std::make_pair(cksum, i));
496 full_section_contents[i] = this_secn_contents;
497 }
498 else
499 {
500 key_range = section_cksum.equal_range(cksum);
501 Unordered_multimap<uint32_t, unsigned int>::iterator it;
502 // Search all the groups with this cksum for a match.
503 for (it = key_range.first; it != key_range.second; ++it)
504 {
505 unsigned int kept_section = it->second;
506 if (full_section_contents[kept_section].length()
507 != this_secn_contents.length())
508 continue;
509 if (memcmp(full_section_contents[kept_section].c_str(),
510 this_secn_contents.c_str(),
511 this_secn_contents.length()) != 0)
512 continue;
513 (*kept_section_id)[i] = kept_section;
514 converged = false;
515 break;
516 }
517 if (it == key_range.second)
518 {
519 // Create a new group for this cksum.
520 section_cksum.insert(std::make_pair(cksum, i));
521 full_section_contents[i] = this_secn_contents;
522 }
523 }
524 // If there are no relocs to foldable sections do not process
525 // this section any further.
526 if (iteration_num == 1 && (*num_tracked_relocs)[i] == 0)
527 (*is_secn_or_group_unique)[i] = true;
528 }
529
530 return converged;
531 }
532
533
534 // This is the main ICF function called in gold.cc. This does the
535 // initialization and calls match_sections repeatedly (twice by default)
536 // which computes the crc checksums and detects identical functions.
537
538 void
539 Icf::find_identical_sections(const Input_objects* input_objects,
540 Symbol_table* symtab)
541 {
542 unsigned int section_num = 0;
543 std::vector<unsigned int> num_tracked_relocs;
544 std::vector<bool> is_secn_or_group_unique;
545 std::vector<std::string> section_contents;
546
547 // Decide which sections are possible candidates first.
548
549 for (Input_objects::Relobj_iterator p = input_objects->relobj_begin();
550 p != input_objects->relobj_end();
551 ++p)
552 {
553 for (unsigned int i = 0;i < (*p)->shnum(); ++i)
554 {
555 // Only looking to fold functions, so just look at .text sections.
556 if (!is_prefix_of(".text.", (*p)->section_name(i).c_str()))
557 continue;
558 if (!(*p)->is_section_included(i))
559 continue;
560 if (parameters->options().gc_sections()
561 && symtab->gc()->is_section_garbage(*p, i))
562 continue;
563 this->id_section_.push_back(Section_id(*p, i));
564 this->section_id_[Section_id(*p, i)] = section_num;
565 this->kept_section_id_.push_back(section_num);
566 num_tracked_relocs.push_back(0);
567 is_secn_or_group_unique.push_back(false);
568 section_contents.push_back("");
569 section_num++;
570 }
571 }
572
573 unsigned int num_iterations = 0;
574
575 // Default number of iterations to run ICF is 2.
576 unsigned int max_iterations = (parameters->options().icf_iterations() > 0)
577 ? parameters->options().icf_iterations()
578 : 2;
579
580 bool converged = false;
581
582 while (!converged && (num_iterations < max_iterations))
583 {
584 num_iterations++;
585 converged = match_sections(num_iterations, symtab,
586 &num_tracked_relocs, &this->kept_section_id_,
587 this->id_section_, &is_secn_or_group_unique,
588 &section_contents);
589 }
590
591 if (parameters->options().print_icf_sections())
592 {
593 if (converged)
594 gold_info(_("%s: ICF Converged after %u iteration(s)"),
595 program_name, num_iterations);
596 else
597 gold_info(_("%s: ICF stopped after %u iteration(s)"),
598 program_name, num_iterations);
599 }
600
601 // Unfold --keep-unique symbols.
602 for (options::String_set::const_iterator p =
603 parameters->options().keep_unique_begin();
604 p != parameters->options().keep_unique_end();
605 ++p)
606 {
607 const char* name = p->c_str();
608 Symbol* sym = symtab->lookup(name);
609 if (sym == NULL)
610 {
611 gold_warning(_("Could not find symbol %s to unfold\n"), name);
612 }
613 else if (sym->source() == Symbol::FROM_OBJECT
614 && !sym->object()->is_dynamic())
615 {
616 Object* obj = sym->object();
617 bool is_ordinary;
618 unsigned int shndx = sym->shndx(&is_ordinary);
619 if (is_ordinary)
620 {
621 this->unfold_section(obj, shndx);
622 }
623 }
624
625 }
626
627 this->icf_ready();
628 }
629
630 // Unfolds the section denoted by OBJ and SHNDX if folded.
631
632 void
633 Icf::unfold_section(Object* obj, unsigned int shndx)
634 {
635 Section_id secn(obj, shndx);
636 Uniq_secn_id_map::iterator it = this->section_id_.find(secn);
637 if (it == this->section_id_.end())
638 return;
639 unsigned int section_num = it->second;
640 unsigned int kept_section_id = this->kept_section_id_[section_num];
641 if (kept_section_id != section_num)
642 this->kept_section_id_[section_num] = section_num;
643 }
644
645 // This function determines if the section corresponding to the
646 // given object and index is folded based on if the kept section
647 // is different from this section.
648
649 bool
650 Icf::is_section_folded(Object* obj, unsigned int shndx)
651 {
652 Section_id secn(obj, shndx);
653 Uniq_secn_id_map::iterator it = this->section_id_.find(secn);
654 if (it == this->section_id_.end())
655 return false;
656 unsigned int section_num = it->second;
657 unsigned int kept_section_id = this->kept_section_id_[section_num];
658 return kept_section_id != section_num;
659 }
660
661 // This function returns the folded section for the given section.
662
663 Section_id
664 Icf::get_folded_section(Object* dup_obj, unsigned int dup_shndx)
665 {
666 Section_id dup_secn(dup_obj, dup_shndx);
667 Uniq_secn_id_map::iterator it = this->section_id_.find(dup_secn);
668 gold_assert(it != this->section_id_.end());
669 unsigned int section_num = it->second;
670 unsigned int kept_section_id = this->kept_section_id_[section_num];
671 Section_id folded_section = this->id_section_[kept_section_id];
672 return folded_section;
673 }
674
675 } // End of namespace gold.
This page took 0.046937 seconds and 5 git commands to generate.