xref: /linux/tools/perf/util/annotate.c (revision 0ba32f84fcd17a7a92ea1ff251fb2245ff29180a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
4  *
5  * Parts came from builtin-annotate.c, see those files for further
6  * copyright notes.
7  */
8 
9 #include <errno.h>
10 #include <inttypes.h>
11 #include <stdlib.h>
12 #include "util.h" // hex_width()
13 #include "ui/ui.h"
14 #include "sort.h"
15 #include "build-id.h"
16 #include "color.h"
17 #include "config.h"
18 #include "disasm.h"
19 #include "dso.h"
20 #include "env.h"
21 #include "map.h"
22 #include "maps.h"
23 #include "symbol.h"
24 #include "srcline.h"
25 #include "units.h"
26 #include "debug.h"
27 #include "debuginfo.h"
28 #include "annotate.h"
29 #include "annotate-data.h"
30 #include "evsel.h"
31 #include "evlist.h"
32 #include "bpf-event.h"
33 #include "bpf-utils.h"
34 #include "block-range.h"
35 #include "string2.h"
36 #include "dwarf-regs.h"
37 #include "util/event.h"
38 #include "util/sharded_mutex.h"
39 #include "arch/common.h"
40 #include "namespaces.h"
41 #include "thread.h"
42 #include "hashmap.h"
43 #include "strbuf.h"
44 #include <regex.h>
45 #include <linux/bitops.h>
46 #include <linux/err.h>
47 #include <linux/kernel.h>
48 #include <linux/string.h>
49 #include <linux/zalloc.h>
50 #include <subcmd/parse-options.h>
51 #include <subcmd/run-command.h>
52 #include <math.h>
53 
54 /* FIXME: For the HE_COLORSET */
55 #include "ui/browser.h"
56 
57 /*
58  * FIXME: Using the same values as slang.h,
59  * but that header may not be available everywhere
60  */
61 #define LARROW_CHAR	((unsigned char)',')
62 #define RARROW_CHAR	((unsigned char)'+')
63 #define DARROW_CHAR	((unsigned char)'.')
64 #define UARROW_CHAR	((unsigned char)'-')
65 
66 #include <linux/ctype.h>
67 
68 /* global annotation options */
69 struct annotation_options annotate_opts;
70 
71 /* Data type collection debug statistics */
72 struct annotated_data_stat ann_data_stat;
73 LIST_HEAD(ann_insn_stat);
74 
75 /* Pseudo data types */
76 struct annotated_data_type stackop_type = {
77 	.self = {
78 		.type_name = (char *)"(stack operation)",
79 		.children = LIST_HEAD_INIT(stackop_type.self.children),
80 	},
81 };
82 
83 struct annotated_data_type canary_type = {
84 	.self = {
85 		.type_name = (char *)"(stack canary)",
86 		.children = LIST_HEAD_INIT(canary_type.self.children),
87 	},
88 };
89 
90 #define NO_TYPE ((struct annotated_data_type *)-1UL)
91 
92 /* symbol histogram: key = offset << 16 | evsel->core.idx */
93 static size_t sym_hist_hash(long key, void *ctx __maybe_unused)
94 {
95 	return (key >> 16) + (key & 0xffff);
96 }
97 
98 static bool sym_hist_equal(long key1, long key2, void *ctx __maybe_unused)
99 {
100 	return key1 == key2;
101 }
102 
103 static struct annotated_source *annotated_source__new(void)
104 {
105 	struct annotated_source *src = zalloc(sizeof(*src));
106 
107 	if (src != NULL)
108 		INIT_LIST_HEAD(&src->source);
109 
110 	return src;
111 }
112 
113 static __maybe_unused void annotated_source__delete(struct annotated_source *src)
114 {
115 	struct hashmap_entry *cur;
116 	size_t bkt;
117 
118 	if (src == NULL)
119 		return;
120 
121 	if (src->samples) {
122 		hashmap__for_each_entry(src->samples, cur, bkt)
123 			zfree(&cur->pvalue);
124 		hashmap__free(src->samples);
125 	}
126 	zfree(&src->histograms);
127 	free(src);
128 }
129 
130 static int annotated_source__alloc_histograms(struct annotated_source *src,
131 					      int nr_hists)
132 {
133 	src->nr_histograms   = nr_hists;
134 	src->histograms	     = calloc(nr_hists, sizeof(*src->histograms));
135 
136 	if (src->histograms == NULL)
137 		return -1;
138 
139 	src->samples = hashmap__new(sym_hist_hash, sym_hist_equal, NULL);
140 	if (IS_ERR(src->samples)) {
141 		zfree(&src->histograms);
142 		src->samples = NULL;
143 	}
144 
145 	return src->histograms ? 0 : -1;
146 }
147 
148 struct sym_hist_entry *
149 annotated_source__hist_entry(struct annotated_source *src, const struct evsel *evsel, u64 offset)
150 {
151 	struct sym_hist_entry *entry;
152 	long key = offset << 16 | evsel->core.idx;
153 
154 	if (!hashmap__find(src->samples, key, &entry))
155 		return NULL;
156 	return entry;
157 }
158 
159 void symbol__annotate_zero_histograms(struct symbol *sym)
160 {
161 	struct annotation *notes = symbol__annotation(sym);
162 
163 	annotation__lock(notes);
164 	if (notes->src != NULL) {
165 		memset(notes->src->histograms, 0,
166 		       notes->src->nr_histograms * sizeof(*notes->src->histograms));
167 		hashmap__clear(notes->src->samples);
168 	}
169 	if (notes->branch && notes->branch->cycles_hist) {
170 		memset(notes->branch->cycles_hist, 0,
171 		       symbol__size(sym) * sizeof(struct cyc_hist));
172 	}
173 	annotation__unlock(notes);
174 }
175 
176 static int __symbol__account_cycles(struct cyc_hist *ch,
177 				    u64 start,
178 				    unsigned offset, unsigned cycles,
179 				    unsigned have_start)
180 {
181 	/*
182 	 * For now we can only account one basic block per
183 	 * final jump. But multiple could be overlapping.
184 	 * Always account the longest one. So when
185 	 * a shorter one has been already seen throw it away.
186 	 *
187 	 * We separately always account the full cycles.
188 	 */
189 	ch[offset].num_aggr++;
190 	ch[offset].cycles_aggr += cycles;
191 
192 	if (cycles > ch[offset].cycles_max)
193 		ch[offset].cycles_max = cycles;
194 
195 	if (ch[offset].cycles_min) {
196 		if (cycles && cycles < ch[offset].cycles_min)
197 			ch[offset].cycles_min = cycles;
198 	} else
199 		ch[offset].cycles_min = cycles;
200 
201 	if (!have_start && ch[offset].have_start)
202 		return 0;
203 	if (ch[offset].num) {
204 		if (have_start && (!ch[offset].have_start ||
205 				   ch[offset].start > start)) {
206 			ch[offset].have_start = 0;
207 			ch[offset].cycles = 0;
208 			ch[offset].num = 0;
209 			if (ch[offset].reset < 0xffff)
210 				ch[offset].reset++;
211 		} else if (have_start &&
212 			   ch[offset].start < start)
213 			return 0;
214 	}
215 
216 	if (ch[offset].num < NUM_SPARKS)
217 		ch[offset].cycles_spark[ch[offset].num] = cycles;
218 
219 	ch[offset].have_start = have_start;
220 	ch[offset].start = start;
221 	ch[offset].cycles += cycles;
222 	ch[offset].num++;
223 	return 0;
224 }
225 
226 static int __symbol__inc_addr_samples(struct map_symbol *ms,
227 				      struct annotated_source *src, u64 addr,
228 				      struct perf_sample *sample)
229 {
230 	struct evsel *evsel = sample->evsel;
231 	struct symbol *sym = ms->sym;
232 	long hash_key;
233 	u64 offset;
234 	struct sym_hist *h;
235 	struct sym_hist_entry *entry;
236 	u64 weight = sample->weight ?: sample->ins_lat ?: sample->weight3;
237 
238 	pr_debug3("%s: addr=%#" PRIx64 "\n", __func__, map__unmap_ip(ms->map, addr));
239 
240 	if ((addr < sym->start || addr >= sym->end) &&
241 	    (addr != sym->end || sym->start != sym->end)) {
242 		pr_debug("%s(%d): ERANGE! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 "\n",
243 		       __func__, __LINE__, sym->name, sym->start, addr, sym->end);
244 		return -ERANGE;
245 	}
246 
247 	offset = addr - sym->start;
248 	h = annotated_source__histogram(src, evsel);
249 	if (h == NULL) {
250 		pr_debug("%s(%d): ENOMEM! sym->name=%s, start=%#" PRIx64 ", addr=%#" PRIx64 ", end=%#" PRIx64 ", func: %d\n",
251 			 __func__, __LINE__, sym->name, sym->start, addr, sym->end,
252 			 symbol__type(sym) == STT_FUNC);
253 		return -ENOMEM;
254 	}
255 
256 	hash_key = offset << 16 | evsel->core.idx;
257 	if (!hashmap__find(src->samples, hash_key, &entry)) {
258 		entry = zalloc(sizeof(*entry));
259 		if (entry == NULL)
260 			return -ENOMEM;
261 
262 		if (hashmap__add(src->samples, hash_key, entry) < 0)
263 			return -ENOMEM;
264 	}
265 
266 	h->nr_samples++;
267 	h->period += sample->period;
268 	entry->nr_samples++;
269 	entry->period += sample->period;
270 
271 	if (sample->evsel->core.attr.sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
272 		entry->weight_sum[WEIGHT_WEIGHT] += sample->weight;
273 		entry->weight_num[WEIGHT_WEIGHT]++;
274 		if (sample->weight)
275 			sym_hist__set_weight_mask(h, BIT(WEIGHT_WEIGHT));
276 	}
277 	if (sample->evsel->core.attr.sample_type & PERF_SAMPLE_WEIGHT_STRUCT) {
278 		entry->weight_sum[WEIGHT_INSNLAT] += sample->ins_lat;
279 		entry->weight_num[WEIGHT_INSNLAT]++;
280 		entry->weight_sum[WEIGHT_WEIGHT3] += sample->weight3;
281 		entry->weight_num[WEIGHT_WEIGHT3]++;
282 		if (sample->ins_lat)
283 			sym_hist__set_weight_mask(h, BIT(WEIGHT_INSNLAT));
284 		if (sample->weight3)
285 			sym_hist__set_weight_mask(h, BIT(WEIGHT_WEIGHT3));
286 	}
287 
288 	pr_debug3("%#" PRIx64 " %s: period++ [addr: %#" PRIx64 ", %#" PRIx64
289 		  ", evidx=%d] => nr_samples: %" PRIu64 ", period: %" PRIu64
290 		  " weight %" PRIu64 "\n",
291 		  sym->start, sym->name, addr, addr - sym->start, evsel->core.idx,
292 		  entry->nr_samples, entry->period, weight);
293 	return 0;
294 }
295 
296 struct annotated_branch *annotation__get_branch(struct annotation *notes)
297 {
298 	if (notes == NULL)
299 		return NULL;
300 
301 	if (notes->branch == NULL)
302 		notes->branch = zalloc(sizeof(*notes->branch));
303 
304 	return notes->branch;
305 }
306 
307 static struct annotated_branch *symbol__find_branch_hist(struct symbol *sym,
308 							 unsigned int br_cntr_nr)
309 {
310 	struct annotation *notes = symbol__annotation(sym);
311 	struct annotated_branch *branch;
312 	const size_t size = symbol__size(sym);
313 
314 	branch = annotation__get_branch(notes);
315 	if (branch == NULL)
316 		return NULL;
317 
318 	if (branch->cycles_hist == NULL) {
319 		branch->cycles_hist = calloc(size, sizeof(struct cyc_hist));
320 		if (!branch->cycles_hist)
321 			return NULL;
322 	}
323 
324 	if (br_cntr_nr && branch->br_cntr == NULL) {
325 		branch->br_cntr = calloc(br_cntr_nr * size, sizeof(u64));
326 		if (!branch->br_cntr)
327 			return NULL;
328 	}
329 
330 	return branch;
331 }
332 
333 struct annotated_source *symbol__hists(struct symbol *sym, int nr_hists)
334 {
335 	struct annotation *notes = symbol__annotation(sym);
336 
337 	if (notes->src == NULL) {
338 		notes->src = annotated_source__new();
339 		if (notes->src == NULL)
340 			return NULL;
341 		goto alloc_histograms;
342 	}
343 
344 	if (notes->src->histograms == NULL) {
345 alloc_histograms:
346 		annotated_source__alloc_histograms(notes->src, nr_hists);
347 	}
348 
349 	return notes->src;
350 }
351 
352 static int symbol__inc_addr_samples(struct map_symbol *ms,
353 				    u64 addr,
354 				    struct perf_sample *sample)
355 {
356 	struct symbol *sym = ms->sym;
357 	struct annotated_source *src;
358 
359 	if (sym == NULL)
360 		return 0;
361 	src = symbol__hists(sym, evlist__nr_entries(sample->evsel->evlist));
362 	return src ? __symbol__inc_addr_samples(ms, src, addr, sample) : 0;
363 }
364 
365 static int symbol__account_br_cntr(struct annotated_branch *branch,
366 				   struct evsel *evsel,
367 				   unsigned offset,
368 				   u64 br_cntr)
369 {
370 	unsigned int br_cntr_nr = evsel__leader(evsel)->br_cntr_nr;
371 	unsigned int base = evsel__leader(evsel)->br_cntr_idx;
372 	unsigned int off = offset * evlist__nr_br_cntr(evsel->evlist);
373 	u64 *branch_br_cntr = branch->br_cntr;
374 	unsigned int i, mask, width;
375 
376 	if (!br_cntr || !branch_br_cntr)
377 		return 0;
378 
379 	perf_env__find_br_cntr_info(evsel__env(evsel), NULL, &width);
380 	mask = (1L << width) - 1;
381 	for (i = 0; i < br_cntr_nr; i++) {
382 		u64 cntr = (br_cntr >> i * width) & mask;
383 
384 		branch_br_cntr[off + i + base] += cntr;
385 		if (cntr == mask)
386 			branch_br_cntr[off + i + base] |= ANNOTATION__BR_CNTR_SATURATED_FLAG;
387 	}
388 
389 	return 0;
390 }
391 
392 static int symbol__account_cycles(u64 addr, u64 start, struct symbol *sym,
393 				  unsigned cycles, struct evsel *evsel,
394 				  u64 br_cntr)
395 {
396 	struct annotated_branch *branch;
397 	unsigned offset;
398 	int ret;
399 
400 	if (sym == NULL)
401 		return 0;
402 	branch = symbol__find_branch_hist(sym, evlist__nr_br_cntr(evsel->evlist));
403 	if (!branch)
404 		return -ENOMEM;
405 	if (addr < sym->start || addr >= sym->end)
406 		return -ERANGE;
407 
408 	if (start) {
409 		if (start < sym->start || start >= sym->end)
410 			return -ERANGE;
411 		if (start >= addr)
412 			start = 0;
413 	}
414 	offset = addr - sym->start;
415 	ret = __symbol__account_cycles(branch->cycles_hist,
416 					start ? start - sym->start : 0,
417 					offset, cycles,
418 					!!start);
419 
420 	if (ret)
421 		return ret;
422 
423 	return symbol__account_br_cntr(branch, evsel, offset, br_cntr);
424 }
425 
426 int addr_map_symbol__account_cycles(struct addr_map_symbol *ams,
427 				    struct addr_map_symbol *start,
428 				    unsigned cycles,
429 				    struct evsel *evsel,
430 				    u64 br_cntr)
431 {
432 	u64 saddr = 0;
433 	int err;
434 
435 	if (!cycles)
436 		return 0;
437 
438 	/*
439 	 * Only set start when IPC can be computed. We can only
440 	 * compute it when the basic block is completely in a single
441 	 * function.
442 	 * Special case the case when the jump is elsewhere, but
443 	 * it starts on the function start.
444 	 */
445 	if (start &&
446 		(start->ms.sym == ams->ms.sym ||
447 		 (ams->ms.sym &&
448 		  start->addr == ams->ms.sym->start + map__start(ams->ms.map))))
449 		saddr = start->al_addr;
450 	if (saddr == 0)
451 		pr_debug2("BB with bad start: addr %"PRIx64" start %"PRIx64" sym %"PRIx64" saddr %"PRIx64"\n",
452 			ams->addr,
453 			start ? start->addr : 0,
454 			ams->ms.sym ? ams->ms.sym->start + map__start(ams->ms.map) : 0,
455 			saddr);
456 	err = symbol__account_cycles(ams->al_addr, saddr, ams->ms.sym, cycles, evsel, br_cntr);
457 	if (err)
458 		pr_debug2("account_cycles failed %d\n", err);
459 	return err;
460 }
461 
462 struct annotation_line *annotated_source__get_line(struct annotated_source *src,
463 						   s64 offset)
464 {
465 	struct annotation_line *al;
466 
467 	list_for_each_entry(al, &src->source, node) {
468 		if (al->offset == offset)
469 			return al;
470 	}
471 	return NULL;
472 }
473 
474 static unsigned annotation__count_insn(struct annotation *notes, u64 start, u64 end)
475 {
476 	struct annotation_line *al;
477 	unsigned n_insn = 0;
478 
479 	al = annotated_source__get_line(notes->src, start);
480 	if (al == NULL)
481 		return 0;
482 
483 	list_for_each_entry_from(al, &notes->src->source, node) {
484 		if (al->offset == -1)
485 			continue;
486 		if ((u64)al->offset > end)
487 			break;
488 		n_insn++;
489 	}
490 	return n_insn;
491 }
492 
493 static void annotated_branch__delete(struct annotated_branch *branch)
494 {
495 	if (branch) {
496 		zfree(&branch->cycles_hist);
497 		free(branch->br_cntr);
498 		free(branch);
499 	}
500 }
501 
502 static void annotation__count_and_fill(struct annotation *notes, u64 start, u64 end, struct cyc_hist *ch)
503 {
504 	unsigned n_insn;
505 	unsigned int cover_insn = 0;
506 
507 	n_insn = annotation__count_insn(notes, start, end);
508 	if (n_insn && ch->num && ch->cycles) {
509 		struct annotation_line *al;
510 		struct annotated_branch *branch;
511 		float ipc = n_insn / ((double)ch->cycles / (double)ch->num);
512 
513 		/* Hide data when there are too many overlaps. */
514 		if (ch->reset >= 0x7fff)
515 			return;
516 
517 		al = annotated_source__get_line(notes->src, start);
518 		if (al == NULL)
519 			return;
520 
521 		list_for_each_entry_from(al, &notes->src->source, node) {
522 			if (al->offset == -1)
523 				continue;
524 			if ((u64)al->offset > end)
525 				break;
526 			if (al->cycles && al->cycles->ipc == 0.0) {
527 				al->cycles->ipc = ipc;
528 				cover_insn++;
529 			}
530 		}
531 
532 		branch = annotation__get_branch(notes);
533 		if (cover_insn && branch) {
534 			branch->hit_cycles += ch->cycles;
535 			branch->hit_insn += n_insn * ch->num;
536 			branch->cover_insn += cover_insn;
537 		}
538 	}
539 }
540 
541 static int annotation__compute_ipc(struct annotation *notes, size_t size,
542 				   struct evsel *evsel)
543 {
544 	unsigned int br_cntr_nr = evlist__nr_br_cntr(evsel->evlist);
545 	int err = 0;
546 	s64 offset;
547 
548 	if (!notes->branch || !notes->branch->cycles_hist)
549 		return 0;
550 
551 	notes->branch->total_insn = annotation__count_insn(notes, 0, size - 1);
552 	notes->branch->hit_cycles = 0;
553 	notes->branch->hit_insn = 0;
554 	notes->branch->cover_insn = 0;
555 
556 	annotation__lock(notes);
557 	for (offset = size - 1; offset >= 0; --offset) {
558 		struct cyc_hist *ch;
559 
560 		ch = &notes->branch->cycles_hist[offset];
561 		if (ch && ch->cycles) {
562 			struct annotation_line *al;
563 
564 			al = annotated_source__get_line(notes->src, offset);
565 			if (al && al->cycles == NULL) {
566 				al->cycles = zalloc(sizeof(*al->cycles));
567 				if (al->cycles == NULL) {
568 					err = ENOMEM;
569 					break;
570 				}
571 			}
572 			if (ch->have_start)
573 				annotation__count_and_fill(notes, ch->start, offset, ch);
574 			if (al && ch->num_aggr) {
575 				al->cycles->avg = ch->cycles_aggr / ch->num_aggr;
576 				al->cycles->max = ch->cycles_max;
577 				al->cycles->min = ch->cycles_min;
578 			}
579 			if (al && notes->branch->br_cntr) {
580 				if (!al->br_cntr) {
581 					al->br_cntr = calloc(br_cntr_nr, sizeof(u64));
582 					if (!al->br_cntr) {
583 						err = ENOMEM;
584 						break;
585 					}
586 				}
587 				al->num_aggr = ch->num_aggr;
588 				al->br_cntr_nr = br_cntr_nr;
589 				al->evsel = evsel;
590 				memcpy(al->br_cntr, &notes->branch->br_cntr[offset * br_cntr_nr],
591 				       br_cntr_nr * sizeof(u64));
592 			}
593 		}
594 	}
595 
596 	if (err) {
597 		while (++offset < (s64)size) {
598 			struct cyc_hist *ch = &notes->branch->cycles_hist[offset];
599 
600 			if (ch && ch->cycles) {
601 				struct annotation_line *al;
602 
603 				al = annotated_source__get_line(notes->src, offset);
604 				if (al) {
605 					zfree(&al->cycles);
606 					zfree(&al->br_cntr);
607 				}
608 			}
609 		}
610 	}
611 
612 	annotation__unlock(notes);
613 	return 0;
614 }
615 
616 int addr_map_symbol__inc_samples(struct addr_map_symbol *ams, struct perf_sample *sample)
617 {
618 	return symbol__inc_addr_samples(&ams->ms, ams->al_addr, sample);
619 }
620 
621 int hist_entry__inc_addr_samples(struct hist_entry *he, struct perf_sample *sample, u64 ip)
622 {
623 	return symbol__inc_addr_samples(&he->ms, ip, sample);
624 }
625 
626 
627 void annotation__exit(struct annotation *notes)
628 {
629 	annotated_source__delete(notes->src);
630 	annotated_branch__delete(notes->branch);
631 }
632 
633 static struct sharded_mutex *sharded_mutex;
634 
635 static void annotation__init_sharded_mutex(void)
636 {
637 	/* As many mutexes as there are CPUs. */
638 	sharded_mutex = sharded_mutex__new(cpu__max_present_cpu().cpu);
639 }
640 
641 static size_t annotation__hash(const struct annotation *notes)
642 {
643 	return (size_t)notes;
644 }
645 
646 static struct mutex *annotation__get_mutex(const struct annotation *notes)
647 {
648 	static pthread_once_t once = PTHREAD_ONCE_INIT;
649 
650 	pthread_once(&once, annotation__init_sharded_mutex);
651 	if (!sharded_mutex)
652 		return NULL;
653 
654 	return sharded_mutex__get_mutex(sharded_mutex, annotation__hash(notes));
655 }
656 
657 void annotation__lock(struct annotation *notes)
658 	NO_THREAD_SAFETY_ANALYSIS
659 {
660 	struct mutex *mutex = annotation__get_mutex(notes);
661 
662 	if (mutex)
663 		mutex_lock(mutex);
664 }
665 
666 void annotation__unlock(struct annotation *notes)
667 	NO_THREAD_SAFETY_ANALYSIS
668 {
669 	struct mutex *mutex = annotation__get_mutex(notes);
670 
671 	if (mutex)
672 		mutex_unlock(mutex);
673 }
674 
675 bool annotation__trylock(struct annotation *notes)
676 {
677 	struct mutex *mutex = annotation__get_mutex(notes);
678 
679 	if (!mutex)
680 		return false;
681 
682 	return mutex_trylock(mutex);
683 }
684 
685 void annotation_line__add(struct annotation_line *al, struct list_head *head)
686 {
687 	list_add_tail(&al->node, head);
688 }
689 
690 struct annotation_line *
691 annotation_line__next(struct annotation_line *pos, struct list_head *head)
692 {
693 	list_for_each_entry_continue(pos, head, node)
694 		if (pos->offset >= 0)
695 			return pos;
696 
697 	return NULL;
698 }
699 
700 static const char *annotate__address_color(struct block_range *br)
701 {
702 	double cov = block_range__coverage(br);
703 
704 	if (cov >= 0) {
705 		/* mark red for >75% coverage */
706 		if (cov > 0.75)
707 			return PERF_COLOR_RED;
708 
709 		/* mark dull for <1% coverage */
710 		if (cov < 0.01)
711 			return PERF_COLOR_NORMAL;
712 	}
713 
714 	return PERF_COLOR_MAGENTA;
715 }
716 
717 static const char *annotate__asm_color(struct block_range *br)
718 {
719 	double cov = block_range__coverage(br);
720 
721 	if (cov >= 0) {
722 		/* mark dull for <1% coverage */
723 		if (cov < 0.01)
724 			return PERF_COLOR_NORMAL;
725 	}
726 
727 	return PERF_COLOR_BLUE;
728 }
729 
730 static void annotate__branch_printf(struct block_range *br, u64 addr)
731 {
732 	bool emit_comment = true;
733 
734 	if (!br)
735 		return;
736 
737 #if 1
738 	if (br->is_target && br->start == addr) {
739 		struct block_range *branch = br;
740 		double p;
741 
742 		/*
743 		 * Find matching branch to our target.
744 		 */
745 		while (!branch->is_branch)
746 			branch = block_range__next(branch);
747 
748 		p = 100 *(double)br->entry / branch->coverage;
749 
750 		if (p > 0.1) {
751 			if (emit_comment) {
752 				emit_comment = false;
753 				printf("\t#");
754 			}
755 
756 			/*
757 			 * The percentage of coverage joined at this target in relation
758 			 * to the next branch.
759 			 */
760 			printf(" +%.2f%%", p);
761 		}
762 	}
763 #endif
764 	if (br->is_branch && br->end == addr) {
765 		double p = 100*(double)br->taken / br->coverage;
766 
767 		if (p > 0.1) {
768 			if (emit_comment) {
769 				emit_comment = false;
770 				printf("\t#");
771 			}
772 
773 			/*
774 			 * The percentage of coverage leaving at this branch, and
775 			 * its prediction ratio.
776 			 */
777 			printf(" -%.2f%% (p:%.2f%%)", p, 100*(double)br->pred  / br->taken);
778 		}
779 	}
780 }
781 
782 static int disasm_line__print(struct disasm_line *dl, u64 start, int addr_fmt_width)
783 {
784 	s64 offset = dl->al.offset;
785 	const u64 addr = start + offset;
786 	struct block_range *br;
787 
788 	br = block_range__find(addr);
789 	color_fprintf(stdout, annotate__address_color(br), "  %*" PRIx64 ":", addr_fmt_width, addr);
790 	color_fprintf(stdout, annotate__asm_color(br), "%s", dl->al.line);
791 	annotate__branch_printf(br, addr);
792 	return 0;
793 }
794 
795 static struct annotated_data_type *
796 __hist_entry__get_data_type(struct hist_entry *he, const struct arch *arch,
797 			    struct debuginfo *dbg, struct disasm_line *dl,
798 			    int *type_offset);
799 
800 static bool needs_type_info(struct annotated_data_type *data_type)
801 {
802 	if (data_type == NULL || data_type == NO_TYPE)
803 		return false;
804 
805 	if (verbose)
806 		return true;
807 
808 	return (data_type != &stackop_type) && (data_type != &canary_type);
809 }
810 
811 static const char *annotation__weight_mode_str(enum symbol__weight_mode mode,
812 						 const struct evsel *evsel)
813 {
814 	switch (mode) {
815 	case WEIGHT_NONE:
816 		return "";
817 	case WEIGHT_WEIGHT:
818 		return "Weight";
819 	case WEIGHT_INSNLAT:
820 		return "InsnLat";
821 	case WEIGHT_WEIGHT3:
822 		switch (evsel__e_machine((struct evsel *)evsel, NULL)) {
823 		case EM_PPC:
824 		case EM_PPC64:
825 			return "PCycleLat";
826 		case EM_X86_64:
827 			return "RetireLat";
828 		default:
829 			return "Weight3";
830 		}
831 	default:
832 		return "";
833 	}
834 }
835 
836 static void annotation__column_title(char *buf, size_t size,
837 					     struct annotation *notes,
838 					     const struct evsel *evsel)
839 {
840 	const char *base = symbol_conf.show_total_period ? "Period" :
841 			symbol_conf.show_nr_samples ? "Samples" : "Percent";
842 	int weight;
843 	u8 weight_mask = annotation__weight_mask(notes, evsel);
844 
845 	scnprintf(buf, size, "%s", base);
846 	for_each_weight(weight) {
847 		if (weight_mask & BIT(weight))
848 			scnprintf(buf + strlen(buf),
849 				  size - strlen(buf),
850 				  " %s",
851 				  annotation__weight_mode_str(weight, evsel));
852 	}
853 }
854 
855 static int
856 annotation_line__print(struct annotation_line *al, struct annotation_print_data *apd,
857 		       struct annotation_options *opts, int printed,
858 		       struct annotation_line *queue)
859 {
860 	struct symbol *sym = apd->he->ms.sym;
861 	struct disasm_line *dl = container_of(al, struct disasm_line, al);
862 	struct annotation *notes = symbol__annotation(sym);
863 	static const char *prev_line;
864 	int max_lines = opts->max_lines;
865 	int percent_type = opts->percent_type;
866 
867 	if (al->offset != -1) {
868 		double max_percent = 0.0;
869 		int i, nr_percent = 1;
870 		const char *color;
871 
872 		for (i = 0; i < al->data_nr; i++) {
873 			double percent;
874 
875 			percent = annotation_data__percent(&al->data[i],
876 							   percent_type);
877 
878 			if (percent > max_percent)
879 				max_percent = percent;
880 		}
881 
882 		if (al->data_nr > nr_percent)
883 			nr_percent = al->data_nr;
884 
885 		if (max_percent < opts->min_pcnt)
886 			return -1;
887 
888 		if (max_lines && printed >= max_lines)
889 			return 1;
890 
891 		if (queue != NULL) {
892 			struct annotation_options queue_opts = {
893 				.max_lines = 1,
894 				.percent_type = percent_type,
895 			};
896 
897 			list_for_each_entry_from(queue, &notes->src->source, node) {
898 				if (queue == al)
899 					break;
900 				annotation_line__print(queue, apd, &queue_opts,
901 						       /*printed=*/0, /*queue=*/NULL);
902 			}
903 		}
904 
905 		color = get_percent_color(max_percent);
906 
907 		for (i = 0; i < nr_percent; i++) {
908 			struct annotation_data *data = &al->data[i];
909 			double percent;
910 			int weight;
911 			u8 weight_mask = annotation__weight_mask(notes, apd->evsel);
912 
913 			percent = annotation_data__percent(data, percent_type);
914 			color = get_percent_color(percent);
915 
916 			if (symbol_conf.show_total_period)
917 				color_fprintf(stdout, color, " %11" PRIu64,
918 					      data->he.period);
919 			else if (symbol_conf.show_nr_samples)
920 				color_fprintf(stdout, color, " %7" PRIu64,
921 					      data->he.nr_samples);
922 			else
923 				color_fprintf(stdout, color, " %7.2f", percent);
924 			for_each_weight(weight) {
925 				if (weight_mask & BIT(weight))
926 					color_fprintf(stdout, color, " %7" PRIu64,
927 						      data->he.weight_num[weight] ?
928 						      data->he.weight_sum[weight] /
929 						      data->he.weight_num[weight]
930 						      : 0);
931 			}
932 		}
933 
934 		printf(" : ");
935 
936 		disasm_line__print(dl, notes->src->start, apd->addr_fmt_width);
937 
938 		if (opts->code_with_type && apd->dbg) {
939 			struct annotated_data_type *data_type;
940 			int offset = 0;
941 
942 			data_type = __hist_entry__get_data_type(apd->he, apd->arch,
943 								apd->dbg, dl, &offset);
944 			if (needs_type_info(data_type)) {
945 				char buf[4096];
946 
947 				printf("\t\t# data-type: %s",
948 				       data_type->self.type_name);
949 
950 				if (data_type != &stackop_type &&
951 				    data_type != &canary_type)
952 					printf(" +%#x", offset);
953 
954 				if (annotated_data_type__get_member_name(data_type,
955 									 buf,
956 									 sizeof(buf),
957 									 offset))
958 					printf(" (%s)", buf);
959 			}
960 		}
961 
962 		/*
963 		 * Also color the filename and line if needed, with
964 		 * the same color than the percentage. Don't print it
965 		 * twice for close colored addr with the same filename:line
966 		 */
967 		if (al->path) {
968 			if (!prev_line || strcmp(prev_line, al->path)) {
969 				color_fprintf(stdout, color, " // %s", al->path);
970 				prev_line = al->path;
971 			}
972 		}
973 
974 		printf("\n");
975 	} else if (max_lines && printed >= max_lines)
976 		return 1;
977 	else {
978 		int width = annotation__pcnt_width(notes, apd->evsel);
979 
980 		if (queue)
981 			return -1;
982 
983 		if (!*al->line)
984 			printf(" %*s:\n", width, " ");
985 		else
986 			printf(" %*s: %-*d %s\n", width, " ", apd->addr_fmt_width,
987 			       al->line_nr, al->line);
988 	}
989 
990 	return 0;
991 }
992 
993 static void calc_percent(struct annotation *notes,
994 			 struct evsel *evsel,
995 			 struct annotation_data *data,
996 			 s64 offset, s64 end)
997 {
998 	struct hists *hists = evsel__hists(evsel);
999 	struct sym_hist *sym_hist = annotation__histogram(notes, evsel);
1000 	unsigned int hits = 0;
1001 	u64 period = 0;
1002 	int i;
1003 	u64 weight_sum[WEIGHT_WEIGHT3 + 1] = { 0 };
1004 	u64 weight_num[WEIGHT_WEIGHT3 + 1] = { 0 };
1005 
1006 	while (offset < end) {
1007 		struct sym_hist_entry *entry;
1008 
1009 		entry = annotated_source__hist_entry(notes->src, evsel, offset);
1010 		if (entry) {
1011 			hits   += entry->nr_samples;
1012 			period += entry->period;
1013 			for_each_weight(i) {
1014 				weight_sum[i] += entry->weight_sum[i];
1015 				weight_num[i] += entry->weight_num[i];
1016 			}
1017 		}
1018 		++offset;
1019 	}
1020 
1021 	if (sym_hist->nr_samples) {
1022 		data->he.period     = period;
1023 		data->he.nr_samples = hits;
1024 		for_each_weight(i) {
1025 			data->he.weight_sum[i] = weight_sum[i];
1026 			data->he.weight_num[i] = weight_num[i];
1027 		}
1028 		data->percent[PERCENT_HITS_LOCAL] = 100.0 * hits / sym_hist->nr_samples;
1029 	}
1030 
1031 	if (hists->stats.nr_non_filtered_samples)
1032 		data->percent[PERCENT_HITS_GLOBAL] = 100.0 * hits / hists->stats.nr_non_filtered_samples;
1033 
1034 	if (sym_hist->period)
1035 		data->percent[PERCENT_PERIOD_LOCAL] = 100.0 * period / sym_hist->period;
1036 
1037 	if (hists->stats.total_period)
1038 		data->percent[PERCENT_PERIOD_GLOBAL] = 100.0 * period / hists->stats.total_period;
1039 }
1040 
1041 static void annotation__calc_percent(struct annotation *notes,
1042 				     struct evsel *leader, s64 len)
1043 {
1044 	struct annotation_line *al, *next;
1045 	struct evsel *evsel;
1046 
1047 	list_for_each_entry(al, &notes->src->source, node) {
1048 		s64 end;
1049 		int i = 0;
1050 
1051 		if (al->offset == -1)
1052 			continue;
1053 
1054 		next = annotation_line__next(al, &notes->src->source);
1055 		end  = next ? next->offset : len;
1056 
1057 		for_each_group_evsel(evsel, leader) {
1058 			struct annotation_data *data;
1059 
1060 			BUG_ON(i >= al->data_nr);
1061 
1062 			if (symbol_conf.skip_empty &&
1063 			    evsel__hists(evsel)->stats.nr_samples == 0)
1064 				continue;
1065 
1066 			data = &al->data[i++];
1067 
1068 			calc_percent(notes, evsel, data, al->offset, end);
1069 		}
1070 	}
1071 }
1072 
1073 void symbol__calc_percent(struct symbol *sym, struct evsel *evsel)
1074 {
1075 	struct annotation *notes = symbol__annotation(sym);
1076 
1077 	annotation__calc_percent(notes, evsel, symbol__size(sym));
1078 }
1079 
1080 
1081 
1082 int map_symbol__get_arch(struct map_symbol *ms, const struct arch **parch)
1083 {
1084 	const struct arch *arch;
1085 	struct machine *machine = NULL;
1086 	struct map *map = ms->map;
1087 	struct dso *dso = map ? map__dso(map) : NULL;
1088 	uint32_t e_flags = 0;
1089 	uint16_t e_machine = EM_NONE;
1090 
1091 	const char *cpuid = NULL;
1092 
1093 	if (ms->thread) {
1094 		machine = maps__machine(thread__maps(ms->thread));
1095 		e_machine = thread__e_machine(ms->thread, machine, &e_flags);
1096 		if (machine && machine->env)
1097 			cpuid = machine->env->cpuid;
1098 	} else if (dso) {
1099 		struct maps *kmaps = (map && dso__kernel(dso)) ? map__kmaps(map) : NULL;
1100 		struct machine *kmap_machine = kmaps ? maps__machine(kmaps) : NULL;
1101 
1102 		e_machine = dso__e_machine(dso, kmap_machine, &e_flags);
1103 		if (kmap_machine && kmap_machine->env)
1104 			cpuid = kmap_machine->env->cpuid;
1105 	}
1106 
1107 	if (e_machine == EM_NONE)
1108 		e_machine = thread__e_machine(NULL, NULL, &e_flags);
1109 
1110 	arch = arch__find(e_machine, e_flags, cpuid);
1111 	if (arch == NULL) {
1112 		pr_err("%s: unsupported arch %d\n", __func__, e_machine);
1113 		/* TODO: Refactor annotate/disassemble subsystem error
1114 		 * codes to uniformly return negative integers.
1115 		 */
1116 		return errno ? errno : ENOTSUP;
1117 	}
1118 	if (parch)
1119 		*parch = arch;
1120 
1121 	return 0;
1122 }
1123 
1124 int symbol__annotate(struct map_symbol *ms, struct evsel *evsel,
1125 		     const struct arch **parch)
1126 {
1127 	struct symbol *sym = ms->sym;
1128 	struct annotation *notes = symbol__annotation(sym);
1129 	struct annotate_args args = {
1130 		.options	= &annotate_opts,
1131 	};
1132 	const struct arch *arch = NULL;
1133 	int err, nr;
1134 
1135 	err = map_symbol__get_arch(ms, &arch);
1136 	if (err)
1137 		return err;
1138 
1139 	if (parch)
1140 		*parch = arch;
1141 
1142 	if (notes->src && !list_empty(&notes->src->source))
1143 		return 0;
1144 
1145 	args.arch = arch;
1146 	args.ms = ms;
1147 
1148 	if (notes->src == NULL) {
1149 		notes->src = annotated_source__new();
1150 		if (notes->src == NULL)
1151 			return -1;
1152 	}
1153 
1154 	nr = 0;
1155 	if (evsel__is_group_event(evsel)) {
1156 		struct evsel *pos;
1157 
1158 		for_each_group_evsel(pos, evsel) {
1159 			if (symbol_conf.skip_empty &&
1160 			    evsel__hists(pos)->stats.nr_samples == 0)
1161 				continue;
1162 			nr++;
1163 		}
1164 	}
1165 	notes->src->nr_events = nr ? nr : 1;
1166 
1167 	if (annotate_opts.full_addr)
1168 		notes->src->start = map__objdump_2mem(ms->map, ms->sym->start);
1169 	else
1170 		notes->src->start = map__rip_2objdump(ms->map, ms->sym->start);
1171 
1172 	return symbol__disassemble(sym, &args);
1173 }
1174 
1175 static void insert_source_line(struct rb_root *root, struct annotation_line *al)
1176 {
1177 	struct annotation_line *iter;
1178 	struct rb_node **p = &root->rb_node;
1179 	struct rb_node *parent = NULL;
1180 	unsigned int percent_type = annotate_opts.percent_type;
1181 	int i, ret;
1182 
1183 	while (*p != NULL) {
1184 		parent = *p;
1185 		iter = rb_entry(parent, struct annotation_line, rb_node);
1186 
1187 		ret = strcmp(iter->path, al->path);
1188 		if (ret == 0) {
1189 			for (i = 0; i < al->data_nr; i++) {
1190 				iter->data[i].percent_sum += annotation_data__percent(&al->data[i],
1191 										      percent_type);
1192 			}
1193 			return;
1194 		}
1195 
1196 		if (ret < 0)
1197 			p = &(*p)->rb_left;
1198 		else
1199 			p = &(*p)->rb_right;
1200 	}
1201 
1202 	for (i = 0; i < al->data_nr; i++) {
1203 		al->data[i].percent_sum = annotation_data__percent(&al->data[i],
1204 								   percent_type);
1205 	}
1206 
1207 	rb_link_node(&al->rb_node, parent, p);
1208 	rb_insert_color(&al->rb_node, root);
1209 }
1210 
1211 static int cmp_source_line(struct annotation_line *a, struct annotation_line *b)
1212 {
1213 	int i;
1214 
1215 	for (i = 0; i < a->data_nr; i++) {
1216 		if (a->data[i].percent_sum == b->data[i].percent_sum)
1217 			continue;
1218 		return a->data[i].percent_sum > b->data[i].percent_sum;
1219 	}
1220 
1221 	return 0;
1222 }
1223 
1224 static void __resort_source_line(struct rb_root *root, struct annotation_line *al)
1225 {
1226 	struct annotation_line *iter;
1227 	struct rb_node **p = &root->rb_node;
1228 	struct rb_node *parent = NULL;
1229 
1230 	while (*p != NULL) {
1231 		parent = *p;
1232 		iter = rb_entry(parent, struct annotation_line, rb_node);
1233 
1234 		if (cmp_source_line(al, iter))
1235 			p = &(*p)->rb_left;
1236 		else
1237 			p = &(*p)->rb_right;
1238 	}
1239 
1240 	rb_link_node(&al->rb_node, parent, p);
1241 	rb_insert_color(&al->rb_node, root);
1242 }
1243 
1244 static void resort_source_line(struct rb_root *dest_root, struct rb_root *src_root)
1245 {
1246 	struct annotation_line *al;
1247 	struct rb_node *node;
1248 
1249 	node = rb_first(src_root);
1250 	while (node) {
1251 		struct rb_node *next;
1252 
1253 		al = rb_entry(node, struct annotation_line, rb_node);
1254 		next = rb_next(node);
1255 		rb_erase(node, src_root);
1256 
1257 		__resort_source_line(dest_root, al);
1258 		node = next;
1259 	}
1260 }
1261 
1262 static void print_summary(struct rb_root *root, const char *filename)
1263 {
1264 	struct annotation_line *al;
1265 	struct rb_node *node;
1266 
1267 	printf("\nSorted summary for file %s\n", filename);
1268 	printf("----------------------------------------------\n\n");
1269 
1270 	if (RB_EMPTY_ROOT(root)) {
1271 		printf(" Nothing higher than %1.1f%%\n", MIN_GREEN);
1272 		return;
1273 	}
1274 
1275 	node = rb_first(root);
1276 	while (node) {
1277 		double percent, percent_max = 0.0;
1278 		const char *color;
1279 		char *path;
1280 		int i;
1281 
1282 		al = rb_entry(node, struct annotation_line, rb_node);
1283 		for (i = 0; i < al->data_nr; i++) {
1284 			percent = al->data[i].percent_sum;
1285 			color = get_percent_color(percent);
1286 			color_fprintf(stdout, color, " %7.2f", percent);
1287 
1288 			if (percent > percent_max)
1289 				percent_max = percent;
1290 		}
1291 
1292 		path = al->path;
1293 		color = get_percent_color(percent_max);
1294 		color_fprintf(stdout, color, " %s\n", path);
1295 
1296 		node = rb_next(node);
1297 	}
1298 }
1299 
1300 static void symbol__annotate_hits(struct symbol *sym, struct evsel *evsel)
1301 {
1302 	struct annotation *notes = symbol__annotation(sym);
1303 	struct sym_hist *h = annotation__histogram(notes, evsel);
1304 	u64 len = symbol__size(sym), offset;
1305 
1306 	for (offset = 0; offset < len; ++offset) {
1307 		struct sym_hist_entry *entry;
1308 
1309 		entry = annotated_source__hist_entry(notes->src, evsel, offset);
1310 		if (entry && entry->nr_samples != 0)
1311 			printf("%*" PRIx64 ": %" PRIu64 "\n", BITS_PER_LONG / 2,
1312 			       sym->start + offset, entry->nr_samples);
1313 	}
1314 	printf("%*s: %" PRIu64 "\n", BITS_PER_LONG / 2, "h->nr_samples", h->nr_samples);
1315 }
1316 
1317 static int annotated_source__addr_fmt_width(struct list_head *lines, u64 start)
1318 {
1319 	char bf[32];
1320 	struct annotation_line *line;
1321 
1322 	list_for_each_entry_reverse(line, lines, node) {
1323 		if (line->offset != -1)
1324 			return scnprintf(bf, sizeof(bf), "%" PRIx64, start + line->offset);
1325 	}
1326 
1327 	return 0;
1328 }
1329 
1330 int hist_entry__annotate_printf(struct hist_entry *he, struct evsel *evsel)
1331 {
1332 	struct map_symbol *ms = &he->ms;
1333 	struct map *map = ms->map;
1334 	struct symbol *sym = ms->sym;
1335 	struct dso *dso = map__dso(map);
1336 	char *filename;
1337 	const char *d_filename;
1338 	const char *evsel_name = evsel__name(evsel);
1339 	struct annotation *notes = symbol__annotation(sym);
1340 	struct sym_hist *h = annotation__histogram(notes, evsel);
1341 	struct annotation_line *pos, *queue = NULL;
1342 	struct annotation_options *opts = &annotate_opts;
1343 	struct annotation_print_data apd = {
1344 		.he = he,
1345 		.evsel = evsel,
1346 	};
1347 	int printed = 2, queue_len = 0;
1348 	int more = 0;
1349 	bool context = opts->context;
1350 	int width = annotation__pcnt_width(notes, evsel);
1351 	int graph_dotted_len;
1352 	char title[64];
1353 	char buf[512];
1354 
1355 	filename = strdup(dso__long_name(dso));
1356 	if (!filename)
1357 		return -ENOMEM;
1358 
1359 	if (opts->full_path)
1360 		d_filename = filename;
1361 	else
1362 		d_filename = perf_basename(filename);
1363 
1364 	if (evsel__is_group_event(evsel)) {
1365 		evsel__group_desc(evsel, buf, sizeof(buf));
1366 		evsel_name = buf;
1367 	}
1368 
1369 	if (map_symbol__get_arch(ms, &apd.arch)) {
1370 		free(filename);
1371 		return ENOTSUP;
1372 	}
1373 
1374 	annotation__column_title(title, sizeof(title), notes, evsel);
1375 	graph_dotted_len = printf(" %-*.*s|\tSource code & Disassembly of %s for %s (%" PRIu64 " samples, "
1376 				  "percent: %s)\n",
1377 				  width, width, title,
1378 				  d_filename, evsel_name, h->nr_samples,
1379 				  percent_type_str(opts->percent_type));
1380 
1381 	printf("%-*.*s----\n",
1382 	       graph_dotted_len, graph_dotted_len, graph_dotted_line);
1383 
1384 	if (verbose > 0)
1385 		symbol__annotate_hits(sym, evsel);
1386 
1387 	apd.addr_fmt_width = annotated_source__addr_fmt_width(&notes->src->source,
1388 							      notes->src->start);
1389 	apd.dbg = dso__debuginfo(dso);
1390 
1391 	list_for_each_entry(pos, &notes->src->source, node) {
1392 		int err;
1393 
1394 		if (context && queue == NULL) {
1395 			queue = pos;
1396 			queue_len = 0;
1397 		}
1398 
1399 		err = annotation_line__print(pos, &apd, opts, printed, queue);
1400 
1401 		switch (err) {
1402 		case 0:
1403 			++printed;
1404 			if (context) {
1405 				printed += queue_len;
1406 				queue = NULL;
1407 				queue_len = 0;
1408 			}
1409 			break;
1410 		case 1:
1411 			/* filtered by max_lines */
1412 			++more;
1413 			break;
1414 		case -1:
1415 		default:
1416 			/*
1417 			 * Filtered by min_pcnt or non IP lines when
1418 			 * context != 0
1419 			 */
1420 			if (!context)
1421 				break;
1422 			if (queue_len == context)
1423 				queue = list_entry(queue->node.next, typeof(*queue), node);
1424 			else
1425 				++queue_len;
1426 			break;
1427 		}
1428 	}
1429 
1430 	debuginfo__delete(apd.dbg);
1431 	free(filename);
1432 
1433 	return more;
1434 }
1435 
1436 static void FILE__set_percent_color(void *fp __maybe_unused,
1437 				    double percent __maybe_unused,
1438 				    bool current __maybe_unused)
1439 {
1440 }
1441 
1442 static int FILE__set_jumps_percent_color(void *fp __maybe_unused,
1443 					 int nr __maybe_unused, bool current __maybe_unused)
1444 {
1445 	return 0;
1446 }
1447 
1448 static int FILE__set_color(void *fp __maybe_unused, int color __maybe_unused)
1449 {
1450 	return 0;
1451 }
1452 
1453 static void FILE__printf(void *fp, const char *fmt, ...)
1454 {
1455 	va_list args;
1456 
1457 	va_start(args, fmt);
1458 	vfprintf(fp, fmt, args);
1459 	va_end(args);
1460 }
1461 
1462 static void FILE__write_graph(void *fp, int graph)
1463 {
1464 	const char *s;
1465 	switch (graph) {
1466 
1467 	case DARROW_CHAR: s = "↓"; break;
1468 	case UARROW_CHAR: s = "↑"; break;
1469 	case LARROW_CHAR: s = "←"; break;
1470 	case RARROW_CHAR: s = "→"; break;
1471 	default:		s = "?"; break;
1472 	}
1473 
1474 	fputs(s, fp);
1475 }
1476 
1477 static int symbol__annotate_fprintf2(struct symbol *sym, FILE *fp,
1478 				     struct annotation_print_data *apd)
1479 {
1480 	struct annotation *notes = symbol__annotation(sym);
1481 	struct annotation_write_ops wops = {
1482 		.first_line		 = true,
1483 		.obj			 = fp,
1484 		.set_color		 = FILE__set_color,
1485 		.set_percent_color	 = FILE__set_percent_color,
1486 		.set_jumps_percent_color = FILE__set_jumps_percent_color,
1487 		.printf			 = FILE__printf,
1488 		.write_graph		 = FILE__write_graph,
1489 	};
1490 	struct annotation_line *al;
1491 
1492 	if (annotate_opts.code_with_type) {
1493 		map_symbol__get_arch(&apd->he->ms, &apd->arch);
1494 		apd->dbg = dso__debuginfo(map__dso(apd->he->ms.map));
1495 	}
1496 
1497 	list_for_each_entry(al, &notes->src->source, node) {
1498 		if (annotation_line__filter(al))
1499 			continue;
1500 		annotation_line__write(al, notes, &wops, apd);
1501 		fputc('\n', fp);
1502 		wops.first_line = false;
1503 	}
1504 
1505 	if (annotate_opts.code_with_type)
1506 		debuginfo__delete(apd->dbg);
1507 
1508 	return 0;
1509 }
1510 
1511 int map_symbol__annotation_dump(struct map_symbol *ms, struct evsel *evsel,
1512 				struct hist_entry *he)
1513 {
1514 	const char *ev_name = evsel__name(evsel);
1515 	char buf[1024];
1516 	char *filename;
1517 	int err = -1;
1518 	FILE *fp;
1519 	struct annotation_print_data apd = {
1520 		.he = he,
1521 		.evsel = evsel,
1522 	};
1523 
1524 	if (asprintf(&filename, "%s.annotation", ms->sym->name) < 0)
1525 		return -1;
1526 
1527 	fp = fopen(filename, "w");
1528 	if (fp == NULL)
1529 		goto out_free_filename;
1530 
1531 	if (evsel__is_group_event(evsel)) {
1532 		evsel__group_desc(evsel, buf, sizeof(buf));
1533 		ev_name = buf;
1534 	}
1535 
1536 	fprintf(fp, "%s() %s\nEvent: %s\n\n",
1537 		ms->sym->name, dso__long_name(map__dso(ms->map)), ev_name);
1538 	symbol__annotate_fprintf2(ms->sym, fp, &apd);
1539 
1540 	fclose(fp);
1541 	err = 0;
1542 out_free_filename:
1543 	free(filename);
1544 	return err;
1545 }
1546 
1547 void symbol__annotate_zero_histogram(struct symbol *sym, struct evsel *evsel)
1548 {
1549 	struct annotation *notes = symbol__annotation(sym);
1550 	struct sym_hist *h = annotation__histogram(notes, evsel);
1551 
1552 	memset(h, 0, sizeof(*notes->src->histograms) * notes->src->nr_histograms);
1553 }
1554 
1555 void symbol__annotate_decay_histogram(struct symbol *sym, struct evsel *evsel)
1556 {
1557 	struct annotation *notes = symbol__annotation(sym);
1558 	struct sym_hist *h = annotation__histogram(notes, evsel);
1559 	struct annotation_line *al;
1560 
1561 	h->nr_samples = 0;
1562 	list_for_each_entry(al, &notes->src->source, node) {
1563 		struct sym_hist_entry *entry;
1564 
1565 		if (al->offset == -1)
1566 			continue;
1567 
1568 		entry = annotated_source__hist_entry(notes->src, evsel, al->offset);
1569 		if (entry == NULL)
1570 			continue;
1571 
1572 		entry->nr_samples = entry->nr_samples * 7 / 8;
1573 		h->nr_samples += entry->nr_samples;
1574 	}
1575 }
1576 
1577 void annotated_source__purge(struct annotated_source *as)
1578 {
1579 	struct annotation_line *al, *n;
1580 
1581 	list_for_each_entry_safe(al, n, &as->source, node) {
1582 		list_del_init(&al->node);
1583 		disasm_line__free(disasm_line(al));
1584 	}
1585 	as->tried_source = false;
1586 }
1587 
1588 static size_t disasm_line__fprintf(struct disasm_line *dl, FILE *fp)
1589 {
1590 	size_t printed;
1591 
1592 	if (dl->al.offset == -1)
1593 		return fprintf(fp, "%s\n", dl->al.line);
1594 
1595 	printed = fprintf(fp, "%#" PRIx64 " %s", dl->al.offset, dl->ins.name);
1596 
1597 	if (dl->ops.raw[0] != '\0') {
1598 		printed += fprintf(fp, "%.*s %s\n", 6 - (int)printed, " ",
1599 				   dl->ops.raw);
1600 	}
1601 
1602 	return printed + fprintf(fp, "\n");
1603 }
1604 
1605 size_t disasm__fprintf(struct list_head *head, FILE *fp)
1606 {
1607 	struct disasm_line *pos;
1608 	size_t printed = 0;
1609 
1610 	list_for_each_entry(pos, head, al.node)
1611 		printed += disasm_line__fprintf(pos, fp);
1612 
1613 	return printed;
1614 }
1615 
1616 bool disasm_line__is_valid_local_jump(struct disasm_line *dl, struct symbol *sym)
1617 {
1618 	if (!dl || !dl->ins.ops || !ins__is_jump(&dl->ins) ||
1619 	    !disasm_line__has_local_offset(dl) || dl->ops.target.offset < 0 ||
1620 	    dl->ops.target.offset >= (s64)symbol__size(sym))
1621 		return false;
1622 
1623 	return true;
1624 }
1625 
1626 static void
1627 annotation__mark_jump_targets(struct annotation *notes, struct symbol *sym)
1628 {
1629 	struct annotation_line *al;
1630 
1631 	/* PLT symbols contain external offsets */
1632 	if (strstr(sym->name, "@plt"))
1633 		return;
1634 
1635 	list_for_each_entry(al, &notes->src->source, node) {
1636 		struct disasm_line *dl;
1637 		struct annotation_line *target;
1638 
1639 		dl = disasm_line(al);
1640 
1641 		if (!disasm_line__is_valid_local_jump(dl, sym))
1642 			continue;
1643 
1644 		target = annotated_source__get_line(notes->src,
1645 						    dl->ops.target.offset);
1646 		/*
1647 		 * FIXME: Oops, no jump target? Buggy disassembler? Or do we
1648 		 * have to adjust to the previous offset?
1649 		 */
1650 		if (target == NULL)
1651 			continue;
1652 
1653 		if (++target->jump_sources > notes->src->max_jump_sources)
1654 			notes->src->max_jump_sources = target->jump_sources;
1655 	}
1656 }
1657 
1658 static void annotation__set_index(struct annotation *notes)
1659 {
1660 	struct annotation_line *al;
1661 	struct annotated_source *src = notes->src;
1662 
1663 	src->widths.max_line_len = 0;
1664 	src->nr_entries = 0;
1665 	src->nr_asm_entries = 0;
1666 
1667 	list_for_each_entry(al, &src->source, node) {
1668 		size_t line_len = strlen(al->line);
1669 
1670 		if (src->widths.max_line_len < line_len)
1671 			src->widths.max_line_len = line_len;
1672 		al->idx = src->nr_entries++;
1673 		if (al->offset != -1)
1674 			al->idx_asm = src->nr_asm_entries++;
1675 		else
1676 			al->idx_asm = -1;
1677 	}
1678 }
1679 
1680 static inline int width_jumps(int n)
1681 {
1682 	if (n >= 100)
1683 		return 5;
1684 	if (n / 10)
1685 		return 2;
1686 	return 1;
1687 }
1688 
1689 static int annotation__max_ins_name(struct annotation *notes)
1690 {
1691 	int max_name = 0, len;
1692 	struct annotation_line *al;
1693 
1694         list_for_each_entry(al, &notes->src->source, node) {
1695 		if (al->offset == -1)
1696 			continue;
1697 
1698 		len = strlen(disasm_line(al)->ins.name);
1699 		if (max_name < len)
1700 			max_name = len;
1701 	}
1702 
1703 	return max_name;
1704 }
1705 
1706 static void
1707 annotation__init_column_widths(struct annotation *notes, struct symbol *sym)
1708 {
1709 	notes->src->widths.addr = notes->src->widths.target =
1710 		notes->src->widths.min_addr = hex_width(symbol__size(sym));
1711 	notes->src->widths.max_addr = hex_width(sym->end);
1712 	notes->src->widths.jumps = width_jumps(notes->src->max_jump_sources);
1713 	notes->src->widths.max_ins_name = annotation__max_ins_name(notes);
1714 }
1715 
1716 void annotation__update_column_widths(struct annotation *notes)
1717 {
1718 	if (annotate_opts.use_offset)
1719 		notes->src->widths.target = notes->src->widths.min_addr;
1720 	else if (annotate_opts.full_addr)
1721 		notes->src->widths.target = BITS_PER_LONG / 4;
1722 	else
1723 		notes->src->widths.target = notes->src->widths.max_addr;
1724 
1725 	notes->src->widths.addr = notes->src->widths.target;
1726 
1727 	if (annotate_opts.show_nr_jumps)
1728 		notes->src->widths.addr += notes->src->widths.jumps + 1;
1729 }
1730 
1731 void annotation__toggle_full_addr(struct annotation *notes, struct map_symbol *ms)
1732 {
1733 	annotate_opts.full_addr = !annotate_opts.full_addr;
1734 
1735 	if (annotate_opts.full_addr)
1736 		notes->src->start = map__objdump_2mem(ms->map, ms->sym->start);
1737 	else
1738 		notes->src->start = map__rip_2objdump(ms->map, ms->sym->start);
1739 
1740 	annotation__update_column_widths(notes);
1741 }
1742 
1743 static void annotation__calc_lines(struct annotation *notes, struct map_symbol *ms,
1744 				   struct rb_root *root)
1745 {
1746 	struct annotation_line *al;
1747 	struct rb_root tmp_root = RB_ROOT;
1748 
1749 	list_for_each_entry(al, &notes->src->source, node) {
1750 		double percent_max = 0.0;
1751 		u64 addr;
1752 		int i;
1753 
1754 		for (i = 0; i < al->data_nr; i++) {
1755 			double percent;
1756 
1757 			percent = annotation_data__percent(&al->data[i],
1758 							   annotate_opts.percent_type);
1759 
1760 			if (percent > percent_max)
1761 				percent_max = percent;
1762 		}
1763 
1764 		if (percent_max <= 0.5)
1765 			continue;
1766 
1767 		addr = map__rip_2objdump(ms->map, ms->sym->start);
1768 		al->path = get_srcline(map__dso(ms->map), addr + al->offset, NULL,
1769 				       false, true, ms->sym->start + al->offset);
1770 		insert_source_line(&tmp_root, al);
1771 	}
1772 
1773 	resort_source_line(root, &tmp_root);
1774 }
1775 
1776 static void symbol__calc_lines(struct map_symbol *ms, struct rb_root *root)
1777 {
1778 	struct annotation *notes = symbol__annotation(ms->sym);
1779 
1780 	annotation__calc_lines(notes, ms, root);
1781 }
1782 
1783 int hist_entry__tty_annotate2(struct hist_entry *he, struct evsel *evsel)
1784 {
1785 	struct map_symbol *ms = &he->ms;
1786 	struct dso *dso = map__dso(ms->map);
1787 	struct symbol *sym = ms->sym;
1788 	struct rb_root source_line = RB_ROOT;
1789 	struct hists *hists = evsel__hists(evsel);
1790 	struct annotation_print_data apd = {
1791 		.he = he,
1792 		.evsel = evsel,
1793 	};
1794 	char buf[1024];
1795 	int err;
1796 
1797 	err = symbol__annotate2(ms, evsel, NULL);
1798 	if (err) {
1799 		char msg[BUFSIZ];
1800 
1801 		dso__set_annotate_warned(dso);
1802 		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
1803 		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
1804 		return -1;
1805 	}
1806 
1807 	if (annotate_opts.print_lines) {
1808 		srcline_full_filename = annotate_opts.full_path;
1809 		symbol__calc_lines(ms, &source_line);
1810 		print_summary(&source_line, dso__long_name(dso));
1811 	}
1812 
1813 	hists__scnprintf_title(hists, buf, sizeof(buf));
1814 	fprintf(stdout, "%s, [percent: %s]\n%s() %s\n",
1815 		buf, percent_type_str(annotate_opts.percent_type), sym->name, dso__long_name(dso));
1816 	symbol__annotate_fprintf2(sym, stdout, &apd);
1817 
1818 	annotated_source__purge(symbol__annotation(sym)->src);
1819 
1820 	return 0;
1821 }
1822 
1823 int hist_entry__tty_annotate(struct hist_entry *he, struct evsel *evsel)
1824 {
1825 	struct map_symbol *ms = &he->ms;
1826 	struct dso *dso = map__dso(ms->map);
1827 	struct symbol *sym = ms->sym;
1828 	struct rb_root source_line = RB_ROOT;
1829 	int err;
1830 
1831 	err = symbol__annotate(ms, evsel, NULL);
1832 	if (err) {
1833 		char msg[BUFSIZ];
1834 
1835 		dso__set_annotate_warned(dso);
1836 		symbol__strerror_disassemble(ms, err, msg, sizeof(msg));
1837 		ui__error("Couldn't annotate %s:\n%s", sym->name, msg);
1838 		return -1;
1839 	}
1840 
1841 	symbol__calc_percent(sym, evsel);
1842 
1843 	if (annotate_opts.print_lines) {
1844 		srcline_full_filename = annotate_opts.full_path;
1845 		symbol__calc_lines(ms, &source_line);
1846 		print_summary(&source_line, dso__long_name(dso));
1847 	}
1848 
1849 	hist_entry__annotate_printf(he, evsel);
1850 
1851 	annotated_source__purge(symbol__annotation(sym)->src);
1852 
1853 	return 0;
1854 }
1855 
1856 bool ui__has_annotation(void)
1857 {
1858 	return use_browser == 1 && perf_hpp_list.sym;
1859 }
1860 
1861 
1862 static double annotation_line__max_percent(struct annotation_line *al,
1863 					   unsigned int percent_type)
1864 {
1865 	double percent_max = 0.0;
1866 	int i;
1867 
1868 	for (i = 0; i < al->data_nr; i++) {
1869 		double percent;
1870 
1871 		percent = annotation_data__percent(&al->data[i],
1872 						   percent_type);
1873 
1874 		if (percent > percent_max)
1875 			percent_max = percent;
1876 	}
1877 
1878 	return percent_max;
1879 }
1880 
1881 static int disasm_line__write(struct disasm_line *dl, struct annotation *notes,
1882 			       void *obj, char *bf, size_t size,
1883 			       void (*obj__printf)(void *obj, const char *fmt, ...),
1884 			       void (*obj__write_graph)(void *obj, int graph))
1885 {
1886 	if (dl->ins.ops && dl->ins.ops->scnprintf) {
1887 		if (ins__is_jump(&dl->ins)) {
1888 			bool fwd;
1889 
1890 			if (dl->ops.target.outside)
1891 				goto call_like;
1892 			fwd = dl->ops.target.offset > dl->al.offset;
1893 			obj__write_graph(obj, fwd ? DARROW_CHAR : UARROW_CHAR);
1894 			obj__printf(obj, " ");
1895 		} else if (ins__is_call(&dl->ins)) {
1896 call_like:
1897 			obj__write_graph(obj, RARROW_CHAR);
1898 			obj__printf(obj, " ");
1899 		} else if (ins__is_ret(&dl->ins)) {
1900 			obj__write_graph(obj, LARROW_CHAR);
1901 			obj__printf(obj, " ");
1902 		} else {
1903 			obj__printf(obj, "  ");
1904 		}
1905 	} else {
1906 		obj__printf(obj, "  ");
1907 	}
1908 
1909 	return disasm_line__scnprintf(dl, bf, size, !annotate_opts.use_offset,
1910 				      notes->src->widths.max_ins_name) + 2;
1911 }
1912 
1913 static void ipc_coverage_string(char *bf, int size, struct annotation *notes)
1914 {
1915 	double ipc = 0.0, coverage = 0.0;
1916 	struct annotated_branch *branch = annotation__get_branch(notes);
1917 
1918 	if (branch && branch->hit_cycles)
1919 		ipc = branch->hit_insn / ((double)branch->hit_cycles);
1920 
1921 	if (branch && branch->total_insn) {
1922 		coverage = branch->cover_insn * 100.0 /
1923 			((double)branch->total_insn);
1924 	}
1925 
1926 	scnprintf(bf, size, "(Average IPC: %.2f, IPC Coverage: %.1f%%)",
1927 		  ipc, coverage);
1928 }
1929 
1930 int annotation_br_cntr_abbr_list(char **str, struct evsel *evsel, bool header)
1931 {
1932 	struct evsel *pos;
1933 	struct strbuf sb;
1934 
1935 	if (evlist__nr_br_cntr(evsel->evlist) <= 0)
1936 		return -ENOTSUP;
1937 
1938 	strbuf_init(&sb, /*hint=*/ 0);
1939 
1940 	if (header && strbuf_addf(&sb, "# Branch counter abbr list:\n"))
1941 		goto err;
1942 
1943 	evlist__for_each_entry(evsel->evlist, pos) {
1944 		if (!(pos->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS))
1945 			continue;
1946 		if (header && strbuf_addf(&sb, "#"))
1947 			goto err;
1948 
1949 		if (strbuf_addf(&sb, " %s = %s\n", pos->name, pos->abbr_name))
1950 			goto err;
1951 	}
1952 
1953 	if (header && strbuf_addf(&sb, "#"))
1954 		goto err;
1955 	if (strbuf_addf(&sb, " '-' No event occurs\n"))
1956 		goto err;
1957 
1958 	if (header && strbuf_addf(&sb, "#"))
1959 		goto err;
1960 	if (strbuf_addf(&sb, " '+' Event occurrences may be lost due to branch counter saturated\n"))
1961 		goto err;
1962 
1963 	*str = strbuf_detach(&sb, NULL);
1964 
1965 	return 0;
1966 err:
1967 	strbuf_release(&sb);
1968 	return -ENOMEM;
1969 }
1970 
1971 /* Assume the branch counter saturated at 3 */
1972 #define ANNOTATION_BR_CNTR_SATURATION		3
1973 
1974 int annotation_br_cntr_entry(char **str, int br_cntr_nr,
1975 			     u64 *br_cntr, int num_aggr,
1976 			     struct evsel *evsel)
1977 {
1978 	struct evsel *pos = evsel ? evlist__first(evsel->evlist) : NULL;
1979 	bool saturated = false;
1980 	int i, j, avg, used;
1981 	struct strbuf sb;
1982 
1983 	strbuf_init(&sb, /*hint=*/ 0);
1984 	for (i = 0; i < br_cntr_nr; i++) {
1985 		used = 0;
1986 		avg = ceil((double)(br_cntr[i] & ~ANNOTATION__BR_CNTR_SATURATED_FLAG) /
1987 			   (double)num_aggr);
1988 
1989 		/*
1990 		 * A histogram with the abbr name is displayed by default.
1991 		 * With -v, the exact number of branch counter is displayed.
1992 		 */
1993 		if (verbose) {
1994 			evlist__for_each_entry_from(evsel->evlist, pos) {
1995 				if ((pos->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) &&
1996 				    (pos->br_cntr_idx == i))
1997 				break;
1998 			}
1999 			if (strbuf_addstr(&sb, pos->abbr_name))
2000 				goto err;
2001 
2002 			if (!br_cntr[i]) {
2003 				if (strbuf_addstr(&sb, "=-"))
2004 					goto err;
2005 			} else {
2006 				if (strbuf_addf(&sb, "=%d", avg))
2007 					goto err;
2008 			}
2009 			if (br_cntr[i] & ANNOTATION__BR_CNTR_SATURATED_FLAG) {
2010 				if (strbuf_addch(&sb, '+'))
2011 					goto err;
2012 			} else {
2013 				if (strbuf_addch(&sb, ' '))
2014 					goto err;
2015 			}
2016 
2017 			if ((i < br_cntr_nr - 1) && strbuf_addch(&sb, ','))
2018 				goto err;
2019 			continue;
2020 		}
2021 
2022 		if (strbuf_addch(&sb, '|'))
2023 			goto err;
2024 
2025 		if (!br_cntr[i]) {
2026 			if (strbuf_addch(&sb, '-'))
2027 				goto err;
2028 			used++;
2029 		} else {
2030 			evlist__for_each_entry_from(evsel->evlist, pos) {
2031 				if ((pos->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) &&
2032 				    (pos->br_cntr_idx == i))
2033 					break;
2034 			}
2035 			if (br_cntr[i] & ANNOTATION__BR_CNTR_SATURATED_FLAG)
2036 				saturated = true;
2037 
2038 			for (j = 0; j < avg; j++, used++) {
2039 				/* Print + if the number of logged events > 3 */
2040 				if (j >= ANNOTATION_BR_CNTR_SATURATION) {
2041 					saturated = true;
2042 					break;
2043 				}
2044 				if (strbuf_addstr(&sb, pos->abbr_name))
2045 					goto err;
2046 			}
2047 
2048 			if (saturated) {
2049 				if (strbuf_addch(&sb, '+'))
2050 					goto err;
2051 				used++;
2052 			}
2053 			pos = list_next_entry(pos, core.node);
2054 		}
2055 
2056 		for (j = used; j < ANNOTATION_BR_CNTR_SATURATION + 1; j++) {
2057 			if (strbuf_addch(&sb, ' '))
2058 				goto err;
2059 		}
2060 	}
2061 
2062 	if (!verbose && strbuf_addch(&sb, br_cntr_nr ? '|' : ' '))
2063 		goto err;
2064 
2065 	*str = strbuf_detach(&sb, NULL);
2066 
2067 	return 0;
2068 err:
2069 	strbuf_release(&sb);
2070 	return -ENOMEM;
2071 }
2072 
2073 struct type_hash_entry {
2074 	struct annotated_data_type *type;
2075 	int offset;
2076 };
2077 
2078 static int disasm_line__snprint_type_info(struct disasm_line *dl,
2079 					  char *buf, int len,
2080 					  struct annotation_print_data *apd)
2081 {
2082 	struct annotated_data_type *data_type = NULL;
2083 	struct type_hash_entry *entry = NULL;
2084 	char member[256];
2085 	int offset = 0;
2086 	int printed;
2087 
2088 	scnprintf(buf, len, " ");
2089 
2090 	if (!annotate_opts.code_with_type || apd->dbg == NULL)
2091 		return 1;
2092 
2093 	if (apd->type_hash) {
2094 		hashmap__find(apd->type_hash, dl->al.offset, &entry);
2095 		if (entry != NULL) {
2096 			data_type = entry->type;
2097 			offset = entry->offset;
2098 		}
2099 	}
2100 
2101 	if (data_type == NULL)
2102 		data_type = __hist_entry__get_data_type(apd->he, apd->arch, apd->dbg, dl, &offset);
2103 
2104 	if (apd->type_hash && entry == NULL) {
2105 		entry = malloc(sizeof(*entry));
2106 		if (entry != NULL) {
2107 			entry->type = data_type;
2108 			entry->offset = offset;
2109 			hashmap__add(apd->type_hash, dl->al.offset, entry);
2110 		}
2111 	}
2112 
2113 	if (!needs_type_info(data_type))
2114 		return 1;
2115 
2116 	printed = scnprintf(buf, len, "\t\t# data-type: %s", data_type->self.type_name);
2117 
2118 	if (data_type != &stackop_type && data_type != &canary_type && len > printed)
2119 		printed += scnprintf(buf + printed, len - printed, " +%#x", offset);
2120 
2121 	if (annotated_data_type__get_member_name(data_type, member, sizeof(member), offset) &&
2122 	    len > printed) {
2123 		printed += scnprintf(buf + printed, len - printed, " (%s)", member);
2124 	}
2125 	return printed;
2126 }
2127 
2128 void annotation_line__write(struct annotation_line *al,
2129 			    struct annotation *notes,
2130 			    const struct annotation_write_ops *wops,
2131 			    struct annotation_print_data *apd)
2132 {
2133 	bool current_entry = wops->current_entry;
2134 	bool change_color = wops->change_color;
2135 	double percent_max = annotation_line__max_percent(al, annotate_opts.percent_type);
2136 	int width = wops->width;
2137 	int pcnt_width = annotation__pcnt_width(notes, apd->evsel);
2138 	u8 weight_mask = annotation__weight_mask(notes, apd->evsel);
2139 	int cycles_width = annotation__cycles_width(notes);
2140 	bool show_title = false;
2141 	char bf[256];
2142 	int printed;
2143 	void *obj = wops->obj;
2144 	int  (*obj__set_color)(void *obj, int color) = wops->set_color;
2145 	void (*obj__set_percent_color)(void *obj, double percent, bool current) = wops->set_percent_color;
2146 	int  (*obj__set_jumps_percent_color)(void *obj, int nr, bool current) = wops->set_jumps_percent_color;
2147 	void (*obj__printf)(void *obj, const char *fmt, ...) = wops->printf;
2148 	void (*obj__write_graph)(void *obj, int graph) = wops->write_graph;
2149 
2150 	if (wops->first_line && (al->offset == -1 || percent_max == 0.0)) {
2151 		if (notes->branch && al->cycles) {
2152 			if (al->cycles->ipc == 0.0 && al->cycles->avg == 0)
2153 				show_title = true;
2154 		} else
2155 			show_title = true;
2156 	}
2157 
2158 	if (al->offset != -1 && percent_max != 0.0) {
2159 		int i;
2160 
2161 		for (i = 0; i < al->data_nr; i++) {
2162 			double percent;
2163 			int weight;
2164 
2165 			percent = annotation_data__percent(&al->data[i],
2166 							   annotate_opts.percent_type);
2167 
2168 			obj__set_percent_color(obj, percent, current_entry);
2169 			if (symbol_conf.show_total_period) {
2170 				obj__printf(obj, "%11" PRIu64 " ", al->data[i].he.period);
2171 			} else if (symbol_conf.show_nr_samples) {
2172 				obj__printf(obj, "%7" PRIu64 " ",
2173 						   al->data[i].he.nr_samples);
2174 			} else {
2175 				obj__printf(obj, "%7.2f ", percent);
2176 			}
2177 
2178 			for_each_weight(weight) {
2179 				if (weight_mask & BIT(weight))
2180 					obj__printf(obj, "%7" PRIu64 " ",
2181 						    al->data[i].he.weight_num[weight] ?
2182 						    al->data[i].he.weight_sum[weight] /
2183 						    al->data[i].he.weight_num[weight] :
2184 						    0);
2185 			}
2186 		}
2187 	} else {
2188 		obj__set_percent_color(obj, 0, current_entry);
2189 
2190 		if (!show_title)
2191 			obj__printf(obj, "%-*s", pcnt_width, " ");
2192 		else {
2193 			char buf[64];
2194 			annotation__column_title(buf, sizeof(buf), notes, apd->evsel);
2195 			obj__printf(obj, "%-*s", pcnt_width, buf);
2196 		}
2197 	}
2198 	width -= pcnt_width;
2199 
2200 	if (notes->branch) {
2201 		if (al->cycles && al->cycles->ipc)
2202 			obj__printf(obj, "%*.2f ", ANNOTATION__IPC_WIDTH - 1, al->cycles->ipc);
2203 		else if (!show_title)
2204 			obj__printf(obj, "%*s", ANNOTATION__IPC_WIDTH, " ");
2205 		else
2206 			obj__printf(obj, "%*s ", ANNOTATION__IPC_WIDTH - 1, "IPC");
2207 
2208 		if (!annotate_opts.show_minmax_cycle) {
2209 			if (al->cycles && al->cycles->avg)
2210 				obj__printf(obj, "%*" PRIu64 " ",
2211 					   ANNOTATION__CYCLES_WIDTH - 1, al->cycles->avg);
2212 			else if (!show_title)
2213 				obj__printf(obj, "%*s",
2214 					    ANNOTATION__CYCLES_WIDTH, " ");
2215 			else
2216 				obj__printf(obj, "%*s ",
2217 					    ANNOTATION__CYCLES_WIDTH - 1,
2218 					    "Cycle");
2219 		} else {
2220 			if (al->cycles) {
2221 				char str[32];
2222 
2223 				scnprintf(str, sizeof(str),
2224 					"%" PRIu64 "(%" PRIu64 "/%" PRIu64 ")",
2225 					al->cycles->avg, al->cycles->min,
2226 					al->cycles->max);
2227 
2228 				obj__printf(obj, "%*s ",
2229 					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
2230 					    str);
2231 			} else if (!show_title)
2232 				obj__printf(obj, "%*s",
2233 					    ANNOTATION__MINMAX_CYCLES_WIDTH,
2234 					    " ");
2235 			else
2236 				obj__printf(obj, "%*s ",
2237 					    ANNOTATION__MINMAX_CYCLES_WIDTH - 1,
2238 					    "Cycle(min/max)");
2239 		}
2240 
2241 		if (annotate_opts.show_br_cntr) {
2242 			if (show_title) {
2243 				obj__printf(obj, "%*s ",
2244 					    ANNOTATION__BR_CNTR_WIDTH,
2245 					    "Branch Counter");
2246 			} else {
2247 				char *buf;
2248 
2249 				if (!annotation_br_cntr_entry(&buf, al->br_cntr_nr, al->br_cntr,
2250 							      al->num_aggr, al->evsel)) {
2251 					obj__printf(obj, "%*s ", ANNOTATION__BR_CNTR_WIDTH, buf);
2252 					free(buf);
2253 				}
2254 			}
2255 		}
2256 
2257 		if (show_title && !*al->line) {
2258 			ipc_coverage_string(bf, sizeof(bf), notes);
2259 			obj__printf(obj, "%*s", ANNOTATION__AVG_IPC_WIDTH, bf);
2260 		}
2261 	}
2262 	width -= cycles_width;
2263 
2264 	obj__printf(obj, " ");
2265 	width -= 1;
2266 
2267 	if (!*al->line)
2268 		obj__printf(obj, "%-*s", width, " ");
2269 	else if (al->offset == -1) {
2270 		if (al->line_nr && annotate_opts.show_linenr)
2271 			printed = scnprintf(bf, sizeof(bf), "%-*d ",
2272 					    notes->src->widths.addr + 1, al->line_nr);
2273 		else
2274 			printed = scnprintf(bf, sizeof(bf), "%-*s  ",
2275 					    notes->src->widths.addr, " ");
2276 		obj__printf(obj, bf);
2277 		width -= printed;
2278 		obj__printf(obj, "%-*s", width, al->line);
2279 	} else {
2280 		u64 addr = al->offset;
2281 		int color = -1;
2282 
2283 		if (!annotate_opts.use_offset)
2284 			addr += notes->src->start;
2285 
2286 		if (!annotate_opts.use_offset) {
2287 			printed = scnprintf(bf, sizeof(bf), "%" PRIx64 ": ", addr);
2288 		} else {
2289 			if (al->jump_sources &&
2290 			    annotate_opts.offset_level >= ANNOTATION__OFFSET_JUMP_TARGETS) {
2291 				if (annotate_opts.show_nr_jumps) {
2292 					int prev;
2293 					printed = scnprintf(bf, sizeof(bf), "%*d ",
2294 							    notes->src->widths.jumps,
2295 							    al->jump_sources);
2296 					prev = obj__set_jumps_percent_color(obj, al->jump_sources,
2297 									    current_entry);
2298 					obj__printf(obj, bf);
2299 					obj__set_color(obj, prev);
2300 				}
2301 print_addr:
2302 				printed = scnprintf(bf, sizeof(bf), "%*" PRIx64 ": ",
2303 						    notes->src->widths.target, addr);
2304 			} else if (ins__is_call(&disasm_line(al)->ins) &&
2305 				   annotate_opts.offset_level >= ANNOTATION__OFFSET_CALL) {
2306 				goto print_addr;
2307 			} else if (annotate_opts.offset_level == ANNOTATION__MAX_OFFSET_LEVEL) {
2308 				goto print_addr;
2309 			} else {
2310 				printed = scnprintf(bf, sizeof(bf), "%-*s  ",
2311 						    notes->src->widths.addr, " ");
2312 			}
2313 		}
2314 
2315 		if (change_color)
2316 			color = obj__set_color(obj, HE_COLORSET_ADDR);
2317 		obj__printf(obj, bf);
2318 		if (change_color)
2319 			obj__set_color(obj, color);
2320 
2321 		width -= printed;
2322 
2323 		printed = disasm_line__write(disasm_line(al), notes, obj, bf, sizeof(bf),
2324 					     obj__printf, obj__write_graph);
2325 
2326 		obj__printf(obj, "%s", bf);
2327 		width -= printed;
2328 
2329 		disasm_line__snprint_type_info(disasm_line(al), bf, sizeof(bf), apd);
2330 		obj__printf(obj, "%-*s", width, bf);
2331 	}
2332 
2333 }
2334 
2335 int symbol__annotate2(struct map_symbol *ms, struct evsel *evsel,
2336 		      const struct arch **parch)
2337 {
2338 	struct symbol *sym = ms->sym;
2339 	struct annotation *notes = symbol__annotation(sym);
2340 	size_t size = symbol__size(sym);
2341 	int err;
2342 
2343 	err = symbol__annotate(ms, evsel, parch);
2344 	if (err)
2345 		return err;
2346 
2347 	symbol__calc_percent(sym, evsel);
2348 
2349 	annotation__set_index(notes);
2350 	annotation__mark_jump_targets(notes, sym);
2351 
2352 	err = annotation__compute_ipc(notes, size, evsel);
2353 	if (err)
2354 		return err;
2355 
2356 	annotation__init_column_widths(notes, sym);
2357 	annotation__update_column_widths(notes);
2358 	symbol__set_annotate2(sym, true);
2359 
2360 	return 0;
2361 }
2362 
2363 const char * const perf_disassembler__strs[] = {
2364 	[PERF_DISASM_UNKNOWN]  = "unknown",
2365 	[PERF_DISASM_LLVM]     = "llvm",
2366 	[PERF_DISASM_CAPSTONE] = "capstone",
2367 	[PERF_DISASM_OBJDUMP]  = "objdump",
2368 };
2369 
2370 
2371 static void annotation_options__add_disassembler(struct annotation_options *options,
2372 						 enum perf_disassembler dis)
2373 {
2374 	for (u8 i = 0; i < ARRAY_SIZE(options->disassemblers); i++) {
2375 		if (options->disassemblers[i] == dis) {
2376 			/* Disassembler is already present then don't add again. */
2377 			return;
2378 		}
2379 		if (options->disassemblers[i] == PERF_DISASM_UNKNOWN) {
2380 			/* Found a free slot. */
2381 			options->disassemblers[i] = dis;
2382 			return;
2383 		}
2384 	}
2385 	pr_err("Failed to add disassembler %d\n", dis);
2386 }
2387 
2388 static int annotation_options__add_disassemblers_str(struct annotation_options *options,
2389 						const char *str)
2390 {
2391 	while (str && *str != '\0') {
2392 		const char *comma = strchr(str, ',');
2393 		int len = comma ? comma - str : (int)strlen(str);
2394 		bool match = false;
2395 
2396 		for (u8 i = 0; i < ARRAY_SIZE(perf_disassembler__strs); i++) {
2397 			const char *dis_str = perf_disassembler__strs[i];
2398 
2399 			if (len == (int)strlen(dis_str) && !strncmp(str, dis_str, len)) {
2400 				annotation_options__add_disassembler(options, i);
2401 				match = true;
2402 				break;
2403 			}
2404 		}
2405 		if (!match) {
2406 			pr_err("Invalid disassembler '%.*s'\n", len, str);
2407 			return -1;
2408 		}
2409 		str = comma ? comma + 1 : NULL;
2410 	}
2411 	return 0;
2412 }
2413 
2414 static int annotation__config(const char *var, const char *value, void *data)
2415 {
2416 	struct annotation_options *opt = data;
2417 
2418 	if (!strstarts(var, "annotate."))
2419 		return 0;
2420 
2421 	if (!strcmp(var, "annotate.offset_level")) {
2422 		perf_config_u8(&opt->offset_level, "offset_level", value);
2423 
2424 		if (opt->offset_level > ANNOTATION__MAX_OFFSET_LEVEL)
2425 			opt->offset_level = ANNOTATION__MAX_OFFSET_LEVEL;
2426 		else if (opt->offset_level < ANNOTATION__MIN_OFFSET_LEVEL)
2427 			opt->offset_level = ANNOTATION__MIN_OFFSET_LEVEL;
2428 	} else if (!strcmp(var, "annotate.disassemblers")) {
2429 		int err = annotation_options__add_disassemblers_str(opt, value);
2430 
2431 		if (err)
2432 			return err;
2433 	} else if (!strcmp(var, "annotate.hide_src_code")) {
2434 		opt->hide_src_code = perf_config_bool("hide_src_code", value);
2435 	} else if (!strcmp(var, "annotate.jump_arrows")) {
2436 		opt->jump_arrows = perf_config_bool("jump_arrows", value);
2437 	} else if (!strcmp(var, "annotate.show_linenr")) {
2438 		opt->show_linenr = perf_config_bool("show_linenr", value);
2439 	} else if (!strcmp(var, "annotate.show_nr_jumps")) {
2440 		opt->show_nr_jumps = perf_config_bool("show_nr_jumps", value);
2441 	} else if (!strcmp(var, "annotate.show_nr_samples")) {
2442 		symbol_conf.show_nr_samples = perf_config_bool("show_nr_samples",
2443 								value);
2444 	} else if (!strcmp(var, "annotate.show_total_period")) {
2445 		symbol_conf.show_total_period = perf_config_bool("show_total_period",
2446 								value);
2447 	} else if (!strcmp(var, "annotate.use_offset")) {
2448 		opt->use_offset = perf_config_bool("use_offset", value);
2449 	} else if (!strcmp(var, "annotate.disassembler_style")) {
2450 		opt->disassembler_style = strdup(value);
2451 		if (!opt->disassembler_style) {
2452 			pr_err("Not enough memory for annotate.disassembler_style\n");
2453 			return -1;
2454 		}
2455 	} else if (!strcmp(var, "annotate.objdump")) {
2456 		opt->objdump_path = strdup(value);
2457 		if (!opt->objdump_path) {
2458 			pr_err("Not enough memory for annotate.objdump\n");
2459 			return -1;
2460 		}
2461 	} else if (!strcmp(var, "annotate.addr2line")) {
2462 		symbol_conf.addr2line_path = strdup(value);
2463 		if (!symbol_conf.addr2line_path) {
2464 			pr_err("Not enough memory for annotate.addr2line\n");
2465 			return -1;
2466 		}
2467 	} else if (!strcmp(var, "annotate.demangle")) {
2468 		symbol_conf.demangle = perf_config_bool("demangle", value);
2469 	} else if (!strcmp(var, "annotate.demangle_kernel")) {
2470 		symbol_conf.demangle_kernel = perf_config_bool("demangle_kernel", value);
2471 	} else {
2472 		pr_debug("%s variable unknown, ignoring...", var);
2473 	}
2474 
2475 	return 0;
2476 }
2477 
2478 void annotation_options__init(void)
2479 {
2480 	struct annotation_options *opt = &annotate_opts;
2481 
2482 	memset(opt, 0, sizeof(*opt));
2483 
2484 	/* Default values. */
2485 	opt->use_offset = true;
2486 	opt->jump_arrows = true;
2487 	opt->annotate_src = true;
2488 	opt->offset_level = ANNOTATION__OFFSET_JUMP_TARGETS;
2489 	opt->percent_type = PERCENT_PERIOD_LOCAL;
2490 	opt->hide_src_code = true;
2491 	opt->hide_src_code_on_title = true;
2492 }
2493 
2494 void annotation_options__exit(void)
2495 {
2496 	zfree(&annotate_opts.disassembler_style);
2497 	zfree(&annotate_opts.objdump_path);
2498 }
2499 
2500 static void annotation_options__default_init_disassemblers(struct annotation_options *options)
2501 {
2502 	if (options->disassemblers[0] != PERF_DISASM_UNKNOWN) {
2503 		/* Already initialized. */
2504 		return;
2505 	}
2506 #ifdef HAVE_LIBLLVM_SUPPORT
2507 	annotation_options__add_disassembler(options, PERF_DISASM_LLVM);
2508 #endif
2509 #ifdef HAVE_LIBCAPSTONE_SUPPORT
2510 	annotation_options__add_disassembler(options, PERF_DISASM_CAPSTONE);
2511 #endif
2512 	annotation_options__add_disassembler(options, PERF_DISASM_OBJDUMP);
2513 }
2514 
2515 void annotation_config__init(void)
2516 {
2517 	perf_config(annotation__config, &annotate_opts);
2518 	annotation_options__default_init_disassemblers(&annotate_opts);
2519 }
2520 
2521 static unsigned int parse_percent_type(char *str1, char *str2)
2522 {
2523 	unsigned int type = (unsigned int) -1;
2524 
2525 	if (!strcmp("period", str1)) {
2526 		if (!strcmp("local", str2))
2527 			type = PERCENT_PERIOD_LOCAL;
2528 		else if (!strcmp("global", str2))
2529 			type = PERCENT_PERIOD_GLOBAL;
2530 	}
2531 
2532 	if (!strcmp("hits", str1)) {
2533 		if (!strcmp("local", str2))
2534 			type = PERCENT_HITS_LOCAL;
2535 		else if (!strcmp("global", str2))
2536 			type = PERCENT_HITS_GLOBAL;
2537 	}
2538 
2539 	return type;
2540 }
2541 
2542 int annotate_parse_percent_type(const struct option *opt __maybe_unused, const char *_str,
2543 				int unset __maybe_unused)
2544 {
2545 	unsigned int type;
2546 	char *str1, *str2;
2547 	int err = -1;
2548 
2549 	str1 = strdup(_str);
2550 	if (!str1)
2551 		return -ENOMEM;
2552 
2553 	str2 = strchr(str1, '-');
2554 	if (!str2)
2555 		goto out;
2556 
2557 	*str2++ = 0;
2558 
2559 	type = parse_percent_type(str1, str2);
2560 	if (type == (unsigned int) -1)
2561 		type = parse_percent_type(str2, str1);
2562 	if (type != (unsigned int) -1) {
2563 		annotate_opts.percent_type = type;
2564 		err = 0;
2565 	}
2566 
2567 out:
2568 	free(str1);
2569 	return err;
2570 }
2571 
2572 int annotate_check_args(void)
2573 {
2574 	struct annotation_options *args = &annotate_opts;
2575 
2576 	if (args->prefix_strip && !args->prefix) {
2577 		pr_err("--prefix-strip requires --prefix\n");
2578 		return -1;
2579 	}
2580 	return 0;
2581 }
2582 
2583 int arch__dwarf_regnum(const struct arch *arch, const char *str)
2584 {
2585 	const char *p = str;
2586 	char *regname, *q;
2587 	int reg;
2588 
2589 	if (arch->objdump.register_char) {
2590 		p = strchr(str, arch->objdump.register_char);
2591 		if (p == NULL)
2592 			return -1;
2593 	}
2594 
2595 	regname = strdup(p);
2596 	if (regname == NULL)
2597 		return -1;
2598 
2599 	q = strpbrk(regname, ",)] ");
2600 	if (q)
2601 		*q = '\0';
2602 
2603 	reg = get_dwarf_regnum(regname, arch->id.e_machine, arch->id.e_flags);
2604 	free(regname);
2605 	return reg < 0 ? -1 : reg;
2606 }
2607 
2608 /**
2609  * annotate_get_insn_location - Get location of instruction
2610  * @arch: the architecture info
2611  * @dl: the target instruction
2612  * @loc: a buffer to save the data
2613  *
2614  * Get detailed location info (register and offset) in the instruction.
2615  * It needs both source and target operand and whether it accesses a
2616  * memory location.  The offset field is meaningful only when the
2617  * corresponding mem flag is set.  The reg2 field is meaningful only
2618  * when multi_regs flag is set.
2619  *
2620  * Some examples on x86:
2621  *
2622  *   mov  (%rax), %rcx   # src_reg1 = rax, src_mem = 1, src_offset = 0
2623  *                       # dst_reg1 = rcx, dst_mem = 0
2624  *
2625  *   mov  0x18, %r8      # src_reg1 = -1, src_mem = 0
2626  *                       # dst_reg1 = r8, dst_mem = 0
2627  *
2628  *   mov  %rsi, 8(%rbx,%rcx,4)  # src_reg1 = rsi, src_mem = 0, src_multi_regs = 0
2629  *                              # dst_reg1 = rbx, dst_reg2 = rcx, dst_mem = 1
2630  *                              # dst_multi_regs = 1, dst_offset = 8
2631  */
2632 int annotate_get_insn_location(const struct arch *arch, struct disasm_line *dl,
2633 			       struct annotated_insn_loc *loc)
2634 {
2635 	struct ins_operands *ops;
2636 	struct annotated_op_loc *op_loc;
2637 	int i;
2638 
2639 	if (ins__is_lock(&dl->ins))
2640 		ops = dl->ops.locked.ops;
2641 	else
2642 		ops = &dl->ops;
2643 
2644 	if (ops == NULL)
2645 		return -1;
2646 
2647 	memset(loc, 0, sizeof(*loc));
2648 
2649 	for_each_insn_op_loc(loc, i, op_loc) {
2650 		const char *insn_str = ops->source.raw;
2651 		bool multi_regs = ops->source.multi_regs;
2652 		bool mem_ref = ops->source.mem_ref;
2653 
2654 		if (i == INSN_OP_TARGET) {
2655 			insn_str = ops->target.raw;
2656 			multi_regs = ops->target.multi_regs;
2657 			mem_ref = ops->target.mem_ref;
2658 		}
2659 
2660 		/* Invalidate the register by default */
2661 		op_loc->reg1 = -1;
2662 		op_loc->reg2 = -1;
2663 		op_loc->mem_ref = mem_ref;
2664 		op_loc->multi_regs = multi_regs;
2665 
2666 		if (arch->extract_op_location)
2667 			arch->extract_op_location(arch, dl, insn_str, i, op_loc);
2668 	}
2669 
2670 	return 0;
2671 }
2672 
2673 static struct disasm_line *find_disasm_line(struct symbol *sym, u64 ip,
2674 					    bool allow_update)
2675 {
2676 	struct disasm_line *dl;
2677 	struct annotation *notes;
2678 
2679 	notes = symbol__annotation(sym);
2680 
2681 	list_for_each_entry(dl, &notes->src->source, al.node) {
2682 		if (dl->al.offset == -1)
2683 			continue;
2684 
2685 		if (sym->start + dl->al.offset == ip) {
2686 			/*
2687 			 * llvm-objdump places "lock" in a separate line and
2688 			 * in that case, we want to get the next line.
2689 			 */
2690 			if (ins__is_lock(&dl->ins) &&
2691 			    *dl->ops.raw == '\0' && allow_update) {
2692 				ip++;
2693 				continue;
2694 			}
2695 			return dl;
2696 		}
2697 	}
2698 	return NULL;
2699 }
2700 
2701 static struct annotated_item_stat *annotate_data_stat(struct list_head *head,
2702 						      const char *name)
2703 {
2704 	struct annotated_item_stat *istat;
2705 
2706 	list_for_each_entry(istat, head, list) {
2707 		if (!strcmp(istat->name, name))
2708 			return istat;
2709 	}
2710 
2711 	istat = zalloc(sizeof(*istat));
2712 	if (istat == NULL)
2713 		return NULL;
2714 
2715 	istat->name = strdup(name);
2716 	if ((istat->name == NULL) || (!strlen(istat->name))) {
2717 		free(istat);
2718 		return NULL;
2719 	}
2720 
2721 	list_add_tail(&istat->list, head);
2722 	return istat;
2723 }
2724 
2725 static bool is_stack_operation(const struct arch *arch, struct disasm_line *dl)
2726 {
2727 	if (arch__is_x86(arch)) {
2728 		if (!strncmp(dl->ins.name, "push", 4) ||
2729 		    !strncmp(dl->ins.name, "pop", 3) ||
2730 		    !strncmp(dl->ins.name, "call", 4) ||
2731 		    !strncmp(dl->ins.name, "ret", 3))
2732 			return true;
2733 	}
2734 
2735 	return false;
2736 }
2737 
2738 static bool is_stack_canary(const struct arch *arch, struct annotated_op_loc *loc)
2739 {
2740 	/* On x86_64, %gs:40 is used for stack canary */
2741 	if (arch__is_x86(arch)) {
2742 		if (loc->segment == INSN_SEG_X86_GS && loc->imm &&
2743 		    loc->offset == 40)
2744 			return true;
2745 	}
2746 
2747 	return false;
2748 }
2749 
2750 /**
2751  * Returns true if the instruction has a memory operand without
2752  * performing a load/store
2753  */
2754 static bool is_address_gen_insn(const struct arch *arch, struct disasm_line *dl)
2755 {
2756 	if (arch__is_x86(arch)) {
2757 		if (!strncmp(dl->ins.name, "lea", 3))
2758 			return true;
2759 	}
2760 
2761 	return false;
2762 }
2763 
2764 static struct disasm_line *
2765 annotation__prev_asm_line(struct annotation *notes, struct disasm_line *curr)
2766 {
2767 	struct list_head *sources = &notes->src->source;
2768 	struct disasm_line *prev;
2769 
2770 	if (curr == list_first_entry(sources, struct disasm_line, al.node))
2771 		return NULL;
2772 
2773 	prev = list_prev_entry(curr, al.node);
2774 	while (prev->al.offset == -1 &&
2775 	       prev != list_first_entry(sources, struct disasm_line, al.node))
2776 		prev = list_prev_entry(prev, al.node);
2777 
2778 	if (prev->al.offset == -1)
2779 		return NULL;
2780 
2781 	return prev;
2782 }
2783 
2784 static struct disasm_line *
2785 annotation__next_asm_line(struct annotation *notes, struct disasm_line *curr)
2786 {
2787 	struct list_head *sources = &notes->src->source;
2788 	struct disasm_line *next;
2789 
2790 	if (curr == list_last_entry(sources, struct disasm_line, al.node))
2791 		return NULL;
2792 
2793 	next = list_next_entry(curr, al.node);
2794 	while (next->al.offset == -1 &&
2795 	       next != list_last_entry(sources, struct disasm_line, al.node))
2796 		next = list_next_entry(next, al.node);
2797 
2798 	if (next->al.offset == -1)
2799 		return NULL;
2800 
2801 	return next;
2802 }
2803 
2804 u64 annotate_calc_pcrel(struct map_symbol *ms, u64 ip, int offset,
2805 			struct disasm_line *dl)
2806 {
2807 	struct annotation *notes;
2808 	struct disasm_line *next;
2809 	u64 addr;
2810 
2811 	notes = symbol__annotation(ms->sym);
2812 	/*
2813 	 * PC-relative addressing starts from the next instruction address
2814 	 * But the IP is for the current instruction.  Since disasm_line
2815 	 * doesn't have the instruction size, calculate it using the next
2816 	 * disasm_line.  If it's the last one, we can use symbol's end
2817 	 * address directly.
2818 	 */
2819 	next = annotation__next_asm_line(notes, dl);
2820 	if (next == NULL)
2821 		addr = ms->sym->end + offset;
2822 	else
2823 		addr = ip + (next->al.offset - dl->al.offset) + offset;
2824 
2825 	return map__rip_2objdump(ms->map, addr);
2826 }
2827 
2828 static struct debuginfo_cache {
2829 	struct dso *dso;
2830 	struct debuginfo *dbg;
2831 } di_cache;
2832 
2833 void debuginfo_cache__delete(void)
2834 {
2835 	dso__put(di_cache.dso);
2836 	di_cache.dso = NULL;
2837 
2838 	debuginfo__delete(di_cache.dbg);
2839 	di_cache.dbg = NULL;
2840 }
2841 
2842 static struct annotated_data_type *
2843 __hist_entry__get_data_type(struct hist_entry *he, const struct arch *arch,
2844 			    struct debuginfo *dbg, struct disasm_line *dl,
2845 			    int *type_offset)
2846 {
2847 	struct map_symbol *ms = &he->ms;
2848 	struct annotated_insn_loc loc;
2849 	struct annotated_op_loc *op_loc;
2850 	struct annotated_data_type *mem_type;
2851 	struct annotated_item_stat *istat;
2852 	int i;
2853 
2854 	istat = annotate_data_stat(&ann_insn_stat, dl->ins.name);
2855 	if (istat == NULL) {
2856 		ann_data_stat.no_insn++;
2857 		return NO_TYPE;
2858 	}
2859 
2860 	if (annotate_get_insn_location(arch, dl, &loc) < 0) {
2861 		ann_data_stat.no_insn_ops++;
2862 		istat->bad++;
2863 		return NO_TYPE;
2864 	}
2865 
2866 	if (is_stack_operation(arch, dl)) {
2867 		istat->good++;
2868 		*type_offset = 0;
2869 		return &stackop_type;
2870 	}
2871 
2872 	if (is_address_gen_insn(arch, dl)) {
2873 		istat->bad++;
2874 		ann_data_stat.no_mem_ops++;
2875 		return NO_TYPE;
2876 	}
2877 
2878 	for_each_insn_op_loc(&loc, i, op_loc) {
2879 		struct data_loc_info dloc = {
2880 			.arch = arch,
2881 			.thread = he->thread,
2882 			.ms = ms,
2883 			.ip = ms->sym->start + dl->al.offset,
2884 			.cpumode = he->cpumode,
2885 			.op = op_loc,
2886 			.di = dbg,
2887 		};
2888 
2889 		if (!op_loc->mem_ref && op_loc->segment == INSN_SEG_NONE)
2890 			continue;
2891 
2892 		/* PC-relative addressing */
2893 		if (op_loc->reg1 == DWARF_REG_PC) {
2894 			dloc.var_addr = annotate_calc_pcrel(ms, dloc.ip,
2895 							    op_loc->offset, dl);
2896 		}
2897 
2898 		/* This CPU access in kernel - pretend PC-relative addressing */
2899 		if (dso__kernel(map__dso(ms->map)) && arch__is_x86(arch) &&
2900 		    op_loc->segment == INSN_SEG_X86_GS && op_loc->imm) {
2901 			dloc.var_addr = op_loc->offset;
2902 			op_loc->reg1 = DWARF_REG_PC;
2903 		}
2904 
2905 		mem_type = find_data_type(&dloc);
2906 
2907 		if (mem_type == NULL && is_stack_canary(arch, op_loc)) {
2908 			istat->good++;
2909 			*type_offset = 0;
2910 			return &canary_type;
2911 		}
2912 
2913 		if (mem_type)
2914 			istat->good++;
2915 		else
2916 			istat->bad++;
2917 
2918 		if (symbol_conf.annotate_data_sample) {
2919 			struct evsel *evsel = hists_to_evsel(he->hists);
2920 
2921 			annotated_data_type__update_samples(mem_type, evsel,
2922 							    dloc.type_offset,
2923 							    he->stat.nr_events,
2924 							    he->stat.period);
2925 		}
2926 		*type_offset = dloc.type_offset;
2927 		return mem_type ?: NO_TYPE;
2928 	}
2929 
2930 	/* retry with a fused instruction */
2931 	return NULL;
2932 }
2933 
2934 /**
2935  * hist_entry__get_data_type - find data type for given hist entry
2936  * @he: hist entry
2937  *
2938  * This function first annotates the instruction at @he->ip and extracts
2939  * register and offset info from it.  Then it searches the DWARF debug
2940  * info to get a variable and type information using the address, register,
2941  * and offset.
2942  */
2943 struct annotated_data_type *hist_entry__get_data_type(struct hist_entry *he)
2944 {
2945 	struct map_symbol *ms = &he->ms;
2946 	struct evsel *evsel = hists_to_evsel(he->hists);
2947 	const struct arch *arch;
2948 	struct disasm_line *dl;
2949 	struct annotated_data_type *mem_type;
2950 	struct annotated_item_stat *istat;
2951 	u64 ip = he->ip;
2952 
2953 	ann_data_stat.total++;
2954 
2955 	if (ms->map == NULL || ms->sym == NULL) {
2956 		ann_data_stat.no_sym++;
2957 		return NULL;
2958 	}
2959 
2960 	if (!symbol_conf.init_annotation) {
2961 		ann_data_stat.no_sym++;
2962 		return NULL;
2963 	}
2964 
2965 	/*
2966 	 * di_cache holds a pair of values, but code below assumes
2967 	 * di_cache.dso can be compared/updated and di_cache.dbg can be
2968 	 * read/updated independently from each other. That assumption only
2969 	 * holds in single threaded code.
2970 	 */
2971 	assert(perf_singlethreaded);
2972 
2973 	if (map__dso(ms->map) != di_cache.dso) {
2974 		dso__put(di_cache.dso);
2975 		di_cache.dso = dso__get(map__dso(ms->map));
2976 
2977 		debuginfo__delete(di_cache.dbg);
2978 		di_cache.dbg = dso__debuginfo(di_cache.dso);
2979 	}
2980 
2981 	if (di_cache.dbg == NULL) {
2982 		ann_data_stat.no_dbginfo++;
2983 		return NULL;
2984 	}
2985 
2986 	/* Make sure it has the disasm of the function */
2987 	if (symbol__annotate(ms, evsel, &arch) < 0) {
2988 		ann_data_stat.no_insn++;
2989 		return NULL;
2990 	}
2991 
2992 	/*
2993 	 * Get a disasm to extract the location from the insn.
2994 	 * This is too slow...
2995 	 */
2996 	dl = find_disasm_line(ms->sym, ip, /*allow_update=*/true);
2997 	if (dl == NULL) {
2998 		ann_data_stat.no_insn++;
2999 		return NULL;
3000 	}
3001 
3002 retry:
3003 	mem_type = __hist_entry__get_data_type(he, arch, di_cache.dbg, dl,
3004 					       &he->mem_type_off);
3005 	if (mem_type)
3006 		return mem_type == NO_TYPE ? NULL : mem_type;
3007 
3008 	/*
3009 	 * Some instructions can be fused and the actual memory access came
3010 	 * from the previous instruction.
3011 	 */
3012 	if (dl->al.offset > 0) {
3013 		struct annotation *notes;
3014 		struct disasm_line *prev_dl;
3015 
3016 		notes = symbol__annotation(ms->sym);
3017 		prev_dl = annotation__prev_asm_line(notes, dl);
3018 
3019 		if (prev_dl && ins__is_fused(arch, prev_dl->ins.name, dl->ins.name)) {
3020 			dl = prev_dl;
3021 			goto retry;
3022 		}
3023 	}
3024 
3025 	ann_data_stat.no_mem_ops++;
3026 	istat = annotate_data_stat(&ann_insn_stat, dl->ins.name);
3027 	if (istat)
3028 		istat->bad++;
3029 	return NULL;
3030 }
3031 
3032 /* Basic block traversal (BFS) data structure */
3033 struct basic_block_data {
3034 	struct list_head queue;
3035 	struct list_head visited;
3036 };
3037 
3038 /*
3039  * During the traversal, it needs to know the parent block where the current
3040  * block block started from.  Note that single basic block can be parent of
3041  * two child basic blocks (in case of condition jump).
3042  */
3043 struct basic_block_link {
3044 	struct list_head node;
3045 	struct basic_block_link *parent;
3046 	struct annotated_basic_block *bb;
3047 };
3048 
3049 /* Check any of basic block in the list already has the offset */
3050 static bool basic_block_has_offset(struct list_head *head, s64 offset)
3051 {
3052 	struct basic_block_link *link;
3053 
3054 	list_for_each_entry(link, head, node) {
3055 		s64 begin_offset = link->bb->begin->al.offset;
3056 		s64 end_offset = link->bb->end->al.offset;
3057 
3058 		if (begin_offset <= offset && offset <= end_offset)
3059 			return true;
3060 	}
3061 	return false;
3062 }
3063 
3064 static bool is_new_basic_block(struct basic_block_data *bb_data,
3065 			       struct disasm_line *dl)
3066 {
3067 	s64 offset = dl->al.offset;
3068 
3069 	if (basic_block_has_offset(&bb_data->visited, offset))
3070 		return false;
3071 	if (basic_block_has_offset(&bb_data->queue, offset))
3072 		return false;
3073 	return true;
3074 }
3075 
3076 /* Add a basic block starting from dl and link it to the parent */
3077 static int add_basic_block(struct basic_block_data *bb_data,
3078 			   struct basic_block_link *parent,
3079 			   struct disasm_line *dl)
3080 {
3081 	struct annotated_basic_block *bb;
3082 	struct basic_block_link *link;
3083 
3084 	if (dl == NULL)
3085 		return -1;
3086 
3087 	if (!is_new_basic_block(bb_data, dl))
3088 		return 0;
3089 
3090 	bb = zalloc(sizeof(*bb));
3091 	if (bb == NULL)
3092 		return -1;
3093 
3094 	bb->begin = dl;
3095 	bb->end = dl;
3096 	INIT_LIST_HEAD(&bb->list);
3097 
3098 	link = malloc(sizeof(*link));
3099 	if (link == NULL) {
3100 		free(bb);
3101 		return -1;
3102 	}
3103 
3104 	link->bb = bb;
3105 	link->parent = parent;
3106 	list_add_tail(&link->node, &bb_data->queue);
3107 	return 0;
3108 }
3109 
3110 /* Returns true when it finds the target in the current basic block */
3111 static bool process_basic_block(struct basic_block_data *bb_data,
3112 				struct basic_block_link *link,
3113 				struct symbol *sym, u64 target)
3114 {
3115 	struct disasm_line *dl, *next_dl, *last_dl;
3116 	struct annotation *notes = symbol__annotation(sym);
3117 	bool found = false;
3118 
3119 	dl = link->bb->begin;
3120 	/* Check if it's already visited */
3121 	if (basic_block_has_offset(&bb_data->visited, dl->al.offset))
3122 		return false;
3123 
3124 	last_dl = list_last_entry(&notes->src->source,
3125 				  struct disasm_line, al.node);
3126 	if (last_dl->al.offset == -1)
3127 		last_dl = annotation__prev_asm_line(notes, last_dl);
3128 
3129 	if (last_dl == NULL)
3130 		return false;
3131 
3132 	list_for_each_entry_from(dl, &notes->src->source, al.node) {
3133 		/* Skip comment or debug info line */
3134 		if (dl->al.offset == -1)
3135 			continue;
3136 		/* Found the target instruction */
3137 		if (sym->start + dl->al.offset == target) {
3138 			found = true;
3139 			break;
3140 		}
3141 		/* End of the function, finish the block */
3142 		if (dl == last_dl)
3143 			break;
3144 		/* 'return' instruction finishes the block */
3145 		if (ins__is_ret(&dl->ins))
3146 			break;
3147 		/* normal instructions are part of the basic block */
3148 		if (!ins__is_jump(&dl->ins))
3149 			continue;
3150 		/* jump to a different function, tail call or return */
3151 		if (dl->ops.target.outside)
3152 			break;
3153 		/* jump instruction creates new basic block(s) */
3154 		next_dl = find_disasm_line(sym, sym->start + dl->ops.target.offset,
3155 					   /*allow_update=*/false);
3156 		if (next_dl)
3157 			add_basic_block(bb_data, link, next_dl);
3158 
3159 		/*
3160 		 * FIXME: determine conditional jumps properly.
3161 		 * Conditional jumps create another basic block with the
3162 		 * next disasm line.
3163 		 */
3164 		if (!strstr(dl->ins.name, "jmp")) {
3165 			next_dl = annotation__next_asm_line(notes, dl);
3166 			if (next_dl)
3167 				add_basic_block(bb_data, link, next_dl);
3168 		}
3169 		break;
3170 
3171 	}
3172 	link->bb->end = dl;
3173 	return found;
3174 }
3175 
3176 /*
3177  * It founds a target basic block, build a proper linked list of basic blocks
3178  * by following the link recursively.
3179  */
3180 static void link_found_basic_blocks(struct basic_block_link *link,
3181 				    struct list_head *head)
3182 {
3183 	while (link) {
3184 		struct basic_block_link *parent = link->parent;
3185 
3186 		list_move(&link->bb->list, head);
3187 		list_del(&link->node);
3188 		free(link);
3189 
3190 		link = parent;
3191 	}
3192 }
3193 
3194 static void delete_basic_blocks(struct basic_block_data *bb_data)
3195 {
3196 	struct basic_block_link *link, *tmp;
3197 
3198 	list_for_each_entry_safe(link, tmp, &bb_data->queue, node) {
3199 		list_del(&link->node);
3200 		zfree(&link->bb);
3201 		free(link);
3202 	}
3203 
3204 	list_for_each_entry_safe(link, tmp, &bb_data->visited, node) {
3205 		list_del(&link->node);
3206 		zfree(&link->bb);
3207 		free(link);
3208 	}
3209 }
3210 
3211 /**
3212  * annotate_get_basic_blocks - Get basic blocks for given address range
3213  * @sym: symbol to annotate
3214  * @src: source address
3215  * @dst: destination address
3216  * @head: list head to save basic blocks
3217  *
3218  * This function traverses disasm_lines from @src to @dst and save them in a
3219  * list of annotated_basic_block to @head.  It uses BFS to find the shortest
3220  * path between two.  The basic_block_link is to maintain parent links so
3221  * that it can build a list of blocks from the start.
3222  */
3223 int annotate_get_basic_blocks(struct symbol *sym, s64 src, s64 dst,
3224 			      struct list_head *head)
3225 {
3226 	struct basic_block_data bb_data = {
3227 		.queue = LIST_HEAD_INIT(bb_data.queue),
3228 		.visited = LIST_HEAD_INIT(bb_data.visited),
3229 	};
3230 	struct basic_block_link *link;
3231 	struct disasm_line *dl;
3232 	int ret = -1;
3233 
3234 	dl = find_disasm_line(sym, src, /*allow_update=*/false);
3235 	if (dl == NULL)
3236 		return -1;
3237 
3238 	if (add_basic_block(&bb_data, /*parent=*/NULL, dl) < 0)
3239 		return -1;
3240 
3241 	/* Find shortest path from src to dst using BFS */
3242 	while (!list_empty(&bb_data.queue)) {
3243 		link = list_first_entry(&bb_data.queue, struct basic_block_link, node);
3244 
3245 		if (process_basic_block(&bb_data, link, sym, dst)) {
3246 			link_found_basic_blocks(link, head);
3247 			ret = 0;
3248 			break;
3249 		}
3250 		list_move(&link->node, &bb_data.visited);
3251 	}
3252 	delete_basic_blocks(&bb_data);
3253 	return ret;
3254 }
3255