profile.js 28.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// Copyright 2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


/**
 * Creates a profile object for processing profiling-related events
 * and calculating function execution times.
 *
 * @constructor
 */
35 36 37 38
function Profile() {
  this.codeMap_ = new CodeMap();
  this.topDownTree_ = new CallTree();
  this.bottomUpTree_ = new CallTree();
39
  this.c_entries_ = {};
40
  this.ticks_ = [];
41 42 43 44 45 46 47 48 49
};


/**
 * Returns whether a function with the specified name must be skipped.
 * Should be overriden by subclasses.
 *
 * @param {string} name Function name.
 */
50
Profile.prototype.skipThisFunction = function(name) {
51 52 53 54
  return false;
};


55 56 57 58 59 60
/**
 * Enum for profiler operations that involve looking up existing
 * code entries.
 *
 * @enum {number}
 */
61
Profile.Operation = {
62
  MOVE: 0,
63 64
  DELETE: 1,
  TICK: 2
65 66 67
};


68 69 70 71 72 73 74 75 76 77 78 79
/**
 * Enum for code state regarding its dynamic optimization.
 *
 * @enum {number}
 */
Profile.CodeState = {
  COMPILED: 0,
  OPTIMIZABLE: 1,
  OPTIMIZED: 2
};


80 81 82
/**
 * Called whenever the specified operation has failed finding a function
 * containing the specified address. Should be overriden by subclasses.
83
 * See the Profile.Operation enum for the list of
84
 * possible operations.
85
 *
86
 * @param {number} operation Operation.
87
 * @param {number} addr Address of the unknown code.
88 89 90
 * @param {number} opt_stackPos If an unknown address is encountered
 *     during stack strace processing, specifies a position of the frame
 *     containing the address.
91
 */
92
Profile.prototype.handleUnknownCode = function(
93
    operation, addr, opt_stackPos) {
94 95 96 97
};


/**
98 99 100 101 102 103
 * Registers a library.
 *
 * @param {string} name Code entry name.
 * @param {number} startAddr Starting address.
 * @param {number} endAddr Ending address.
 */
104
Profile.prototype.addLibrary = function(
105
    name, startAddr, endAddr) {
106
  var entry = new CodeMap.CodeEntry(
107
      endAddr - startAddr, name, 'SHARED_LIB');
108 109 110 111 112 113 114
  this.codeMap_.addLibrary(startAddr, entry);
  return entry;
};


/**
 * Registers statically compiled code entry.
115 116 117 118 119
 *
 * @param {string} name Code entry name.
 * @param {number} startAddr Starting address.
 * @param {number} endAddr Ending address.
 */
120
Profile.prototype.addStaticCode = function(
121
    name, startAddr, endAddr) {
122
  var entry = new CodeMap.CodeEntry(
123
      endAddr - startAddr, name, 'CPP');
124 125
  this.codeMap_.addStaticCode(startAddr, entry);
  return entry;
126 127 128 129 130 131 132 133 134 135 136
};


/**
 * Registers dynamic (JIT-compiled) code entry.
 *
 * @param {string} type Code entry type.
 * @param {string} name Code entry name.
 * @param {number} start Starting address.
 * @param {number} size Code entry size.
 */
137
Profile.prototype.addCode = function(
138
    type, name, timestamp, start, size) {
139
  var entry = new Profile.DynamicCodeEntry(size, type, name);
140 141
  this.codeMap_.addCode(start, entry);
  return entry;
142 143 144
};


145
/**
146
 * Registers dynamic (JIT-compiled) code entry.
147
 *
148 149 150 151 152 153 154 155
 * @param {string} type Code entry type.
 * @param {string} name Code entry name.
 * @param {number} start Starting address.
 * @param {number} size Code entry size.
 * @param {number} funcAddr Shared function object address.
 * @param {Profile.CodeState} state Optimization state.
 */
