xref: /linux/tools/perf/util/annotate-data.c (revision f4dc5a3355a84f53ff3287d496728c7b77160069)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Convert sample address to data type using DWARF debug info.
4  *
5  * Written by Namhyung Kim <namhyung@kernel.org>
6  */
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <inttypes.h>
11 #include <linux/zalloc.h>
12 
13 #include "annotate.h"
14 #include "annotate-data.h"
15 #include "debuginfo.h"
16 #include "debug.h"
17 #include "dso.h"
18 #include "dwarf-regs.h"
19 #include "evsel.h"
20 #include "evlist.h"
21 #include "map.h"
22 #include "map_symbol.h"
23 #include "sort.h"
24 #include "strbuf.h"
25 #include "symbol.h"
26 #include "symbol_conf.h"
27 #include "thread.h"
28 
29 /* register number of the stack pointer */
30 #define X86_REG_SP 7
31 
32 static void delete_var_types(struct die_var_type *var_types);
33 
34 #define pr_debug_dtp(fmt, ...)					\
35 do {								\
36 	if (debug_type_profile)					\
37 		pr_info(fmt, ##__VA_ARGS__);			\
38 	else							\
39 		pr_debug3(fmt, ##__VA_ARGS__);			\
40 } while (0)
41 
42 void pr_debug_type_name(Dwarf_Die *die, enum type_state_kind kind)
43 {
44 	struct strbuf sb;
45 	char *str;
46 	Dwarf_Word size = 0;
47 
48 	if (!debug_type_profile && verbose < 3)
49 		return;
50 
51 	switch (kind) {
52 	case TSR_KIND_INVALID:
53 		pr_info("\n");
54 		return;
55 	case TSR_KIND_PERCPU_BASE:
56 		pr_info(" percpu base\n");
57 		return;
58 	case TSR_KIND_CONST:
59 		pr_info(" constant\n");
60 		return;
61 	case TSR_KIND_POINTER:
62 		pr_info(" pointer");
63 		/* it also prints the type info */
64 		break;
65 	case TSR_KIND_CANARY:
66 		pr_info(" stack canary\n");
67 		return;
68 	case TSR_KIND_TYPE:
69 	default:
70 		break;
71 	}
72 
73 	dwarf_aggregate_size(die, &size);
74 
75 	strbuf_init(&sb, 32);
76 	die_get_typename_from_type(die, &sb);
77 	str = strbuf_detach(&sb, NULL);
78 	pr_info(" type='%s' size=%#lx (die:%#lx)\n",
79 		str, (long)size, (long)dwarf_dieoffset(die));
80 	free(str);
81 }
82 
83 static void pr_debug_location(Dwarf_Die *die, u64 pc, int reg)
84 {
85 	ptrdiff_t off = 0;
86 	Dwarf_Attribute attr;
87 	Dwarf_Addr base, start, end;
88 	Dwarf_Op *ops;
89 	size_t nops;
90 
91 	if (!debug_type_profile && verbose < 3)
92 		return;
93 
94 	if (dwarf_attr(die, DW_AT_location, &attr) == NULL)
95 		return;
96 
97 	while ((off = dwarf_getlocations(&attr, off, &base, &start, &end, &ops, &nops)) > 0) {
98 		if (reg != DWARF_REG_PC && end <= pc)
99 			continue;
100 		if (reg != DWARF_REG_PC && start > pc)
101 			break;
102 
103 		pr_info(" variable location: ");
104 		switch (ops->atom) {
105 		case DW_OP_reg0 ...DW_OP_reg31:
106 			pr_info("reg%d\n", ops->atom - DW_OP_reg0);
107 			break;
108 		case DW_OP_breg0 ...DW_OP_breg31:
109 			pr_info("base=reg%d, offset=%#lx\n",
110 				ops->atom - DW_OP_breg0, (long)ops->number);
111 			break;
112 		case DW_OP_regx:
113 			pr_info("reg%ld\n", (long)ops->number);
114 			break;
115 		case DW_OP_bregx:
116 			pr_info("base=reg%ld, offset=%#lx\n",
117 				(long)ops->number, (long)ops->number2);
118 			break;
119 		case DW_OP_fbreg:
120 			pr_info("use frame base, offset=%#lx\n", (long)ops->number);
121 			break;
122 		case DW_OP_addr:
123 			pr_info("address=%#lx\n", (long)ops->number);
124 			break;
125 		default:
126 			pr_info("unknown: code=%#x, number=%#lx\n",
127 				ops->atom, (long)ops->number);
128 			break;
129 		}
130 		break;
131 	}
132 }
133 
134 static void pr_debug_scope(Dwarf_Die *scope_die)
135 {
136 	int tag;
137 
138 	if (!debug_type_profile && verbose < 3)
139 		return;
140 
141 	pr_info("(die:%lx) ", (long)dwarf_dieoffset(scope_die));
142 
143 	tag = dwarf_tag(scope_die);
144 	if (tag == DW_TAG_subprogram)
145 		pr_info("[function] %s\n", dwarf_diename(scope_die));
146 	else if (tag == DW_TAG_inlined_subroutine)
147 		pr_info("[inlined] %s\n", dwarf_diename(scope_die));
148 	else if (tag == DW_TAG_lexical_block)
149 		pr_info("[block]\n");
150 	else
151 		pr_info("[unknown] tag=%x\n", tag);
152 }
153 
154 bool has_reg_type(struct type_state *state, int reg)
155 {
156 	return (unsigned)reg < ARRAY_SIZE(state->regs);
157 }
158 
159 static void init_type_state(struct type_state *state, struct arch *arch)
160 {
161 	memset(state, 0, sizeof(*state));
162 	INIT_LIST_HEAD(&state->stack_vars);
163 
164 	if (arch__is(arch, "x86")) {
165 		state->regs[0].caller_saved = true;
166 		state->regs[1].caller_saved = true;
167 		state->regs[2].caller_saved = true;
168 		state->regs[4].caller_saved = true;
169 		state->regs[5].caller_saved = true;
170 		state->regs[8].caller_saved = true;
171 		state->regs[9].caller_saved = true;
172 		state->regs[10].caller_saved = true;
173 		state->regs[11].caller_saved = true;
174 		state->ret_reg = 0;
175 		state->stack_reg = X86_REG_SP;
176 	}
177 }
178 
179 static void exit_type_state(struct type_state *state)
180 {
181 	struct type_state_stack *stack, *tmp;
182 
183 	list_for_each_entry_safe(stack, tmp, &state->stack_vars, list) {
184 		list_del(&stack->list);
185 		free(stack);
186 	}
187 }
188 
189 /*
190  * Compare type name and size to maintain them in a tree.
191  * I'm not sure if DWARF would have information of a single type in many
192  * different places (compilation units).  If not, it could compare the
193  * offset of the type entry in the .debug_info section.
194  */
195 static int data_type_cmp(const void *_key, const struct rb_node *node)
196 {
197 	const struct annotated_data_type *key = _key;
198 	struct annotated_data_type *type;
199 
200 	type = rb_entry(node, struct annotated_data_type, node);
201 
202 	if (key->self.size != type->self.size)
203 		return key->self.size - type->self.size;
204 	return strcmp(key->self.type_name, type->self.type_name);
205 }
206 
207 static bool data_type_less(struct rb_node *node_a, const struct rb_node *node_b)
208 {
209 	struct annotated_data_type *a, *b;
210 
211 	a = rb_entry(node_a, struct annotated_data_type, node);
212 	b = rb_entry(node_b, struct annotated_data_type, node);
213 
214 	if (a->self.size != b->self.size)
215 		return a->self.size < b->self.size;
216 	return strcmp(a->self.type_name, b->self.type_name) < 0;
217 }
218 
219 /* Recursively add new members for struct/union */
220 static int __add_member_cb(Dwarf_Die *die, void *arg)
221 {
222 	struct annotated_member *parent = arg;
223 	struct annotated_member *member;
224 	Dwarf_Die member_type, die_mem;
225 	Dwarf_Word size, loc, bit_size = 0;
226 	Dwarf_Attribute attr;
227 	struct strbuf sb;
228 	int tag;
229 
230 	if (dwarf_tag(die) != DW_TAG_member)
231 		return DIE_FIND_CB_SIBLING;
232 
233 	member = zalloc(sizeof(*member));
234 	if (member == NULL)
235 		return DIE_FIND_CB_END;
236 
237 	strbuf_init(&sb, 32);
238 	die_get_typename(die, &sb);
239 
240 	__die_get_real_type(die, &member_type);
241 	if (dwarf_tag(&member_type) == DW_TAG_typedef)
242 		die_get_real_type(&member_type, &die_mem);
243 	else
244 		die_mem = member_type;
245 
246 	if (dwarf_aggregate_size(&die_mem, &size) < 0)
247 		size = 0;
248 
249 	if (dwarf_attr_integrate(die, DW_AT_data_member_location, &attr))
250 		dwarf_formudata(&attr, &loc);
251 	else {
252 		/* bitfield member */
253 		if (dwarf_attr_integrate(die, DW_AT_data_bit_offset, &attr) &&
254 		    dwarf_formudata(&attr, &loc) == 0)
255 			loc /= 8;
256 		else
257 			loc = 0;
258 
259 		if (dwarf_attr_integrate(die, DW_AT_bit_size, &attr) &&
260 		    dwarf_formudata(&attr, &bit_size) == 0)
261 			size = (bit_size + 7) / 8;
262 	}
263 
264 	member->type_name = strbuf_detach(&sb, NULL);
265 	/* member->var_name can be NULL */
266 	if (dwarf_diename(die)) {
267 		if (bit_size) {
268 			if (asprintf(&member->var_name, "%s:%ld",
269 				     dwarf_diename(die), (long)bit_size) < 0)
270 				member->var_name = NULL;
271 		} else {
272 			member->var_name = strdup(dwarf_diename(die));
273 		}
274 
275 		if (member->var_name == NULL) {
276 			free(member);
277 			return DIE_FIND_CB_END;
278 		}
279 	}
280 	member->size = size;
281 	member->offset = loc + parent->offset;
282 	INIT_LIST_HEAD(&member->children);
283 	list_add_tail(&member->node, &parent->children);
284 
285 	tag = dwarf_tag(&die_mem);
286 	switch (tag) {
287 	case DW_TAG_structure_type:
288 	case DW_TAG_union_type:
289 		die_find_child(&die_mem, __add_member_cb, member, &die_mem);
290 		break;
291 	default:
292 		break;
293 	}
294 	return DIE_FIND_CB_SIBLING;
295 }
296 
297 static void add_member_types(struct annotated_data_type *parent, Dwarf_Die *type)
298 {
299 	Dwarf_Die die_mem;
300 
301 	die_find_child(type, __add_member_cb, &parent->self, &die_mem);
302 }
303 
304 static void delete_members(struct annotated_member *member)
305 {
306 	struct annotated_member *child, *tmp;
307 
308 	list_for_each_entry_safe(child, tmp, &member->children, node) {
309 		list_del(&child->node);
310 		delete_members(child);
311 		zfree(&child->type_name);
312 		zfree(&child->var_name);
313 		free(child);
314 	}
315 }
316 
317 static struct annotated_data_type *dso__findnew_data_type(struct dso *dso,
318 							  Dwarf_Die *type_die)
319 {
320 	struct annotated_data_type *result = NULL;
321 	struct annotated_data_type key;
322 	struct rb_node *node;
323 	struct strbuf sb;
324 	char *type_name;
325 	Dwarf_Word size;
326 
327 	strbuf_init(&sb, 32);
328 	if (die_get_typename_from_type(type_die, &sb) < 0)
329 		strbuf_add(&sb, "(unknown type)", 14);
330 	type_name = strbuf_detach(&sb, NULL);
331 
332 	if (dwarf_tag(type_die) == DW_TAG_typedef)
333 		die_get_real_type(type_die, type_die);
334 
335 	dwarf_aggregate_size(type_die, &size);
336 
337 	/* Check existing nodes in dso->data_types tree */
338 	key.self.type_name = type_name;
339 	key.self.size = size;
340 	node = rb_find(&key, dso__data_types(dso), data_type_cmp);
341 	if (node) {
342 		result = rb_entry(node, struct annotated_data_type, node);
343 		free(type_name);
344 		return result;
345 	}
346 
347 	/* If not, add a new one */
348 	result = zalloc(sizeof(*result));
349 	if (result == NULL) {
350 		free(type_name);
351 		return NULL;
352 	}
353 
354 	result->self.type_name = type_name;
355 	result->self.size = size;
356 	INIT_LIST_HEAD(&result->self.children);
357 
358 	if (symbol_conf.annotate_data_member)
359 		add_member_types(result, type_die);
360 
361 	rb_add(&result->node, dso__data_types(dso), data_type_less);
362 	return result;
363 }
364 
365 static bool find_cu_die(struct debuginfo *di, u64 pc, Dwarf_Die *cu_die)
366 {
367 	Dwarf_Off off, next_off;
368 	size_t header_size;
369 
370 	if (dwarf_addrdie(di->dbg, pc, cu_die) != NULL)
371 		return cu_die;
372 
373 	/*
374 	 * There are some kernels don't have full aranges and contain only a few
375 	 * aranges entries.  Fallback to iterate all CU entries in .debug_info
376 	 * in case it's missing.
377 	 */
378 	off = 0;
379 	while (dwarf_nextcu(di->dbg, off, &next_off, &header_size,
380 			    NULL, NULL, NULL) == 0) {
381 		if (dwarf_offdie(di->dbg, off + header_size, cu_die) &&
382 		    dwarf_haspc(cu_die, pc))
383 			return true;
384 
385 		off = next_off;
386 	}
387 	return false;
388 }
389 
390 enum type_match_result {
391 	PERF_TMR_UNKNOWN = 0,
392 	PERF_TMR_OK,
393 	PERF_TMR_NO_TYPE,
394 	PERF_TMR_NO_POINTER,
395 	PERF_TMR_NO_SIZE,
396 	PERF_TMR_BAD_OFFSET,
397 	PERF_TMR_BAIL_OUT,
398 };
399 
400 static const char *match_result_str(enum type_match_result tmr)
401 {
402 	switch (tmr) {
403 	case PERF_TMR_OK:
404 		return "Good!";
405 	case PERF_TMR_NO_TYPE:
406 		return "no type information";
407 	case PERF_TMR_NO_POINTER:
408 		return "no/void pointer";
409 	case PERF_TMR_NO_SIZE:
410 		return "type size is unknown";
411 	case PERF_TMR_BAD_OFFSET:
412 		return "offset bigger than size";
413 	case PERF_TMR_UNKNOWN:
414 	case PERF_TMR_BAIL_OUT:
415 	default:
416 		return "invalid state";
417 	}
418 }
419 
420 static bool is_pointer_type(Dwarf_Die *type_die)
421 {
422 	int tag = dwarf_tag(type_die);
423 
424 	return tag == DW_TAG_pointer_type || tag == DW_TAG_array_type;
425 }
426 
427 static bool is_compound_type(Dwarf_Die *type_die)
428 {
429 	int tag = dwarf_tag(type_die);
430 
431 	return tag == DW_TAG_structure_type || tag == DW_TAG_union_type;
432 }
433 
434 /* returns if Type B has better information than Type A */
435 static bool is_better_type(Dwarf_Die *type_a, Dwarf_Die *type_b)
436 {
437 	Dwarf_Word size_a, size_b;
438 	Dwarf_Die die_a, die_b;
439 
440 	/* pointer type is preferred */
441 	if (is_pointer_type(type_a) != is_pointer_type(type_b))
442 		return is_pointer_type(type_b);
443 
444 	if (is_pointer_type(type_b)) {
445 		/*
446 		 * We want to compare the target type, but 'void *' can fail to
447 		 * get the target type.
448 		 */
449 		if (die_get_real_type(type_a, &die_a) == NULL)
450 			return true;
451 		if (die_get_real_type(type_b, &die_b) == NULL)
452 			return false;
453 
454 		type_a = &die_a;
455 		type_b = &die_b;
456 	}
457 
458 	/* bigger type is preferred */
459 	if (dwarf_aggregate_size(type_a, &size_a) < 0 ||
460 	    dwarf_aggregate_size(type_b, &size_b) < 0)
461 		return false;
462 
463 	if (size_a != size_b)
464 		return size_a < size_b;
465 
466 	/* struct or union is preferred */
467 	if (is_compound_type(type_a) != is_compound_type(type_b))
468 		return is_compound_type(type_b);
469 
470 	/* typedef is preferred */
471 	if (dwarf_tag(type_b) == DW_TAG_typedef)
472 		return true;
473 
474 	return false;
475 }
476 
477 /* The type info will be saved in @type_die */
478 static enum type_match_result check_variable(struct data_loc_info *dloc,
479 					     Dwarf_Die *var_die,
480 					     Dwarf_Die *type_die, int reg,
481 					     int offset, bool is_fbreg)
482 {
483 	Dwarf_Word size;
484 	bool needs_pointer = true;
485 	Dwarf_Die sized_type;
486 
487 	if (reg == DWARF_REG_PC)
488 		needs_pointer = false;
489 	else if (reg == dloc->fbreg || is_fbreg)
490 		needs_pointer = false;
491 	else if (arch__is(dloc->arch, "x86") && reg == X86_REG_SP)
492 		needs_pointer = false;
493 
494 	/* Get the type of the variable */
495 	if (__die_get_real_type(var_die, type_die) == NULL)
496 		return PERF_TMR_NO_TYPE;
497 
498 	/*
499 	 * Usually it expects a pointer type for a memory access.
500 	 * Convert to a real type it points to.  But global variables
501 	 * and local variables are accessed directly without a pointer.
502 	 */
503 	if (needs_pointer) {
504 		if (!is_pointer_type(type_die) ||
505 		    __die_get_real_type(type_die, type_die) == NULL)
506 			return PERF_TMR_NO_POINTER;
507 	}
508 
509 	if (dwarf_tag(type_die) == DW_TAG_typedef)
510 		die_get_real_type(type_die, &sized_type);
511 	else
512 		sized_type = *type_die;
513 
514 	/* Get the size of the actual type */
515 	if (dwarf_aggregate_size(&sized_type, &size) < 0)
516 		return PERF_TMR_NO_SIZE;
517 
518 	/* Minimal sanity check */
519 	if ((unsigned)offset >= size)
520 		return PERF_TMR_BAD_OFFSET;
521 
522 	return PERF_TMR_OK;
523 }
524 
525 struct type_state_stack *find_stack_state(struct type_state *state,
526 						 int offset)
527 {
528 	struct type_state_stack *stack;
529 
530 	list_for_each_entry(stack, &state->stack_vars, list) {
531 		if (offset == stack->offset)
532 			return stack;
533 
534 		if (stack->compound && stack->offset < offset &&
535 		    offset < stack->offset + stack->size)
536 			return stack;
537 	}
538 	return NULL;
539 }
540 
541 void set_stack_state(struct type_state_stack *stack, int offset, u8 kind,
542 			    Dwarf_Die *type_die)
543 {
544 	int tag;
545 	Dwarf_Word size;
546 
547 	if (dwarf_aggregate_size(type_die, &size) < 0)
548 		size = 0;
549 
550 	tag = dwarf_tag(type_die);
551 
552 	stack->type = *type_die;
553 	stack->size = size;
554 	stack->offset = offset;
555 	stack->kind = kind;
556 
557 	switch (tag) {
558 	case DW_TAG_structure_type:
559 	case DW_TAG_union_type:
560 		stack->compound = (kind != TSR_KIND_POINTER);
561 		break;
562 	default:
563 		stack->compound = false;
564 		break;
565 	}
566 }
567 
568 struct type_state_stack *findnew_stack_state(struct type_state *state,
569 						    int offset, u8 kind,
570 						    Dwarf_Die *type_die)
571 {
572 	struct type_state_stack *stack = find_stack_state(state, offset);
573 
574 	if (stack) {
575 		set_stack_state(stack, offset, kind, type_die);
576 		return stack;
577 	}
578 
579 	stack = malloc(sizeof(*stack));
580 	if (stack) {
581 		set_stack_state(stack, offset, kind, type_die);
582 		list_add(&stack->list, &state->stack_vars);
583 	}
584 	return stack;
585 }
586 
587 /* Maintain a cache for quick global variable lookup */
588 struct global_var_entry {
589 	struct rb_node node;
590 	char *name;
591 	u64 start;
592 	u64 end;
593 	u64 die_offset;
594 };
595 
596 static int global_var_cmp(const void *_key, const struct rb_node *node)
597 {
598 	const u64 addr = (uintptr_t)_key;
599 	struct global_var_entry *gvar;
600 
601 	gvar = rb_entry(node, struct global_var_entry, node);
602 
603 	if (gvar->start <= addr && addr < gvar->end)
604 		return 0;
605 	return gvar->start > addr ? -1 : 1;
606 }
607 
608 static bool global_var_less(struct rb_node *node_a, const struct rb_node *node_b)
609 {
610 	struct global_var_entry *gvar_a, *gvar_b;
611 
612 	gvar_a = rb_entry(node_a, struct global_var_entry, node);
613 	gvar_b = rb_entry(node_b, struct global_var_entry, node);
614 
615 	return gvar_a->start < gvar_b->start;
616 }
617 
618 static struct global_var_entry *global_var__find(struct data_loc_info *dloc, u64 addr)
619 {
620 	struct dso *dso = map__dso(dloc->ms->map);
621 	struct rb_node *node;
622 
623 	node = rb_find((void *)(uintptr_t)addr, dso__global_vars(dso), global_var_cmp);
624 	if (node == NULL)
625 		return NULL;
626 
627 	return rb_entry(node, struct global_var_entry, node);
628 }
629 
630 static bool global_var__add(struct data_loc_info *dloc, u64 addr,
631 			    const char *name, Dwarf_Die *type_die)
632 {
633 	struct dso *dso = map__dso(dloc->ms->map);
634 	struct global_var_entry *gvar;
635 	Dwarf_Word size;
636 
637 	if (dwarf_aggregate_size(type_die, &size) < 0)
638 		return false;
639 
640 	gvar = malloc(sizeof(*gvar));
641 	if (gvar == NULL)
642 		return false;
643 
644 	gvar->name = name ? strdup(name) : NULL;
645 	if (name && gvar->name == NULL) {
646 		free(gvar);
647 		return false;
648 	}
649 
650 	gvar->start = addr;
651 	gvar->end = addr + size;
652 	gvar->die_offset = dwarf_dieoffset(type_die);
653 
654 	rb_add(&gvar->node, dso__global_vars(dso), global_var_less);
655 	return true;
656 }
657 
658 void global_var_type__tree_delete(struct rb_root *root)
659 {
660 	struct global_var_entry *gvar;
661 
662 	while (!RB_EMPTY_ROOT(root)) {
663 		struct rb_node *node = rb_first(root);
664 
665 		rb_erase(node, root);
666 		gvar = rb_entry(node, struct global_var_entry, node);
667 		zfree(&gvar->name);
668 		free(gvar);
669 	}
670 }
671 
672 bool get_global_var_info(struct data_loc_info *dloc, u64 addr,
673 				const char **var_name, int *var_offset)
674 {
675 	struct addr_location al;
676 	struct symbol *sym;
677 	u64 mem_addr;
678 
679 	/* Kernel symbols might be relocated */
680 	mem_addr = addr + map__reloc(dloc->ms->map);
681 
682 	addr_location__init(&al);
683 	sym = thread__find_symbol_fb(dloc->thread, dloc->cpumode,
684 				     mem_addr, &al);
685 	if (sym) {
686 		*var_name = sym->name;
687 		/* Calculate type offset from the start of variable */
688 		*var_offset = mem_addr - map__unmap_ip(al.map, sym->start);
689 	} else {
690 		*var_name = NULL;
691 	}
692 	addr_location__exit(&al);
693 	if (*var_name == NULL)
694 		return false;
695 
696 	return true;
697 }
698 
699 static void global_var__collect(struct data_loc_info *dloc)
700 {
701 	Dwarf *dwarf = dloc->di->dbg;
702 	Dwarf_Off off, next_off;
703 	Dwarf_Die cu_die, type_die;
704 	size_t header_size;
705 
706 	/* Iterate all CU and collect global variables that have no location in a register. */
707 	off = 0;
708 	while (dwarf_nextcu(dwarf, off, &next_off, &header_size,
709 			    NULL, NULL, NULL) == 0) {
710 		struct die_var_type *var_types = NULL;
711 		struct die_var_type *pos;
712 
713 		if (dwarf_offdie(dwarf, off + header_size, &cu_die) == NULL) {
714 			off = next_off;
715 			continue;
716 		}
717 
718 		die_collect_global_vars(&cu_die, &var_types);
719 
720 		for (pos = var_types; pos; pos = pos->next) {
721 			const char *var_name = NULL;
722 			int var_offset = 0;
723 
724 			if (pos->reg != -1)
725 				continue;
726 
727 			if (!dwarf_offdie(dwarf, pos->die_off, &type_die))
728 				continue;
729 
730 			if (!get_global_var_info(dloc, pos->addr, &var_name,
731 						 &var_offset))
732 				continue;
733 
734 			if (var_offset != 0)
735 				continue;
736 
737 			global_var__add(dloc, pos->addr, var_name, &type_die);
738 		}
739 
740 		delete_var_types(var_types);
741 
742 		off = next_off;
743 	}
744 }
745 
746 bool get_global_var_type(Dwarf_Die *cu_die, struct data_loc_info *dloc,
747 				u64 ip, u64 var_addr, int *var_offset,
748 				Dwarf_Die *type_die)
749 {
750 	u64 pc;
751 	int offset;
752 	const char *var_name = NULL;
753 	struct global_var_entry *gvar;
754 	struct dso *dso = map__dso(dloc->ms->map);
755 	Dwarf_Die var_die;
756 
757 	if (RB_EMPTY_ROOT(dso__global_vars(dso)))
758 		global_var__collect(dloc);
759 
760 	gvar = global_var__find(dloc, var_addr);
761 	if (gvar) {
762 		if (!dwarf_offdie(dloc->di->dbg, gvar->die_offset, type_die))
763 			return false;
764 
765 		*var_offset = var_addr - gvar->start;
766 		return true;
767 	}
768 
769 	/* Try to get the variable by address first */
770 	if (die_find_variable_by_addr(cu_die, var_addr, &var_die, &offset) &&
771 	    check_variable(dloc, &var_die, type_die, DWARF_REG_PC, offset,
772 			   /*is_fbreg=*/false) == PERF_TMR_OK) {
773 		var_name = dwarf_diename(&var_die);
774 		*var_offset = offset;
775 		goto ok;
776 	}
777 
778 	if (!get_global_var_info(dloc, var_addr, &var_name, var_offset))
779 		return false;
780 
781 	pc = map__rip_2objdump(dloc->ms->map, ip);
782 
783 	/* Try to get the name of global variable */
784 	if (die_find_variable_at(cu_die, var_name, pc, &var_die) &&
785 	    check_variable(dloc, &var_die, type_die, DWARF_REG_PC, *var_offset,
786 			   /*is_fbreg=*/false) == PERF_TMR_OK)
787 		goto ok;
788 
789 	return false;
790 
791 ok:
792 	/* The address should point to the start of the variable */
793 	global_var__add(dloc, var_addr - *var_offset, var_name, type_die);
794 	return true;
795 }
796 
797 static bool die_is_same(Dwarf_Die *die_a, Dwarf_Die *die_b)
798 {
799 	return (die_a->cu == die_b->cu) && (die_a->addr == die_b->addr);
800 }
801 
802 /**
803  * update_var_state - Update type state using given variables
804  * @state: type state table
805  * @dloc: data location info
806  * @addr: instruction address to match with variable
807  * @insn_offset: instruction offset (for debug)
808  * @var_types: list of variables with type info
809  *
810  * This function fills the @state table using @var_types info.  Each variable
811  * is used only at the given location and updates an entry in the table.
812  */
813 static void update_var_state(struct type_state *state, struct data_loc_info *dloc,
814 			     u64 addr, u64 insn_offset, struct die_var_type *var_types)
815 {
816 	Dwarf_Die mem_die;
817 	struct die_var_type *var;
818 	int fbreg = dloc->fbreg;
819 	int fb_offset = 0;
820 
821 	if (dloc->fb_cfa) {
822 		if (die_get_cfa(dloc->di->dbg, addr, &fbreg, &fb_offset) < 0)
823 			fbreg = -1;
824 	}
825 
826 	for (var = var_types; var != NULL; var = var->next) {
827 		if (var->addr != addr)
828 			continue;
829 		/* Get the type DIE using the offset */
830 		if (!dwarf_offdie(dloc->di->dbg, var->die_off, &mem_die))
831 			continue;
832 
833 		if (var->reg == DWARF_REG_FB || var->reg == fbreg || var->reg == state->stack_reg) {
834 			int offset = var->offset;
835 			struct type_state_stack *stack;
836 
837 			if (var->reg != DWARF_REG_FB)
838 				offset -= fb_offset;
839 
840 			stack = find_stack_state(state, offset);
841 			if (stack && stack->kind == TSR_KIND_TYPE &&
842 			    !is_better_type(&stack->type, &mem_die))
843 				continue;
844 
845 			findnew_stack_state(state, offset, TSR_KIND_TYPE,
846 					    &mem_die);
847 
848 			if (var->reg == state->stack_reg) {
849 				pr_debug_dtp("var [%"PRIx64"] %#x(reg%d)",
850 					     insn_offset, offset, state->stack_reg);
851 			} else {
852 				pr_debug_dtp("var [%"PRIx64"] -%#x(stack)",
853 					     insn_offset, -offset);
854 			}
855 			pr_debug_type_name(&mem_die, TSR_KIND_TYPE);
856 		} else if (has_reg_type(state, var->reg) && var->offset == 0) {
857 			struct type_state_reg *reg;
858 			Dwarf_Die orig_type;
859 
860 			reg = &state->regs[var->reg];
861 
862 			if (reg->ok && reg->kind == TSR_KIND_TYPE &&
863 			    !is_better_type(&reg->type, &mem_die))
864 				continue;
865 
866 			orig_type = reg->type;
867 
868 			reg->type = mem_die;
869 			reg->kind = TSR_KIND_TYPE;
870 			reg->ok = true;
871 
872 			pr_debug_dtp("var [%"PRIx64"] reg%d",
873 				     insn_offset, var->reg);
874 			pr_debug_type_name(&mem_die, TSR_KIND_TYPE);
875 
876 			/*
877 			 * If this register is directly copied from another and it gets a
878 			 * better type, also update the type of the source register.  This
879 			 * is usually the case of container_of() macro with offset of 0.
880 			 */
881 			if (has_reg_type(state, reg->copied_from)) {
882 				struct type_state_reg *copy_reg;
883 
884 				copy_reg = &state->regs[reg->copied_from];
885 
886 				/* TODO: check if type is compatible or embedded */
887 				if (!copy_reg->ok || (copy_reg->kind != TSR_KIND_TYPE) ||
888 				    !die_is_same(&copy_reg->type, &orig_type) ||
889 				    !is_better_type(&copy_reg->type, &mem_die))
890 					continue;
891 
892 				copy_reg->type = mem_die;
893 
894 				pr_debug_dtp("var [%"PRIx64"] copyback reg%d",
895 					     insn_offset, reg->copied_from);
896 				pr_debug_type_name(&mem_die, TSR_KIND_TYPE);
897 			}
898 		}
899 	}
900 }
901 
902 /**
903  * update_insn_state - Update type state for an instruction
904  * @state: type state table
905  * @dloc: data location info
906  * @cu_die: compile unit debug entry
907  * @dl: disasm line for the instruction
908  *
909  * This function updates the @state table for the target operand of the
910  * instruction at @dl if it transfers the type like MOV on x86.  Since it
911  * tracks the type, it won't care about the values like in arithmetic
912  * instructions like ADD/SUB/MUL/DIV and INC/DEC.
913  *
914  * Note that ops->reg2 is only available when both mem_ref and multi_regs
915  * are true.
916  */
917 static void update_insn_state(struct type_state *state, struct data_loc_info *dloc,
918 			      Dwarf_Die *cu_die, struct disasm_line *dl)
919 {
920 	if (dloc->arch->update_insn_state)
921 		dloc->arch->update_insn_state(state, dloc, cu_die, dl);
922 }
923 
924 /*
925  * Prepend this_blocks (from the outer scope) to full_blocks, removing
926  * duplicate disasm line.
927  */
928 static void prepend_basic_blocks(struct list_head *this_blocks,
929 				 struct list_head *full_blocks)
930 {
931 	struct annotated_basic_block *first_bb, *last_bb;
932 
933 	last_bb = list_last_entry(this_blocks, typeof(*last_bb), list);
934 	first_bb = list_first_entry(full_blocks, typeof(*first_bb), list);
935 
936 	if (list_empty(full_blocks))
937 		goto out;
938 
939 	/* Last insn in this_blocks should be same as first insn in full_blocks */
940 	if (last_bb->end != first_bb->begin) {
941 		pr_debug("prepend basic blocks: mismatched disasm line %"PRIx64" -> %"PRIx64"\n",
942 			 last_bb->end->al.offset, first_bb->begin->al.offset);
943 		goto out;
944 	}
945 
946 	/* Is the basic block have only one disasm_line? */
947 	if (last_bb->begin == last_bb->end) {
948 		list_del(&last_bb->list);
949 		free(last_bb);
950 		goto out;
951 	}
952 
953 	/* Point to the insn before the last when adding this block to full_blocks */
954 	last_bb->end = list_prev_entry(last_bb->end, al.node);
955 
956 out:
957 	list_splice(this_blocks, full_blocks);
958 }
959 
960 static void delete_basic_blocks(struct list_head *basic_blocks)
961 {
962 	struct annotated_basic_block *bb, *tmp;
963 
964 	list_for_each_entry_safe(bb, tmp, basic_blocks, list) {
965 		list_del(&bb->list);
966 		free(bb);
967 	}
968 }
969 
970 /* Make sure all variables have a valid start address */
971 static void fixup_var_address(struct die_var_type *var_types, u64 addr)
972 {
973 	while (var_types) {
974 		/*
975 		 * Some variables have no address range meaning it's always
976 		 * available in the whole scope.  Let's adjust the start
977 		 * address to the start of the scope.
978 		 */
979 		if (var_types->addr == 0)
980 			var_types->addr = addr;
981 
982 		var_types = var_types->next;
983 	}
984 }
985 
986 static void delete_var_types(struct die_var_type *var_types)
987 {
988 	while (var_types) {
989 		struct die_var_type *next = var_types->next;
990 
991 		free(var_types);
992 		var_types = next;
993 	}
994 }
995 
996 /* should match to is_stack_canary() in util/annotate.c */
997 static void setup_stack_canary(struct data_loc_info *dloc)
998 {
999 	if (arch__is(dloc->arch, "x86")) {
1000 		dloc->op->segment = INSN_SEG_X86_GS;
1001 		dloc->op->imm = true;
1002 		dloc->op->offset = 40;
1003 	}
1004 }
1005 
1006 /*
1007  * It's at the target address, check if it has a matching type.
1008  * It returns PERF_TMR_BAIL_OUT when it looks up per-cpu variables which
1009  * are similar to global variables and no additional info is needed.
1010  */
1011 static enum type_match_result check_matching_type(struct type_state *state,
1012 						  struct data_loc_info *dloc,
1013 						  Dwarf_Die *cu_die,
1014 						  struct disasm_line *dl,
1015 						  Dwarf_Die *type_die)
1016 {
1017 	Dwarf_Word size;
1018 	u32 insn_offset = dl->al.offset;
1019 	int reg = dloc->op->reg1;
1020 	int offset = dloc->op->offset;
1021 	const char *offset_sign = "";
1022 	bool retry = true;
1023 
1024 	if (offset < 0) {
1025 		offset = -offset;
1026 		offset_sign = "-";
1027 	}
1028 
1029 again:
1030 	pr_debug_dtp("chk [%x] reg%d offset=%s%#x ok=%d kind=%d ",
1031 		     insn_offset, reg, offset_sign, offset,
1032 		     state->regs[reg].ok, state->regs[reg].kind);
1033 
1034 	if (!state->regs[reg].ok)
1035 		goto check_non_register;
1036 
1037 	if (state->regs[reg].kind == TSR_KIND_TYPE) {
1038 		Dwarf_Die sized_type;
1039 		struct strbuf sb;
1040 
1041 		strbuf_init(&sb, 32);
1042 		die_get_typename_from_type(&state->regs[reg].type, &sb);
1043 		pr_debug_dtp("(%s)", sb.buf);
1044 		strbuf_release(&sb);
1045 
1046 		/*
1047 		 * Normal registers should hold a pointer (or array) to
1048 		 * dereference a memory location.
1049 		 */
1050 		if (!is_pointer_type(&state->regs[reg].type)) {
1051 			if (dloc->op->offset < 0 && reg != state->stack_reg)
1052 				goto check_kernel;
1053 
1054 			return PERF_TMR_NO_POINTER;
1055 		}
1056 
1057 		/* Remove the pointer and get the target type */
1058 		if (__die_get_real_type(&state->regs[reg].type, type_die) == NULL)
1059 			return PERF_TMR_NO_POINTER;
1060 
1061 		dloc->type_offset = dloc->op->offset;
1062 
1063 		if (dwarf_tag(type_die) == DW_TAG_typedef)
1064 			die_get_real_type(type_die, &sized_type);
1065 		else
1066 			sized_type = *type_die;
1067 
1068 		/* Get the size of the actual type */
1069 		if (dwarf_aggregate_size(&sized_type, &size) < 0 ||
1070 		    (unsigned)dloc->type_offset >= size)
1071 			return PERF_TMR_BAD_OFFSET;
1072 
1073 		return PERF_TMR_OK;
1074 	}
1075 
1076 	if (state->regs[reg].kind == TSR_KIND_POINTER) {
1077 		pr_debug_dtp("percpu ptr");
1078 
1079 		/*
1080 		 * It's actaully pointer but the address was calculated using
1081 		 * some arithmetic.  So it points to the actual type already.
1082 		 */
1083 		*type_die = state->regs[reg].type;
1084 
1085 		dloc->type_offset = dloc->op->offset;
1086 
1087 		/* Get the size of the actual type */
1088 		if (dwarf_aggregate_size(type_die, &size) < 0 ||
1089 		    (unsigned)dloc->type_offset >= size)
1090 			return PERF_TMR_BAIL_OUT;
1091 
1092 		return PERF_TMR_OK;
1093 	}
1094 
1095 	if (state->regs[reg].kind == TSR_KIND_CANARY) {
1096 		pr_debug_dtp("stack canary");
1097 
1098 		/*
1099 		 * This is a saved value of the stack canary which will be handled
1100 		 * in the outer logic when it returns failure here.  Pretend it's
1101 		 * from the stack canary directly.
1102 		 */
1103 		setup_stack_canary(dloc);
1104 
1105 		return PERF_TMR_BAIL_OUT;
1106 	}
1107 
1108 	if (state->regs[reg].kind == TSR_KIND_PERCPU_BASE) {
1109 		u64 var_addr = dloc->op->offset;
1110 		int var_offset;
1111 
1112 		pr_debug_dtp("percpu var");
1113 
1114 		if (dloc->op->multi_regs) {
1115 			int reg2 = dloc->op->reg2;
1116 
1117 			if (dloc->op->reg2 == reg)
1118 				reg2 = dloc->op->reg1;
1119 
1120 			if (has_reg_type(state, reg2) && state->regs[reg2].ok &&
1121 			    state->regs[reg2].kind == TSR_KIND_CONST)
1122 				var_addr += state->regs[reg2].imm_value;
1123 		}
1124 
1125 		if (get_global_var_type(cu_die, dloc, dloc->ip, var_addr,
1126 					&var_offset, type_die)) {
1127 			dloc->type_offset = var_offset;
1128 			return PERF_TMR_OK;
1129 		}
1130 		/* No need to retry per-cpu (global) variables */
1131 		return PERF_TMR_BAIL_OUT;
1132 	}
1133 
1134 check_non_register:
1135 	if (reg == dloc->fbreg || reg == state->stack_reg) {
1136 		struct type_state_stack *stack;
1137 
1138 		pr_debug_dtp("%s", reg == dloc->fbreg ? "fbreg" : "stack");
1139 
1140 		stack = find_stack_state(state, dloc->type_offset);
1141 		if (stack == NULL) {
1142 			if (retry) {
1143 				pr_debug_dtp(" : retry\n");
1144 				retry = false;
1145 
1146 				/* update type info it's the first store to the stack */
1147 				update_insn_state(state, dloc, cu_die, dl);
1148 				goto again;
1149 			}
1150 			return PERF_TMR_NO_TYPE;
1151 		}
1152 
1153 		if (stack->kind == TSR_KIND_CANARY) {
1154 			setup_stack_canary(dloc);
1155 			return PERF_TMR_BAIL_OUT;
1156 		}
1157 
1158 		if (stack->kind != TSR_KIND_TYPE)
1159 			return PERF_TMR_NO_TYPE;
1160 
1161 		*type_die = stack->type;
1162 		/* Update the type offset from the start of slot */
1163 		dloc->type_offset -= stack->offset;
1164 
1165 		return PERF_TMR_OK;
1166 	}
1167 
1168 	if (dloc->fb_cfa) {
1169 		struct type_state_stack *stack;
1170 		u64 pc = map__rip_2objdump(dloc->ms->map, dloc->ip);
1171 		int fbreg, fboff;
1172 
1173 		pr_debug_dtp("cfa");
1174 
1175 		if (die_get_cfa(dloc->di->dbg, pc, &fbreg, &fboff) < 0)
1176 			fbreg = -1;
1177 
1178 		if (reg != fbreg)
1179 			return PERF_TMR_NO_TYPE;
1180 
1181 		stack = find_stack_state(state, dloc->type_offset - fboff);
1182 		if (stack == NULL) {
1183 			if (retry) {
1184 				pr_debug_dtp(" : retry\n");
1185 				retry = false;
1186 
1187 				/* update type info it's the first store to the stack */
1188 				update_insn_state(state, dloc, cu_die, dl);
1189 				goto again;
1190 			}
1191 			return PERF_TMR_NO_TYPE;
1192 		}
1193 
1194 		if (stack->kind == TSR_KIND_CANARY) {
1195 			setup_stack_canary(dloc);
1196 			return PERF_TMR_BAIL_OUT;
1197 		}
1198 
1199 		if (stack->kind != TSR_KIND_TYPE)
1200 			return PERF_TMR_NO_TYPE;
1201 
1202 		*type_die = stack->type;
1203 		/* Update the type offset from the start of slot */
1204 		dloc->type_offset -= fboff + stack->offset;
1205 
1206 		return PERF_TMR_OK;
1207 	}
1208 
1209 check_kernel:
1210 	if (dso__kernel(map__dso(dloc->ms->map))) {
1211 		u64 addr;
1212 
1213 		/* Direct this-cpu access like "%gs:0x34740" */
1214 		if (dloc->op->segment == INSN_SEG_X86_GS && dloc->op->imm &&
1215 		    arch__is(dloc->arch, "x86")) {
1216 			pr_debug_dtp("this-cpu var");
1217 
1218 			addr = dloc->op->offset;
1219 
1220 			if (get_global_var_type(cu_die, dloc, dloc->ip, addr,
1221 						&offset, type_die)) {
1222 				dloc->type_offset = offset;
1223 				return PERF_TMR_OK;
1224 			}
1225 			return PERF_TMR_BAIL_OUT;
1226 		}
1227 
1228 		/* Access to global variable like "-0x7dcf0500(,%rdx,8)" */
1229 		if (dloc->op->offset < 0 && reg != state->stack_reg) {
1230 			addr = (s64) dloc->op->offset;
1231 
1232 			if (get_global_var_type(cu_die, dloc, dloc->ip, addr,
1233 						&offset, type_die)) {
1234 				pr_debug_dtp("global var");
1235 
1236 				dloc->type_offset = offset;
1237 				return PERF_TMR_OK;
1238 			}
1239 			return PERF_TMR_BAIL_OUT;
1240 		}
1241 	}
1242 
1243 	return PERF_TMR_UNKNOWN;
1244 }
1245 
1246 /* Iterate instructions in basic blocks and update type table */
1247 static enum type_match_result find_data_type_insn(struct data_loc_info *dloc,
1248 						  struct list_head *basic_blocks,
1249 						  struct die_var_type *var_types,
1250 						  Dwarf_Die *cu_die,
1251 						  Dwarf_Die *type_die)
1252 {
1253 	struct type_state state;
1254 	struct symbol *sym = dloc->ms->sym;
1255 	struct annotation *notes = symbol__annotation(sym);
1256 	struct annotated_basic_block *bb;
1257 	enum type_match_result ret = PERF_TMR_UNKNOWN;
1258 
1259 	init_type_state(&state, dloc->arch);
1260 
1261 	list_for_each_entry(bb, basic_blocks, list) {
1262 		struct disasm_line *dl = bb->begin;
1263 
1264 		BUG_ON(bb->begin->al.offset == -1 || bb->end->al.offset == -1);
1265 
1266 		pr_debug_dtp("bb: [%"PRIx64" - %"PRIx64"]\n",
1267 			     bb->begin->al.offset, bb->end->al.offset);
1268 
1269 		list_for_each_entry_from(dl, &notes->src->source, al.node) {
1270 			u64 this_ip = sym->start + dl->al.offset;
1271 			u64 addr = map__rip_2objdump(dloc->ms->map, this_ip);
1272 
1273 			/* Skip comment or debug info lines */
1274 			if (dl->al.offset == -1)
1275 				continue;
1276 
1277 			/* Update variable type at this address */
1278 			update_var_state(&state, dloc, addr, dl->al.offset, var_types);
1279 
1280 			if (this_ip == dloc->ip) {
1281 				ret = check_matching_type(&state, dloc,
1282 							  cu_die, dl, type_die);
1283 				pr_debug_dtp(" : %s\n", match_result_str(ret));
1284 				goto out;
1285 			}
1286 
1287 			/* Update type table after processing the instruction */
1288 			update_insn_state(&state, dloc, cu_die, dl);
1289 			if (dl == bb->end)
1290 				break;
1291 		}
1292 	}
1293 
1294 out:
1295 	exit_type_state(&state);
1296 	return ret;
1297 }
1298 
1299 static int arch_supports_insn_tracking(struct data_loc_info *dloc)
1300 {
1301 	if ((arch__is(dloc->arch, "x86")) || (arch__is(dloc->arch, "powerpc")))
1302 		return 1;
1303 	return 0;
1304 }
1305 
1306 /*
1307  * Construct a list of basic blocks for each scope with variables and try to find
1308  * the data type by updating a type state table through instructions.
1309  */
1310 static enum type_match_result find_data_type_block(struct data_loc_info *dloc,
1311 						   Dwarf_Die *cu_die,
1312 						   Dwarf_Die *scopes,
1313 						   int nr_scopes,
1314 						   Dwarf_Die *type_die)
1315 {
1316 	LIST_HEAD(basic_blocks);
1317 	struct die_var_type *var_types = NULL;
1318 	u64 src_ip, dst_ip, prev_dst_ip;
1319 	enum type_match_result ret = PERF_TMR_UNKNOWN;
1320 
1321 	/* TODO: other architecture support */
1322 	if (!arch_supports_insn_tracking(dloc))
1323 		return PERF_TMR_BAIL_OUT;
1324 
1325 	prev_dst_ip = dst_ip = dloc->ip;
1326 	for (int i = nr_scopes - 1; i >= 0; i--) {
1327 		Dwarf_Addr base, start, end;
1328 		LIST_HEAD(this_blocks);
1329 
1330 		if (dwarf_ranges(&scopes[i], 0, &base, &start, &end) < 0)
1331 			break;
1332 
1333 		pr_debug_dtp("scope: [%d/%d] ", i + 1, nr_scopes);
1334 		pr_debug_scope(&scopes[i]);
1335 
1336 		src_ip = map__objdump_2rip(dloc->ms->map, start);
1337 
1338 again:
1339 		/* Get basic blocks for this scope */
1340 		if (annotate_get_basic_blocks(dloc->ms->sym, src_ip, dst_ip,
1341 					      &this_blocks) < 0) {
1342 			/* Try previous block if they are not connected */
1343 			if (prev_dst_ip != dst_ip) {
1344 				dst_ip = prev_dst_ip;
1345 				goto again;
1346 			}
1347 
1348 			pr_debug_dtp("cannot find a basic block from %"PRIx64" to %"PRIx64"\n",
1349 				     src_ip - dloc->ms->sym->start,
1350 				     dst_ip - dloc->ms->sym->start);
1351 			continue;
1352 		}
1353 		prepend_basic_blocks(&this_blocks, &basic_blocks);
1354 
1355 		/* Get variable info for this scope and add to var_types list */
1356 		die_collect_vars(&scopes[i], &var_types);
1357 		fixup_var_address(var_types, start);
1358 
1359 		/* Find from start of this scope to the target instruction */
1360 		ret = find_data_type_insn(dloc, &basic_blocks, var_types,
1361 					    cu_die, type_die);
1362 		if (ret == PERF_TMR_OK) {
1363 			char buf[64];
1364 			int offset = dloc->op->offset;
1365 			const char *offset_sign = "";
1366 
1367 			if (offset < 0) {
1368 				offset = -offset;
1369 				offset_sign = "-";
1370 			}
1371 
1372 			if (dloc->op->multi_regs)
1373 				snprintf(buf, sizeof(buf), "reg%d, reg%d",
1374 					 dloc->op->reg1, dloc->op->reg2);
1375 			else
1376 				snprintf(buf, sizeof(buf), "reg%d", dloc->op->reg1);
1377 
1378 			pr_debug_dtp("found by insn track: %s%#x(%s) type-offset=%#x\n",
1379 				     offset_sign, offset, buf, dloc->type_offset);
1380 			break;
1381 		}
1382 
1383 		if (ret == PERF_TMR_BAIL_OUT)
1384 			break;
1385 
1386 		/* Go up to the next scope and find blocks to the start */
1387 		prev_dst_ip = dst_ip;
1388 		dst_ip = src_ip;
1389 	}
1390 
1391 	delete_basic_blocks(&basic_blocks);
1392 	delete_var_types(var_types);
1393 	return ret;
1394 }
1395 
1396 /* The result will be saved in @type_die */
1397 static int find_data_type_die(struct data_loc_info *dloc, Dwarf_Die *type_die)
1398 {
1399 	struct annotated_op_loc *loc = dloc->op;
1400 	Dwarf_Die cu_die, var_die;
1401 	Dwarf_Die *scopes = NULL;
1402 	int reg, offset = loc->offset;
1403 	int ret = -1;
1404 	int i, nr_scopes;
1405 	int fbreg = -1;
1406 	int fb_offset = 0;
1407 	bool is_fbreg = false;
1408 	bool found = false;
1409 	u64 pc;
1410 	char buf[64];
1411 	enum type_match_result result = PERF_TMR_UNKNOWN;
1412 	const char *offset_sign = "";
1413 
1414 	if (dloc->op->multi_regs)
1415 		snprintf(buf, sizeof(buf), "reg%d, reg%d", dloc->op->reg1, dloc->op->reg2);
1416 	else if (dloc->op->reg1 == DWARF_REG_PC)
1417 		snprintf(buf, sizeof(buf), "PC");
1418 	else
1419 		snprintf(buf, sizeof(buf), "reg%d", dloc->op->reg1);
1420 
1421 	if (offset < 0) {
1422 		offset = -offset;
1423 		offset_sign = "-";
1424 	}
1425 
1426 	pr_debug_dtp("-----------------------------------------------------------\n");
1427 	pr_debug_dtp("find data type for %s%#x(%s) at %s+%#"PRIx64"\n",
1428 		     offset_sign, offset, buf,
1429 		     dloc->ms->sym->name, dloc->ip - dloc->ms->sym->start);
1430 
1431 	/*
1432 	 * IP is a relative instruction address from the start of the map, as
1433 	 * it can be randomized/relocated, it needs to translate to PC which is
1434 	 * a file address for DWARF processing.
1435 	 */
1436 	pc = map__rip_2objdump(dloc->ms->map, dloc->ip);
1437 
1438 	/* Get a compile_unit for this address */
1439 	if (!find_cu_die(dloc->di, pc, &cu_die)) {
1440 		pr_debug_dtp("cannot find CU for address %"PRIx64"\n", pc);
1441 		ann_data_stat.no_cuinfo++;
1442 		return -1;
1443 	}
1444 
1445 	reg = loc->reg1;
1446 	offset = loc->offset;
1447 
1448 	pr_debug_dtp("CU for %s (die:%#lx)\n",
1449 		     dwarf_diename(&cu_die), (long)dwarf_dieoffset(&cu_die));
1450 
1451 	if (reg == DWARF_REG_PC) {
1452 		if (get_global_var_type(&cu_die, dloc, dloc->ip, dloc->var_addr,
1453 					&offset, type_die)) {
1454 			dloc->type_offset = offset;
1455 
1456 			pr_debug_dtp("found by addr=%#"PRIx64" type_offset=%#x\n",
1457 				     dloc->var_addr, offset);
1458 			pr_debug_type_name(type_die, TSR_KIND_TYPE);
1459 			found = true;
1460 			goto out;
1461 		}
1462 	}
1463 
1464 	/* Get a list of nested scopes - i.e. (inlined) functions and blocks. */
1465 	nr_scopes = die_get_scopes(&cu_die, pc, &scopes);
1466 
1467 	if (reg != DWARF_REG_PC && dwarf_hasattr(&scopes[0], DW_AT_frame_base)) {
1468 		Dwarf_Attribute attr;
1469 		Dwarf_Block block;
1470 
1471 		/* Check if the 'reg' is assigned as frame base register */
1472 		if (dwarf_attr(&scopes[0], DW_AT_frame_base, &attr) != NULL &&
1473 		    dwarf_formblock(&attr, &block) == 0 && block.length == 1) {
1474 			switch (*block.data) {
1475 			case DW_OP_reg0 ... DW_OP_reg31:
1476 				fbreg = dloc->fbreg = *block.data - DW_OP_reg0;
1477 				break;
1478 			case DW_OP_call_frame_cfa:
1479 				dloc->fb_cfa = true;
1480 				if (die_get_cfa(dloc->di->dbg, pc, &fbreg,
1481 						&fb_offset) < 0)
1482 					fbreg = -1;
1483 				break;
1484 			default:
1485 				break;
1486 			}
1487 
1488 			pr_debug_dtp("frame base: cfa=%d fbreg=%d\n",
1489 				     dloc->fb_cfa, fbreg);
1490 		}
1491 	}
1492 
1493 retry:
1494 	is_fbreg = (reg == fbreg);
1495 	if (is_fbreg)
1496 		offset = loc->offset - fb_offset;
1497 
1498 	/* Search from the inner-most scope to the outer */
1499 	for (i = nr_scopes - 1; i >= 0; i--) {
1500 		Dwarf_Die mem_die;
1501 		int type_offset = offset;
1502 
1503 		if (reg == DWARF_REG_PC) {
1504 			if (!die_find_variable_by_addr(&scopes[i], dloc->var_addr,
1505 						       &var_die, &type_offset))
1506 				continue;
1507 		} else {
1508 			/* Look up variables/parameters in this scope */
1509 			if (!die_find_variable_by_reg(&scopes[i], pc, reg,
1510 						      &type_offset, is_fbreg, &var_die))
1511 				continue;
1512 		}
1513 
1514 		pr_debug_dtp("found \"%s\" (die: %#lx) in scope=%d/%d (die: %#lx) ",
1515 			     dwarf_diename(&var_die), (long)dwarf_dieoffset(&var_die),
1516 			     i+1, nr_scopes, (long)dwarf_dieoffset(&scopes[i]));
1517 
1518 		/* Found a variable, see if it's correct */
1519 		result = check_variable(dloc, &var_die, &mem_die, reg, type_offset, is_fbreg);
1520 		if (result == PERF_TMR_OK) {
1521 			if (reg == DWARF_REG_PC) {
1522 				pr_debug_dtp("addr=%#"PRIx64" type_offset=%#x\n",
1523 					     dloc->var_addr, type_offset);
1524 			} else if (reg == DWARF_REG_FB || is_fbreg) {
1525 				pr_debug_dtp("stack_offset=%#x type_offset=%#x\n",
1526 					     fb_offset, type_offset);
1527 			} else {
1528 				pr_debug_dtp("type_offset=%#x\n", type_offset);
1529 			}
1530 
1531 			if (!found || is_better_type(type_die, &mem_die)) {
1532 				*type_die = mem_die;
1533 				dloc->type_offset = type_offset;
1534 				found = true;
1535 			}
1536 		} else {
1537 			pr_debug_dtp("failed: %s\n", match_result_str(result));
1538 		}
1539 
1540 		pr_debug_location(&var_die, pc, reg);
1541 		pr_debug_type_name(&mem_die, TSR_KIND_TYPE);
1542 	}
1543 
1544 	if (!found && loc->multi_regs && reg == loc->reg1 && loc->reg1 != loc->reg2) {
1545 		reg = loc->reg2;
1546 		goto retry;
1547 	}
1548 
1549 	if (!found && reg != DWARF_REG_PC) {
1550 		result = find_data_type_block(dloc, &cu_die, scopes,
1551 					      nr_scopes, type_die);
1552 		if (result == PERF_TMR_OK) {
1553 			ann_data_stat.insn_track++;
1554 			found = true;
1555 		}
1556 	}
1557 
1558 out:
1559 	pr_debug_dtp("final result: ");
1560 	if (found) {
1561 		pr_debug_type_name(type_die, TSR_KIND_TYPE);
1562 		ret = 0;
1563 	} else {
1564 		switch (result) {
1565 		case PERF_TMR_NO_TYPE:
1566 		case PERF_TMR_NO_POINTER:
1567 			pr_debug_dtp("%s\n", match_result_str(result));
1568 			ann_data_stat.no_typeinfo++;
1569 			break;
1570 		case PERF_TMR_NO_SIZE:
1571 			pr_debug_dtp("%s\n", match_result_str(result));
1572 			ann_data_stat.invalid_size++;
1573 			break;
1574 		case PERF_TMR_BAD_OFFSET:
1575 			pr_debug_dtp("%s\n", match_result_str(result));
1576 			ann_data_stat.bad_offset++;
1577 			break;
1578 		case PERF_TMR_UNKNOWN:
1579 		case PERF_TMR_BAIL_OUT:
1580 		case PERF_TMR_OK:  /* should not reach here */
1581 		default:
1582 			pr_debug_dtp("no variable found\n");
1583 			ann_data_stat.no_var++;
1584 			break;
1585 		}
1586 		ret = -1;
1587 	}
1588 
1589 	free(scopes);
1590 	return ret;
1591 }
1592 
1593 /**
1594  * find_data_type - Return a data type at the location
1595  * @dloc: data location
1596  *
1597  * This functions searches the debug information of the binary to get the data
1598  * type it accesses.  The exact location is expressed by (ip, reg, offset)
1599  * for pointer variables or (ip, addr) for global variables.  Note that global
1600  * variables might update the @dloc->type_offset after finding the start of the
1601  * variable.  If it cannot find a global variable by address, it tried to find
1602  * a declaration of the variable using var_name.  In that case, @dloc->offset
1603  * won't be updated.
1604  *
1605  * It return %NULL if not found.
1606  */
1607 struct annotated_data_type *find_data_type(struct data_loc_info *dloc)
1608 {
1609 	struct dso *dso = map__dso(dloc->ms->map);
1610 	Dwarf_Die type_die;
1611 
1612 	/*
1613 	 * The type offset is the same as instruction offset by default.
1614 	 * But when finding a global variable, the offset won't be valid.
1615 	 */
1616 	dloc->type_offset = dloc->op->offset;
1617 
1618 	dloc->fbreg = -1;
1619 
1620 	if (find_data_type_die(dloc, &type_die) < 0)
1621 		return NULL;
1622 
1623 	return dso__findnew_data_type(dso, &type_die);
1624 }
1625 
1626 static int alloc_data_type_histograms(struct annotated_data_type *adt, int nr_entries)
1627 {
1628 	int i;
1629 	size_t sz = sizeof(struct type_hist);
1630 
1631 	sz += sizeof(struct type_hist_entry) * adt->self.size;
1632 
1633 	/* Allocate a table of pointers for each event */
1634 	adt->histograms = calloc(nr_entries, sizeof(*adt->histograms));
1635 	if (adt->histograms == NULL)
1636 		return -ENOMEM;
1637 
1638 	/*
1639 	 * Each histogram is allocated for the whole size of the type.
1640 	 * TODO: Probably we can move the histogram to members.
1641 	 */
1642 	for (i = 0; i < nr_entries; i++) {
1643 		adt->histograms[i] = zalloc(sz);
1644 		if (adt->histograms[i] == NULL)
1645 			goto err;
1646 	}
1647 
1648 	adt->nr_histograms = nr_entries;
1649 	return 0;
1650 
1651 err:
1652 	while (--i >= 0)
1653 		zfree(&(adt->histograms[i]));
1654 	zfree(&adt->histograms);
1655 	return -ENOMEM;
1656 }
1657 
1658 static void delete_data_type_histograms(struct annotated_data_type *adt)
1659 {
1660 	for (int i = 0; i < adt->nr_histograms; i++)
1661 		zfree(&(adt->histograms[i]));
1662 
1663 	zfree(&adt->histograms);
1664 	adt->nr_histograms = 0;
1665 }
1666 
1667 void annotated_data_type__tree_delete(struct rb_root *root)
1668 {
1669 	struct annotated_data_type *pos;
1670 
1671 	while (!RB_EMPTY_ROOT(root)) {
1672 		struct rb_node *node = rb_first(root);
1673 
1674 		rb_erase(node, root);
1675 		pos = rb_entry(node, struct annotated_data_type, node);
1676 		delete_members(&pos->self);
1677 		delete_data_type_histograms(pos);
1678 		zfree(&pos->self.type_name);
1679 		free(pos);
1680 	}
1681 }
1682 
1683 /**
1684  * annotated_data_type__update_samples - Update histogram
1685  * @adt: Data type to update
1686  * @evsel: Event to update
1687  * @offset: Offset in the type
1688  * @nr_samples: Number of samples at this offset
1689  * @period: Event count at this offset
1690  *
1691  * This function updates type histogram at @ofs for @evsel.  Samples are
1692  * aggregated before calling this function so it can be called with more
1693  * than one samples at a certain offset.
1694  */
1695 int annotated_data_type__update_samples(struct annotated_data_type *adt,
1696 					struct evsel *evsel, int offset,
1697 					int nr_samples, u64 period)
1698 {
1699 	struct type_hist *h;
1700 
1701 	if (adt == NULL)
1702 		return 0;
1703 
1704 	if (adt->histograms == NULL) {
1705 		int nr = evsel->evlist->core.nr_entries;
1706 
1707 		if (alloc_data_type_histograms(adt, nr) < 0)
1708 			return -1;
1709 	}
1710 
1711 	if (offset < 0 || offset >= adt->self.size)
1712 		return -1;
1713 
1714 	h = adt->histograms[evsel->core.idx];
1715 
1716 	h->nr_samples += nr_samples;
1717 	h->addr[offset].nr_samples += nr_samples;
1718 	h->period += period;
1719 	h->addr[offset].period += period;
1720 	return 0;
1721 }
1722 
1723 static void print_annotated_data_header(struct hist_entry *he, struct evsel *evsel)
1724 {
1725 	struct dso *dso = map__dso(he->ms.map);
1726 	int nr_members = 1;
1727 	int nr_samples = he->stat.nr_events;
1728 	int width = 7;
1729 	const char *val_hdr = "Percent";
1730 
1731 	if (evsel__is_group_event(evsel)) {
1732 		struct hist_entry *pair;
1733 
1734 		list_for_each_entry(pair, &he->pairs.head, pairs.node)
1735 			nr_samples += pair->stat.nr_events;
1736 	}
1737 
1738 	printf("Annotate type: '%s' in %s (%d samples):\n",
1739 	       he->mem_type->self.type_name, dso__name(dso), nr_samples);
1740 
1741 	if (evsel__is_group_event(evsel)) {
1742 		struct evsel *pos;
1743 		int i = 0;
1744 
1745 		nr_members = 0;
1746 		for_each_group_evsel(pos, evsel) {
1747 			if (symbol_conf.skip_empty &&
1748 			    evsel__hists(pos)->stats.nr_samples == 0)
1749 				continue;
1750 
1751 			printf(" event[%d] = %s\n", i++, pos->name);
1752 			nr_members++;
1753 		}
1754 	}
1755 
1756 	if (symbol_conf.show_total_period) {
1757 		width = 11;
1758 		val_hdr = "Period";
1759 	} else if (symbol_conf.show_nr_samples) {
1760 		width = 7;
1761 		val_hdr = "Samples";
1762 	}
1763 
1764 	printf("============================================================================\n");
1765 	printf("%*s %10s %10s  %s\n", (width + 1) * nr_members, val_hdr,
1766 	       "offset", "size", "field");
1767 }
1768 
1769 static void print_annotated_data_value(struct type_hist *h, u64 period, int nr_samples)
1770 {
1771 	double percent = h->period ? (100.0 * period / h->period) : 0;
1772 	const char *color = get_percent_color(percent);
1773 
1774 	if (symbol_conf.show_total_period)
1775 		color_fprintf(stdout, color, " %11" PRIu64, period);
1776 	else if (symbol_conf.show_nr_samples)
1777 		color_fprintf(stdout, color, " %7d", nr_samples);
1778 	else
1779 		color_fprintf(stdout, color, " %7.2f", percent);
1780 }
1781 
1782 static void print_annotated_data_type(struct annotated_data_type *mem_type,
1783 				      struct annotated_member *member,
1784 				      struct evsel *evsel, int indent)
1785 {
1786 	struct annotated_member *child;
1787 	struct type_hist *h = mem_type->histograms[evsel->core.idx];
1788 	int i, nr_events = 0, samples = 0;
1789 	u64 period = 0;
1790 	int width = symbol_conf.show_total_period ? 11 : 7;
1791 	struct evsel *pos;
1792 
1793 	for_each_group_evsel(pos, evsel) {
1794 		h = mem_type->histograms[pos->core.idx];
1795 
1796 		if (symbol_conf.skip_empty &&
1797 		    evsel__hists(pos)->stats.nr_samples == 0)
1798 			continue;
1799 
1800 		samples = 0;
1801 		period = 0;
1802 		for (i = 0; i < member->size; i++) {
1803 			samples += h->addr[member->offset + i].nr_samples;
1804 			period += h->addr[member->offset + i].period;
1805 		}
1806 		print_annotated_data_value(h, period, samples);
1807 		nr_events++;
1808 	}
1809 
1810 	printf(" %#10x %#10x  %*s%s\t%s",
1811 	       member->offset, member->size, indent, "", member->type_name,
1812 	       member->var_name ?: "");
1813 
1814 	if (!list_empty(&member->children))
1815 		printf(" {\n");
1816 
1817 	list_for_each_entry(child, &member->children, node)
1818 		print_annotated_data_type(mem_type, child, evsel, indent + 4);
1819 
1820 	if (!list_empty(&member->children))
1821 		printf("%*s}", (width + 1) * nr_events + 24 + indent, "");
1822 	printf(";\n");
1823 }
1824 
1825 int hist_entry__annotate_data_tty(struct hist_entry *he, struct evsel *evsel)
1826 {
1827 	print_annotated_data_header(he, evsel);
1828 	print_annotated_data_type(he->mem_type, &he->mem_type->self, evsel, 0);
1829 	printf("\n");
1830 
1831 	/* move to the next entry */
1832 	return '>';
1833 }
1834