Profile.prototype.addFuncCode = function(
156
    type, name, timestamp, start, size, funcAddr, state) {
157 158 159 160 161 162 163 164 165
  // As code and functions are in the same address space,
  // it is safe to put them in a single code map.
  var func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
  if (!func) {
    func = new Profile.FunctionEntry(name);
    this.codeMap_.addCode(funcAddr, func);
  } else if (func.name !== name) {
    // Function object has been overwritten with a new one.
    func.name = name;
166
  }
167
  var entry = this.codeMap_.findDynamicEntryByStartAddress(start);
168 169 170 171
  if (entry) {
    if (entry.size === size && entry.func === func) {
      // Entry state has changed.
      entry.state = state;
172 173 174
    } else {
      this.codeMap_.deleteCode(start);
      entry = null;
175
    }
176 177
  }
  if (!entry) {
178 179
    entry = new Profile.DynamicFuncCodeEntry(size, type, func, state);
    this.codeMap_.addCode(start, entry);
180
  }
181
  return entry;
182 183 184
};


185 186 187 188 189 190
/**
 * Reports about moving of a dynamic code entry.
 *
 * @param {number} from Current code entry address.
 * @param {number} to New code entry address.
 */
191
Profile.prototype.moveCode = function(from, to) {
192 193 194
  try {
    this.codeMap_.moveCode(from, to);
  } catch (e) {
195
    this.handleUnknownCode(Profile.Operation.MOVE, from);
196 197 198
  }
};

199 200 201 202
Profile.prototype.deoptCode = function(
    timestamp, code, inliningId, scriptOffset, bailoutType,
    sourcePositionText, deoptReasonText) {
};
203

204 205 206 207 208 209 210 211 212 213 214 215 216
/**
 * Reports about deletion of a dynamic code entry.
 *
 * @param {number} start Starting address.
 */
Profile.prototype.deleteCode = function(start) {
  try {
    this.codeMap_.deleteCode(start);
  } catch (e) {
    this.handleUnknownCode(Profile.Operation.DELETE, start);
  }
};

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
/**
 * Adds source positions for given code.
 */
Profile.prototype.addSourcePositions = function(
    start, script, startPos, endPos, sourcePositions, inliningPositions,
    inlinedFunctions) {
  // CLI does not need source code => ignore.
};

/**
 * Adds script source code.
 */
Profile.prototype.addScriptSource = function(script, source) {
  // CLI does not need source code => ignore.
};
232

233 234 235 236 237 238
/**
 * Reports about moving of a dynamic code entry.
 *
 * @param {number} from Current code entry address.
 * @param {number} to New code entry address.
 */
239
Profile.prototype.moveFunc = function(from, to) {
240 241 242 243 244 245
  if (this.codeMap_.findDynamicEntryByStartAddress(from)) {
    this.codeMap_.moveCode(from, to);
  }
};


246 247 248 249 250
/**
 * Retrieves a code entry by an address.
 *
 * @param {number} addr Entry address.
 */
251
Profile.prototype.findEntry = function(addr) {
252 253 254 255
  return this.codeMap_.findEntry(addr);
};


256 257 258 259 260 261
/**
 * Records a tick event. Stack must contain a sequence of
 * addresses starting with the program counter value.
 *
 * @param {Array<number>} stack Stack sample.
 */
262
Profile.prototype.recordTick = function(time_ns, vmState, stack) {
263 264 265 266 267 268 269 270 271 272 273 274 275
  var processedStack = this.resolveAndFilterFuncs_(stack);
  this.bottomUpTree_.addPath(processedStack);
  processedStack.reverse();
  this.topDownTree_.addPath(processedStack);
};


/**
 * Translates addresses into function names and filters unneeded
 * functions.
 *
 * @param {Array<number>} stack Stack sample.
 */
276
Profile.prototype.resolveAndFilterFuncs_ = function(stack) {
277
  var result = [];
278 279
  var last_seen_c_function = '';
  var look_for_first_c_function = false;
280 281 282 283
  for (var i = 0; i < stack.length; ++i) {
    var entry = this.codeMap_.findEntry(stack[i]);
    if (entry) {
      var name = entry.getName();
jkummerow's avatar
jkummerow committed
284
      if (i === 0 && (entry.type === 'CPP' || entry.type === 'SHARED_LIB')) {
285 286
        look_for_first_c_function = true;
      }
jkummerow's avatar
jkummerow committed
287 288
      if (look_for_first_c_function && entry.type === 'CPP') {
        last_seen_c_function = name;
289
      }
290 291 292 293
      if (!this.skipThisFunction(name)) {
        result.push(name);
      }
    } else {
jkummerow's avatar
jkummerow committed
294 295 296 297 298 299 300 301 302 303 304 305
      this.handleUnknownCode(Profile.Operation.TICK, stack[i], i);
      if (i === 0) result.push("UNKNOWN");
    }
    if (look_for_first_c_function &&
        i > 0 &&
        (!entry || entry.type !== 'CPP') &&
        last_seen_c_function !== '') {
      if (this.c_entries_[last_seen_c_function] === undefined) {
        this.c_entries_[last_seen_c_function] = 0;
      }
      this.c_entries_[last_seen_c_function]++;
      look_for_first_c_function = false;  // Found it, we're done.
306 307 308 309 310 311 312
    }
  }
  return result;
};


/**
313
 * Performs a BF traversal of the top down call graph.
314
 *
315
 * @param {function(CallTree.Node)} f Visitor function.
316
 */
317
Profile.prototype.traverseTopDownTree = function(f) {
318 319 320 321 322
  this.topDownTree_.traverse(f);
};


/**
323
 * Performs a BF traversal of the bottom up call graph.
324
 *
325
 * @param {function(CallTree.Node)} f Visitor function.
326
 */
327
Profile.prototype.traverseBottomUpTree = function(f) {
328 329 330 331
  this.bottomUpTree_.traverse(f);
};


332
/**
333 334
 * Calculates a top down profile for a node with the specified label.
 * If no name specified, returns the whole top down calls tree.
335
 *
336
 * @param {string} opt_label Node label.
337
 */
338
Profile.prototype.getTopDownProfile = function(opt_label) {
339 340 341 342 343 344 345 346 347 348
  return this.getTreeProfile_(this.topDownTree_, opt_label);
};


/**
 * Calculates a bottom up profile for a node with the specified label.
 * If no name specified, returns the whole bottom up calls tree.
 *
 * @param {string} opt_label Node label.
 */
349
Profile.prototype.getBottomUpProfile = function(opt_label) {
350
  return this.getTreeProfile_(this.bottomUpTree_, opt_label);
351 352 353 354
};


/**
355
 * Helper function for calculating a tree profile.
356
 *
357
 * @param {Profile.CallTree} tree Call tree.
358
 * @param {string} opt_label Node label.
359
 */
360
Profile.prototype.getTreeProfile_ = function(tree, opt_label) {
361 362 363
  if (!opt_label) {
    tree.computeTotalWeights();
    return tree;
364
  } else {
365 366 367
    var subTree = tree.cloneSubtree(opt_label);
    subTree.computeTotalWeights();
    return subTree;
368 369 370 371
  }
};


372
/**
373 374
 * Calculates a flat profile of callees starting from a node with
 * the specified label. If no name specified, starts from the root.
375
 *
376
 * @param {string} opt_label Starting node label.
377
 */
378 379 380
Profile.prototype.getFlatProfile = function(opt_label) {
  var counters = new CallTree();
  var rootLabel = opt_label || CallTree.ROOT_NODE_LABEL;
381
  var precs = {};
382 383 384
  precs[rootLabel] = 0;
  var root = counters.findOrAddChild(rootLabel);

385 386 387 388 389 390
  this.topDownTree_.computeTotalWeights();
  this.topDownTree_.traverseInDepth(
    function onEnter(node) {
      if (!(node.label in precs)) {
        precs[node.label] = 0;
      }
391 392 393 394 395 396 397 398 399 400 401 402 403
      var nodeLabelIsRootLabel = node.label == rootLabel;
      if (nodeLabelIsRootLabel || precs[rootLabel] > 0) {
        if (precs[rootLabel] == 0) {
          root.selfWeight += node.selfWeight;
          root.totalWeight += node.totalWeight;
        } else {
          var rec = root.findOrAddChild(node.label);
          rec.selfWeight += node.selfWeight;
          if (nodeLabelIsRootLabel || precs[node.label] == 0) {
            rec.totalWeight += node.totalWeight;
          }
        }
        precs[node.label]++;
404 405 406
      }
    },
    function onExit(node) {
407 408 409
      if (node.label == rootLabel || precs[rootLabel] > 0) {
        precs[node.label]--;
      }
410
    },
411 412 413 414 415 416 417 418 419 420 421 422
    null);

  if (!opt_label) {
    // If we have created a flat profile for the whole program, we don't
    // need an explicit root in it. Thus, replace the counters tree
    // root with the node corresponding to the whole program.
    counters.root_ = root;
  } else {
    // Propagate weights so percents can be calculated correctly.
    counters.getRoot().selfWeight = root.selfWeight;
    counters.getRoot().totalWeight = root.totalWeight;
  }
423
  return counters;
424 425 426
};


427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
Profile.CEntryNode = function(name, ticks) {
  this.name = name;
  this.ticks = ticks;
}


Profile.prototype.getCEntryProfile = function() {
  var result = [new Profile.CEntryNode("TOTAL", 0)];
  var total_ticks = 0;
  for (var f in this.c_entries_) {
    var ticks = this.c_entries_[f];
    total_ticks += ticks;
    result.push(new Profile.CEntryNode(f, ticks));
  }
  result[0].ticks = total_ticks;  // Sorting will keep this at index 0.
  result.sort(function(n1, n2) {
    return n2.ticks - n1.ticks || (n2.name < n1.name ? -1 : 1)
  });
  return result;
}


449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
/**
 * Cleans up function entries that are not referenced by code entries.
 */
Profile.prototype.cleanUpFuncEntries = function() {
  var referencedFuncEntries = [];
  var entries = this.codeMap_.getAllDynamicEntriesWithAddresses();
  for (var i = 0, l = entries.length; i < l; ++i) {
    if (entries[i][1].constructor === Profile.FunctionEntry) {
      entries[i][1].used = false;
    }
  }
  for (var i = 0, l = entries.length; i < l; ++i) {
    if ("func" in entries[i][1]) {
      entries[i][1].func.used = true;
    }
  }
  for (var i = 0, l = entries.length; i < l; ++i) {
    if (entries[i][1].constructor === Profile.FunctionEntry &&
        !entries[i][1].used) {
      this.codeMap_.deleteCode(entries[i][0]);
    }
  }
};


474 475 476 477 478 479 480 481
/**
 * Creates a dynamic code entry.
 *
 * @param {number} size Code size.
 * @param {string} type Code type.
 * @param {string} name Function name.
 * @constructor
 */
482
Profile.DynamicCodeEntry = function(size, type, name) {
483
  CodeMap.CodeEntry.call(this, size, name, type);
484 485 486 487 488 489
};


/**
 * Returns node name.
 */
490
Profile.DynamicCodeEntry.prototype.getName = function() {
491
  return this.type + ': ' + this.name;
492 493 494
};


495 496 497
/**
 * Returns raw node name (without type decoration).
 */
498
Profile.DynamicCodeEntry.prototype.getRawName = function() {
499 500 501 502
  return this.name;
};


503
Profile.DynamicCodeEntry.prototype.isJSFunction = function() {
504 505 506 507
  return false;
};


508 509 510 511 512
Profile.DynamicCodeEntry.prototype.toString = function() {
  return this.getName() + ': ' + this.size.toString(16);
};


513 514 515 516 517 518 519 520 521 522
/**
 * Creates a dynamic code entry.
 *
 * @param {number} size Code size.
 * @param {string} type Code type.
 * @param {Profile.FunctionEntry} func Shared function entry.
 * @param {Profile.CodeState} state Code optimization state.
 * @constructor
 */
Profile.DynamicFuncCodeEntry = function(size, type, func, state) {
523
  CodeMap.CodeEntry.call(this, size, '', type);
524 525 526 527 528 529
  this.func = func;
  this.state = state;
};

Profile.DynamicFuncCodeEntry.STATE_PREFIX = ["", "~", "*"];

530 531 532 533 534 535 536
/**
 * Returns state.
 */
Profile.DynamicFuncCodeEntry.prototype.getState = function() {
  return Profile.DynamicFuncCodeEntry.STATE_PREFIX[this.state];
};

537 538 539 540 541
/**
 * Returns node name.
 */
Profile.DynamicFuncCodeEntry.prototype.getName = function() {
  var name = this.func.getName();
542
  return this.type + ': ' + this.getState() + name;
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
};


/**
 * Returns raw node name (without type decoration).
 */
Profile.DynamicFuncCodeEntry.prototype.getRawName = function() {
  return this.func.getName();
};


Profile.DynamicFuncCodeEntry.prototype.isJSFunction = function() {
  return true;
};


559 560 561 562 563
Profile.DynamicFuncCodeEntry.prototype.toString = function() {
  return this.getName() + ': ' + this.size.toString(16);
};


564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
/**
 * Creates a shared function object entry.
 *
 * @param {string} name Function name.
 * @constructor
 */
Profile.FunctionEntry = function(name) {
  CodeMap.CodeEntry.call(this, 0, name);
};


/**
 * Returns node name.
 */
Profile.FunctionEntry.prototype.getName = function() {
  var name = this.name;
  if (name.length == 0) {
    name = '<anonymous>';
  } else if (name.charAt(0) == ' ') {
    // An anonymous function with location: " aaa.js:10".
    name = '<anonymous>' + name;
  }
  return name;
587 588
};

589
Profile.FunctionEntry.prototype.toString = CodeMap.CodeEntry.prototype.toString;
590

591 592 593 594 595
/**
 * Constructs a call graph.
 *
 * @constructor
 */
596 597 598
function CallTree() {
  this.root_ = new CallTree.Node(
      CallTree.ROOT_NODE_LABEL);
599 600 601
};


602 603 604
/**
 * The label of the root node.
 */
605
CallTree.ROOT_NODE_LABEL = '';
606 607


608 609 610
/**
 * @private
 */
611
CallTree.prototype.totalsComputed_ = false;
612 613


614 615 616
/**
 * Returns the tree root.
 */
617
CallTree.prototype.getRoot = function() {
618 619 620 621
  return this.root_;
};


622 623 624 625 626
/**
 * Adds the specified call path, constructing nodes as necessary.
 *
 * @param {Array<string>} path Call path.
 */
627
CallTree.prototype.addPath = function(path) {
628 629 630 631 632 633 634 635 636 637 638 639
  if (path.length == 0) {
    return;
  }
  var curr = this.root_;
  for (var i = 0; i < path.length; ++i) {
    curr = curr.findOrAddChild(path[i]);
  }
  curr.selfWeight++;
  this.totalsComputed_ = false;
};


640 641 642 643 644 645 646
/**
 * Finds an immediate child of the specified parent with the specified
 * label, creates a child node if necessary. If a parent node isn't
 * specified, uses tree root.
 *
 * @param {string} label Child node label.
 */
647
CallTree.prototype.findOrAddChild = function(label) {
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
  return this.root_.findOrAddChild(label);
};


/**
 * Creates a subtree by cloning and merging all subtrees rooted at nodes
 * with a given label. E.g. cloning the following call tree on label 'A'
 * will give the following result:
 *
 *           <A>--<B>                                     <B>
 *          /                                            /
 *     <root>             == clone on 'A' ==>  <root>--<A>
 *          \                                            \
 *           <C>--<A>--<D>                                <D>
 *
 * And <A>'s selfWeight will be the sum of selfWeights of <A>'s from the
 * source call tree.
 *
 * @param {string} label The label of the new root node.
 */
668 669
CallTree.prototype.cloneSubtree = function(label) {
  var subTree = new CallTree();
670 671 672 673 674 675 676 677 678
  this.traverse(function(node, parent) {
    if (!parent && node.label != label) {
      return null;
    }
    var child = (parent ? parent : subTree).findOrAddChild(node.label);
    child.selfWeight += node.selfWeight;
    return child;
  });
  return subTree;
679 680 681
};


682 683 684
/**
 * Computes total weights in the call graph.
 */
685
CallTree.prototype.computeTotalWeights = function() {
686 687 688 689 690 691 692 693 694
  if (this.totalsComputed_) {
    return;
  }
  this.root_.computeTotalWeight();
  this.totalsComputed_ = true;
};


/**
695 696 697
 * Traverses the call graph in preorder. This function can be used for
 * building optionally modified tree clones. This is the boilerplate code
 * for this scenario:
698
 *
699 700 701 702 703 704 705
 * callTree.traverse(function(node, parentClone) {
 *   var nodeClone = cloneNode(node);
 *   if (parentClone)
 *     parentClone.addChild(nodeClone);
 *   return nodeClone;
 * });
 *
706
 * @param {function(CallTree.Node, *)} f Visitor function.
707
 *    The second parameter is the result of calling 'f' on the parent node.
708
 */
709
CallTree.prototype.traverse = function(f) {
710
  var pairsToProcess = new ConsArray();
711
  pairsToProcess.concat([{node: this.root_, param: null}]);
712 713
  while (!pairsToProcess.atEnd()) {
    var pair = pairsToProcess.next();
714 715
    var node = pair.node;
    var newParam = f(node, pair.param);
716 717 718 719
    var morePairsToProcess = [];
    node.forEachChild(function (child) {
        morePairsToProcess.push({node: child, param: newParam}); });
    pairsToProcess.concat(morePairsToProcess);
720 721 722 723 724 725 726
  }
};


/**
 * Performs an indepth call graph traversal.
 *
727
 * @param {function(CallTree.Node)} enter A function called
728
 *     prior to visiting node's children.
729
 * @param {function(CallTree.Node)} exit A function called
730 731
 *     after visiting node's children.
 */
732
CallTree.prototype.traverseInDepth = function(enter, exit) {
733 734 735 736 737
  function traverse(node) {
    enter(node);
    node.forEachChild(traverse);
    exit(node);
  }
738
  traverse(this.root_);
739 740 741 742 743 744 745
};


/**
 * Constructs a call graph node.
 *
 * @param {string} label Node label.
746
 * @param {CallTree.Node} opt_parent Node parent.
747
 */
748
CallTree.Node = function(label, opt_parent) {
749 750 751 752 753 754 755 756 757 758 759
  this.label = label;
  this.parent = opt_parent;
  this.children = {};
};


/**
 * Node self weight (how many times this node was the last node in
 * a call path).
 * @type {number}
 */
760
CallTree.Node.prototype.selfWeight = 0;
761 762 763 764 765 766


/**
 * Node total weight (includes weights of all children).
 * @type {number}
 */
767
CallTree.Node.prototype.totalWeight = 0;
768 769 770 771 772 773 774


/**
 * Adds a child node.
 *
 * @param {string} label Child node label.
 */
775 776
CallTree.Node.prototype.addChild = function(label) {
  var child = new CallTree.Node(label, this);
777 778 779 780 781 782 783 784
  this.children[label] = child;
  return child;
};


/**
 * Computes node's total weight.
 */
785
CallTree.Node.prototype.computeTotalWeight =
786 787 788 789 790 791 792 793 794 795 796
    function() {
  var totalWeight = this.selfWeight;
  this.forEachChild(function(child) {
      totalWeight += child.computeTotalWeight(); });
  return this.totalWeight = totalWeight;
};


/**
 * Returns all node's children as an array.
 */
797
CallTree.Node.prototype.exportChildren = function() {
798 799 800 801 802 803 804 805 806 807 808
  var result = [];
  this.forEachChild(function (node) { result.push(node); });
  return result;
};


/**
 * Finds an immediate child with the specified label.
 *
 * @param {string} label Child node label.
 */
809
CallTree.Node.prototype.findChild = function(label) {
810 811 812 813 814 815 816 817 818 819
  return this.children[label] || null;
};


/**
 * Finds an immediate child with the specified label, creates a child
 * node if necessary.
 *
 * @param {string} label Child node label.
 */
820
CallTree.Node.prototype.findOrAddChild = function(label) {
821 822 823 824 825 826 827
  return this.findChild(label) || this.addChild(label);
};


/**
 * Calls the specified function for every child.
 *
828
 * @param {function(CallTree.Node)} f Visitor function.
829
 */
830
CallTree.Node.prototype.forEachChild = function(f) {
831 832 833 834 835 836 837 838 839
  for (var c in this.children) {
    f(this.children[c]);
  }
};


/**
 * Walks up from the current node up to the call tree root.
 *
840
 * @param {function(CallTree.Node)} f Visitor function.
841
 */
842
CallTree.Node.prototype.walkUpToRoot = function(f) {
843 844 845 846 847 848 849 850 851 852
  for (var curr = this; curr != null; curr = curr.parent) {
    f(curr);
  }
};


/**
 * Tries to find a node with the specified path.
 *
 * @param {Array<string>} labels The path.
853
 * @param {function(CallTree.Node)} opt_f Visitor function.
854
 */
855
CallTree.Node.prototype.descendToChild = function(
856 857 858 859 860 861 862 863 864 865
    labels, opt_f) {
  for (var pos = 0, curr = this; pos < labels.length && curr != null; pos++) {
    var child = curr.findChild(labels[pos]);
    if (opt_f) {
      opt_f(child, pos);
    }
    curr = child;
  }
  return curr;
};
866 867 868 869 870 871

function JsonProfile() {
  this.codeMap_ = new CodeMap();
  this.codeEntries_ = [];
  this.functionEntries_ = [];
  this.ticks_ = [];
872
  this.scripts_ = [];
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
}

JsonProfile.prototype.addLibrary = function(
    name, startAddr, endAddr) {
  var entry = new CodeMap.CodeEntry(
      endAddr - startAddr, name, 'SHARED_LIB');
  this.codeMap_.addLibrary(startAddr, entry);

  entry.codeId = this.codeEntries_.length;
  this.codeEntries_.push({name : entry.name, type : entry.type});
  return entry;
};

JsonProfile.prototype.addStaticCode = function(
    name, startAddr, endAddr) {
  var entry = new CodeMap.CodeEntry(
      endAddr - startAddr, name, 'CPP');
  this.codeMap_.addStaticCode(startAddr, entry);

  entry.codeId = this.codeEntries_.length;
  this.codeEntries_.push({name : entry.name, type : entry.type});
  return entry;
};

JsonProfile.prototype.addCode = function(
898
    kind, name, timestamp, start, size) {
899 900 901 902 903 904 905 906
  let codeId = this.codeEntries_.length;
  // Find out if we have a static code entry for the code. If yes, we will
  // make sure it is written to the JSON file just once.
  let staticEntry = this.codeMap_.findAddress(start);
  if (staticEntry && staticEntry.entry.type === 'CPP') {
    codeId = staticEntry.entry.codeId;
  }

907 908 909
  var entry = new CodeMap.CodeEntry(size, name, 'CODE');
  this.codeMap_.addCode(start, entry);

910 911
  entry.codeId = codeId;
  this.codeEntries_[codeId] = {
912 913 914 915
    name : entry.name,
    timestamp: timestamp,
    type : entry.type,
    kind : kind
916
  };
917 918 919 920 921

  return entry;
};

JsonProfile.prototype.addFuncCode = function(
922
    kind, name, timestamp, start, size, funcAddr, state) {
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
  // As code and functions are in the same address space,
  // it is safe to put them in a single code map.
  var func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
  if (!func) {
    var func = new CodeMap.CodeEntry(0, name, 'SFI');
    this.codeMap_.addCode(funcAddr, func);

    func.funcId = this.functionEntries_.length;
    this.functionEntries_.push({name : name, codes : []});
  } else if (func.name !== name) {
    // Function object has been overwritten with a new one.
    func.name = name;

    func.funcId = this.functionEntries_.length;
    this.functionEntries_.push({name : name, codes : []});
  }
  // TODO(jarin): Insert the code object into the SFI's code list.
  var entry = this.codeMap_.findDynamicEntryByStartAddress(start);
  if (entry) {
    if (entry.size === size && entry.func === func) {
      // Entry state has changed.
      entry.state = state;
945 946 947
    } else {
      this.codeMap_.deleteCode(start);
      entry = null;
948
    }
949 950 951
  }
  if (!entry) {
    entry = new CodeMap.CodeEntry(size, name, 'JS');
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    this.codeMap_.addCode(start, entry);

    entry.codeId = this.codeEntries_.length;

    this.functionEntries_[func.funcId].codes.push(entry.codeId);

    if (state === 0) {
      kind = "Builtin";
    } else if (state === 1) {
      kind = "Unopt";
    } else if (state === 2) {
      kind = "Opt";
    }

    this.codeEntries_.push({
        name : entry.name,
        type : entry.type,
        kind : kind,
970 971
        func : func.funcId,
        tm : timestamp
972 973 974 975 976 977 978 979 980 981 982 983 984
    });
  }
  return entry;
};

JsonProfile.prototype.moveCode = function(from, to) {
  try {
    this.codeMap_.moveCode(from, to);
  } catch (e) {
    printErr("Move: unknown source " + from);
  }
};

985 986 987 988 989 990 991
JsonProfile.prototype.addSourcePositions = function(
    start, script, startPos, endPos, sourcePositions, inliningPositions,
    inlinedFunctions) {
  var entry = this.codeMap_.findDynamicEntryByStartAddress(start);
  if (!entry) return;
  var codeId = entry.codeId;

992
  // Resolve the inlined functions list.
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
  if (inlinedFunctions.length > 0) {
    inlinedFunctions = inlinedFunctions.substring(1).split("S");
    for (var i = 0; i < inlinedFunctions.length; i++) {
      var funcAddr = parseInt(inlinedFunctions[i]);
      var func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
      if (!func || func.funcId === undefined) {
        printErr("Could not find function " + inlinedFunctions[i]);
        inlinedFunctions[i] = null;
      } else {
        inlinedFunctions[i] = func.funcId;
      }
    }
  } else {
    inlinedFunctions = [];
  }

  this.codeEntries_[entry.codeId].source = {
    script : script,
    start : startPos,
    end : endPos,
    positions : sourcePositions,
    inlined : inliningPositions,
    fns : inlinedFunctions
  };
};

1019 1020
JsonProfile.prototype.addScriptSource = function(script, url, source) {
  this.scripts_[script] = {
1021 1022
    name : url,
    source : source
1023
  };
1024 1025 1026
};


1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
JsonProfile.prototype.deoptCode = function(
    timestamp, code, inliningId, scriptOffset, bailoutType,
    sourcePositionText, deoptReasonText) {
  let entry = this.codeMap_.findDynamicEntryByStartAddress(code);
  if (entry) {
    let codeId = entry.codeId;
    if (!this.codeEntries_[codeId].deopt) {
      // Only add the deopt if there was no deopt before.
      // The subsequent deoptimizations should be lazy deopts for
      // other on-stack activations.
      this.codeEntries_[codeId].deopt = {
          tm : timestamp,
          inliningId : inliningId,
          scriptOffset : scriptOffset,
          posText : sourcePositionText,
          reason : deoptReasonText,
          bailoutType : bailoutType
      };
    }
  }
};

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
JsonProfile.prototype.deleteCode = function(start) {
  try {
    this.codeMap_.deleteCode(start);
  } catch (e) {
    printErr("Delete: unknown address " + start);
  }
};

JsonProfile.prototype.moveFunc = function(from, to) {
  if (this.codeMap_.findDynamicEntryByStartAddress(from)) {
    this.codeMap_.moveCode(from, to);
  }
};

JsonProfile.prototype.findEntry = function(addr) {
  return this.codeMap_.findEntry(addr);
};

JsonProfile.prototype.recordTick = function(time_ns, vmState, stack) {
  // TODO(jarin) Resolve the frame-less case (when top of stack is
  // known code).
  var processedStack = [];
  for (var i = 0; i < stack.length; i++) {
    var resolved = this.codeMap_.findAddress(stack[i]);
    if (resolved) {
      processedStack.push(resolved.entry.codeId, resolved.offset);
    } else {
      processedStack.push(-1, stack[i]);
    }
  }
  this.ticks_.push({ tm : time_ns, vm : vmState, s : processedStack });
};

1082 1083 1084 1085
function writeJson(s) {
  write(JSON.stringify(s, null, 2));
}

1086
JsonProfile.prototype.writeJson = function() {
1087 1088 1089
  // Write out the JSON in a partially manual way to avoid creating too-large
  // strings in one JSON.stringify call when there are a lot of ticks.
  write('{\n')
1090 1091 1092 1093 1094 1095 1096 1097 1098

  write('  "code": ');
  writeJson(this.codeEntries_);
  write(',\n');

  write('  "functions": ');
  writeJson(this.functionEntries_);
  write(',\n');

1099 1100
  write('  "ticks": [\n');
  for (var i = 0; i < this.ticks_.length; i++) {
1101 1102
    write('    ');
    writeJson(this.ticks_[i]);
1103 1104 1105 1106 1107 1108
    if (i < this.ticks_.length - 1) {
      write(',\n');
    } else {
      write('\n');
    }
  }
1109 1110 1111 1112 1113
  write('  ],\n');

  write('  "scripts": ');
  writeJson(this.scripts_);

1114
  write('}\n');
1115
};