Bug 1072903 - TraceLogger: Part 3: Refactor into TraceLoggerGraph, TraceLoggerThread and TraceLoggerThreadState, r=bbouvier
authorHannes Verschore <hv1989@gmail.com>
Thu, 20 Nov 2014 17:44:00 +0100
changeset 247493 12348c397b086e2a6337034325a559c9876a3dfb
parent 247492 63b734ac95b2f1f3c7ca2cf83d8f511599d7ab8d
child 247494 04988ab0c1dad724475c7d932ccf11edf28155bb
push id4489
push userraliiev@mozilla.com
push dateMon, 23 Feb 2015 15:17:55 +0000
treeherdermozilla-beta@fd7c3dc24146 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersbbouvier
bugs1072903
milestone37.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1072903 - TraceLogger: Part 3: Refactor into TraceLoggerGraph, TraceLoggerThread and TraceLoggerThreadState, r=bbouvier
js/src/builtin/TestingFunctions.cpp
js/src/frontend/BytecodeCompiler.cpp
js/src/jit/Bailouts.cpp
js/src/jit/BaselineBailouts.cpp
js/src/jit/BaselineCompiler.cpp
js/src/jit/BaselineJIT.cpp
js/src/jit/CodeGenerator.cpp
js/src/jit/Ion.cpp
js/src/jit/JitFrames.cpp
js/src/jit/MacroAssembler.cpp
js/src/jit/VMFunctions.cpp
js/src/jit/arm/CodeGenerator-arm.cpp
js/src/jit/shared/CodeGenerator-shared.cpp
js/src/jsgc.cpp
js/src/moz.build
js/src/vm/HelperThreads.cpp
js/src/vm/Interpreter.cpp
js/src/vm/RegExpObject.cpp
js/src/vm/Runtime.h
js/src/vm/TraceLogging.cpp
js/src/vm/TraceLogging.h
js/src/vm/TraceLoggingGraph.cpp
js/src/vm/TraceLoggingGraph.h
js/src/vm/TraceLoggingTypes.h
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -1668,27 +1668,27 @@ TimesAccessed(JSContext *cx, unsigned ar
     args.rval().setInt32(++accessed);
     return true;
 }
 
 static bool
 EnableTraceLogger(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     args.rval().setBoolean(TraceLoggerEnable(logger, cx));
 
     return true;
 }
 
 static bool
 DisableTraceLogger(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     args.rval().setBoolean(TraceLoggerDisable(logger));
 
     return true;
 }
 
 #ifdef DEBUG
 static bool
 DumpObject(JSContext *cx, unsigned argc, jsval *vp)
--- a/js/src/frontend/BytecodeCompiler.cpp
+++ b/js/src/frontend/BytecodeCompiler.cpp
@@ -215,17 +215,17 @@ frontend::CompileScript(ExclusiveContext
                         JSString *source_ /* = nullptr */,
                         unsigned staticLevel /* = 0 */,
                         SourceCompressionTask *extraSct /* = nullptr */)
 {
     MOZ_ASSERT(srcBuf.get());
 
     RootedString source(cx, source_);
 
-    js::TraceLogger *logger = nullptr;
+    js::TraceLoggerThread *logger = nullptr;
     if (cx->isJSContext())
         logger = TraceLoggerForMainThread(cx->asJSContext()->runtime());
     else
         logger = TraceLoggerForCurrentThread();
     uint32_t logId = js::TraceLogCreateTextId(logger, options);
     js::AutoTraceLog scriptLogger(logger, logId);
     js::AutoTraceLog typeLogger(logger, TraceLogger_ParserCompileScript);
 
@@ -468,17 +468,17 @@ frontend::CompileLazyFunction(JSContext 
     CompileOptions options(cx, lazy->version());
     options.setMutedErrors(lazy->mutedErrors())
            .setFileAndLine(lazy->source()->filename(), lazy->lineno())
            .setColumn(lazy->column())
            .setCompileAndGo(true)
            .setNoScriptRval(false)
            .setSelfHostingMode(false);
 
-    js::TraceLogger *logger = js::TraceLoggerForMainThread(cx->runtime());
+    js::TraceLoggerThread *logger = js::TraceLoggerForMainThread(cx->runtime());
     uint32_t logId = js::TraceLogCreateTextId(logger, options);
     js::AutoTraceLog scriptLogger(logger, logId);
     js::AutoTraceLog typeLogger(logger, TraceLogger_ParserCompileLazy);
 
     Parser<FullParseHandler> parser(cx, &cx->tempLifoAlloc(), options, chars, length,
                                     /* foldConstants = */ true, nullptr, lazy);
     if (!parser.checkOptions())
         return false;
@@ -526,17 +526,17 @@ frontend::CompileLazyFunction(JSContext 
 
 // Compile a JS function body, which might appear as the value of an event
 // handler attribute in an HTML <INPUT> tag, or in a Function() constructor.
 static bool
 CompileFunctionBody(JSContext *cx, MutableHandleFunction fun, const ReadOnlyCompileOptions &options,
                     const AutoNameVector &formals, SourceBufferHolder &srcBuf,
                     HandleObject enclosingScope, GeneratorKind generatorKind)
 {
-    js::TraceLogger *logger = js::TraceLoggerForMainThread(cx->runtime());
+    js::TraceLoggerThread *logger = js::TraceLoggerForMainThread(cx->runtime());
     uint32_t logId = js::TraceLogCreateTextId(logger, options);
     js::AutoTraceLog scriptLogger(logger, logId);
     js::AutoTraceLog typeLogger(logger, TraceLogger_ParserCompileFunction);
 
     // FIXME: make Function pass in two strings and parse them as arguments and
     // ProgramElements respectively.
 
     if (!CheckLength(cx, srcBuf))
--- a/js/src/jit/Bailouts.cpp
+++ b/js/src/jit/Bailouts.cpp
@@ -36,17 +36,17 @@ jit::Bailout(BailoutStack *sp, BaselineB
                "Fake jitTop pointer should be within the first page.");
     cx->mainThread().jitTop = FAKE_JIT_TOP_FOR_BAILOUT;
 
     JitActivationIterator jitActivations(cx->runtime());
     BailoutFrameInfo bailoutData(jitActivations, sp);
     JitFrameIterator iter(jitActivations);
     MOZ_ASSERT(!iter.ionScript()->invalidated());
 
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     TraceLogTimestamp(logger, TraceLogger_Bailout);
 
     JitSpew(JitSpew_IonBailouts, "Took bailout! Snapshot offset: %d", iter.snapshotOffset());
 
     MOZ_ASSERT(IsBaselineEnabled(cx));
 
     *bailoutInfo = nullptr;
     bool poppedLastSPSFrame = false;
@@ -102,17 +102,17 @@ jit::InvalidationBailout(InvalidationBai
 
     // We don't have an exit frame.
     cx->mainThread().jitTop = FAKE_JIT_TOP_FOR_BAILOUT;
 
     JitActivationIterator jitActivations(cx->runtime());
     BailoutFrameInfo bailoutData(jitActivations, sp);
     JitFrameIterator iter(jitActivations);
 
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     TraceLogTimestamp(logger, TraceLogger_Invalidation);
 
     JitSpew(JitSpew_IonBailouts, "Took invalidation bailout! Snapshot offset: %d", iter.snapshotOffset());
 
     // Note: the frame size must be computed before we return from this function.
     *frameSizeOut = iter.frameSize();
 
     MOZ_ASSERT(IsBaselineEnabled(cx));
--- a/js/src/jit/BaselineBailouts.cpp
+++ b/js/src/jit/BaselineBailouts.cpp
@@ -1376,17 +1376,17 @@ jit::BailoutIonToBaseline(JSContext *cx,
                           const ExceptionBailoutInfo *excInfo, bool *poppedLastSPSFrameOut)
 {
     MOZ_ASSERT(bailoutInfo != nullptr);
     MOZ_ASSERT(*bailoutInfo == nullptr);
 
     MOZ_ASSERT(poppedLastSPSFrameOut);
     MOZ_ASSERT(!*poppedLastSPSFrameOut);
 
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     TraceLogStopEvent(logger, TraceLogger_IonMonkey);
     TraceLogStartEvent(logger, TraceLogger_Baseline);
 
     // The caller of the top frame must be one of the following:
     //      IonJS - Ion calling into Ion.
     //      BaselineStub - Baseline calling into Ion.
     //      Entry - Interpreter or other calling into Ion.
     //      Rectifier - Arguments rectifier calling into Ion.
--- a/js/src/jit/BaselineCompiler.cpp
+++ b/js/src/jit/BaselineCompiler.cpp
@@ -76,17 +76,17 @@ MethodStatus
 BaselineCompiler::compile()
 {
     JitSpew(JitSpew_BaselineScripts, "Baseline compiling script %s:%d (%p)",
             script->filename(), script->lineno(), script);
 
     JitSpew(JitSpew_Codegen, "# Emitting baseline code for script %s:%d",
             script->filename(), script->lineno());
 
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     AutoTraceLog logScript(logger, TraceLogCreateTextId(logger, script));
     AutoTraceLog logCompile(logger, TraceLogger_BaselineCompilation);
 
     if (!script->ensureHasTypes(cx) || !script->ensureHasAnalyzedArgsUsage(cx))
         return Method_Error;
 
     // Pin analysis info during compilation.
     types::AutoEnterAnalysis autoEnterAnalysis(cx);
@@ -370,17 +370,17 @@ BaselineCompiler::emitPrologue()
         emitInitializeLocals(frame.nvars(), UndefinedValue());
     if (frame.nlexicals() > 0)
         emitInitializeLocals(frame.nlexicals(), MagicValue(JS_UNINITIALIZED_LEXICAL));
 
     if (needsEarlyStackCheck())
         masm.bind(&earlyStackCheckFailed);
 
 #ifdef JS_TRACE_LOGGING
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     Register loggerReg = RegisterSet::Volatile().takeGeneral();
     masm.Push(loggerReg);
     masm.movePtr(ImmPtr(logger), loggerReg);
     masm.tracelogStart(loggerReg, TraceLogCreateTextId(logger, script));
     masm.tracelogStart(loggerReg, TraceLogger_Baseline);
     masm.Pop(loggerReg);
 #endif
 
@@ -420,17 +420,17 @@ BaselineCompiler::emitEpilogue()
 {
     // Record the offset of the epilogue, so we can do early return from
     // Debugger handlers during on-stack recompile.
     epilogueOffset_ = CodeOffsetLabel(masm.currentOffset());
 
     masm.bind(&return_);
 
 #ifdef JS_TRACE_LOGGING
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     Register loggerReg = RegisterSet::Volatile().takeGeneral();
     masm.Push(loggerReg);
     masm.movePtr(ImmPtr(logger), loggerReg);
     masm.tracelogStop(loggerReg, TraceLogger_Baseline);
     masm.tracelogStop(loggerReg, TraceLogger_Scripts);
     masm.Pop(loggerReg);
 #endif
 
--- a/js/src/jit/BaselineJIT.cpp
+++ b/js/src/jit/BaselineJIT.cpp
@@ -187,17 +187,17 @@ jit::EnterBaselineAtBranch(JSContext *cx
 
         // For eval function frames, set the callee token to the enclosing function.
         if (fp->isFunctionFrame())
             data.calleeToken = CalleeToToken(&fp->callee(), /* constructing = */ false);
         else
             data.calleeToken = CalleeToToken(fp->script());
     }
 
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     TraceLogStopEvent(logger, TraceLogger_Interpreter);
     TraceLogStartEvent(logger, TraceLogger_Baseline);
 
     JitExecStatus status = EnterBaseline(cx, data);
     if (status != JitExec_Ok)
         return status;
 
     fp->setReturnValue(data.result);
--- a/js/src/jit/CodeGenerator.cpp
+++ b/js/src/jit/CodeGenerator.cpp
@@ -7620,17 +7620,17 @@ CodeGenerator::link(JSContext *cx, types
     if (graph.numConstants())
         ionScript->copyConstants(graph.constantPool());
     if (callTargets.length() > 0)
         ionScript->copyCallTargetEntries(callTargets.begin());
     if (patchableBackedges_.length() > 0)
         ionScript->copyPatchableBackedges(cx, code, patchableBackedges_.begin(), masm);
 
 #ifdef JS_TRACE_LOGGING
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     for (uint32_t i = 0; i < patchableTraceLoggers_.length(); i++) {
         patchableTraceLoggers_[i].fixup(&masm);
         Assembler::PatchDataWithValueCheck(CodeLocationLabel(code, patchableTraceLoggers_[i]),
                                            ImmPtr(logger),
                                            ImmPtr(nullptr));
     }
     uint32_t scriptId = TraceLogCreateTextId(logger, script);
     for (uint32_t i = 0; i < patchableTLScripts_.length(); i++) {
--- a/js/src/jit/Ion.cpp
+++ b/js/src/jit/Ion.cpp
@@ -543,17 +543,17 @@ jit::LazyLinkTopActivation(JSContext *cx
 
     types::AutoEnterAnalysis enterTypes(cx);
     RootedScript script(cx, builder->script());
 
     // Remove from pending.
     builder->remove();
 
     if (CodeGenerator *codegen = builder->backgroundCodegen()) {
-        js::TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+        js::TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
         AutoTraceLog logScript(logger, TraceLogCreateTextId(logger, script));
         AutoTraceLog logLink(logger, TraceLogger_IonLinking);
 
         JitContext jctx(cx, &builder->alloc());
 
         // Root the assembler until the builder is finished below. As it
         // was constructed off thread, the assembler has not been rooted
         // previously, though any GC activity would discard the builder.
@@ -1267,17 +1267,17 @@ jit::ToggleBarriers(JS::Zone *zone, bool
 
 namespace js {
 namespace jit {
 
 bool
 OptimizeMIR(MIRGenerator *mir)
 {
     MIRGraph &graph = mir->graph();
-    TraceLogger *logger;
+    TraceLoggerThread *logger;
     if (GetJitContext()->runtime->onMainThread())
         logger = TraceLoggerForMainThread(GetJitContext()->runtime);
     else
         logger = TraceLoggerForCurrentThread();
 
     if (!mir->compilingAsmJS()) {
         if (!MakeMRegExpHoistable(graph))
             return false;
@@ -1599,17 +1599,17 @@ OptimizeMIR(MIRGenerator *mir)
     return true;
 }
 
 LIRGraph *
 GenerateLIR(MIRGenerator *mir)
 {
     MIRGraph &graph = mir->graph();
 
-    TraceLogger *logger;
+    TraceLoggerThread *logger;
     if (GetJitContext()->runtime->onMainThread())
         logger = TraceLoggerForMainThread(GetJitContext()->runtime);
     else
         logger = TraceLoggerForCurrentThread();
 
     LIRGraph *lir = mir->alloc().lifoAlloc()->new_<LIRGraph>(&graph);
     if (!lir || !lir->init())
         return nullptr;
@@ -1693,17 +1693,17 @@ GenerateLIR(MIRGenerator *mir)
     }
 
     return lir;
 }
 
 CodeGenerator *
 GenerateCode(MIRGenerator *mir, LIRGraph *lir)
 {
-    TraceLogger *logger;
+    TraceLoggerThread *logger;
     if (GetJitContext()->runtime->onMainThread())
         logger = TraceLoggerForMainThread(GetJitContext()->runtime);
     else
         logger = TraceLoggerForCurrentThread();
     AutoTraceLog log(logger, TraceLogger_GenerateCode);
 
     CodeGenerator *codegen = js_new<CodeGenerator>(mir, lir);
     if (!codegen)
@@ -1740,17 +1740,17 @@ AttachFinishedCompilations(JSContext *cx
     if (!ion)
         return;
 
     types::AutoEnterAnalysis enterTypes(cx);
     AutoLockHelperThreadState lock;
 
     GlobalHelperThreadState::IonBuilderVector &finished = HelperThreadState().ionFinishedList();
 
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
 
     // Incorporate any off thread compilations for the compartment which have
     // finished, failed or have been cancelled.
     while (true) {
         IonBuilder *builder = nullptr;
 
         // Find a finished builder for the compartment.
         for (size_t i = 0; i < finished.length(); i++) {
@@ -1871,17 +1871,17 @@ TrackPropertiesForSingletonScopes(JSCont
 }
 
 static AbortReason
 IonCompile(JSContext *cx, JSScript *script,
            BaselineFrame *baselineFrame, jsbytecode *osrPc, bool constructing,
            ExecutionMode executionMode, bool recompile,
            OptimizationLevel optimizationLevel)
 {
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     AutoTraceLog logScript(logger, TraceLogCreateTextId(logger, script));
     AutoTraceLog logCompile(logger, TraceLogger_IonCompilation);
 
     MOZ_ASSERT(optimizationLevel > Optimization_DontCompile);
 
     // Make sure the script's canonical function isn't lazy. We can't de-lazify
     // it in a helper thread.
     script->ensureNonLazyCanonicalFunction(cx);
--- a/js/src/jit/JitFrames.cpp
+++ b/js/src/jit/JitFrames.cpp
@@ -709,17 +709,17 @@ struct AutoDeleteDebugModeOSRInfo
     explicit AutoDeleteDebugModeOSRInfo(BaselineFrame *frame) : frame(frame) { MOZ_ASSERT(frame); }
     ~AutoDeleteDebugModeOSRInfo() { frame->deleteDebugModeOSRInfo(); }
 };
 
 void
 HandleException(ResumeFromException *rfe)
 {
     JSContext *cx = GetJSContextFromJitCode();
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
 
     rfe->kind = ResumeFromException::RESUME_ENTRY_FRAME;
 
     JitSpew(JitSpew_IonInvalidate, "handling exception");
 
     // Clear any Ion return override that's been set.
     // This may happen if a callVM function causes an invalidation (setting the
     // override), and then fails, bypassing the bailout handlers that would
--- a/js/src/jit/MacroAssembler.cpp
+++ b/js/src/jit/MacroAssembler.cpp
@@ -1669,17 +1669,17 @@ MacroAssembler::printf(const char *outpu
 
 #ifdef JS_TRACE_LOGGING
 void
 MacroAssembler::tracelogStart(Register logger, uint32_t textId)
 {
     if (!TraceLogTextIdEnabled(textId))
         return;
 
-    void (&TraceLogFunc)(TraceLogger*, uint32_t) = TraceLogStartEvent;
+    void (&TraceLogFunc)(TraceLoggerThread *, uint32_t) = TraceLogStartEvent;
 
     PushRegsInMask(RegisterSet::Volatile());
 
     RegisterSet regs = RegisterSet::Volatile();
     regs.takeUnchecked(logger);
 
     Register temp = regs.takeGeneral();
 
@@ -1690,17 +1690,17 @@ MacroAssembler::tracelogStart(Register l
     callWithABINoProfiling(JS_FUNC_TO_DATA_PTR(void *, TraceLogFunc));
 
     PopRegsInMask(RegisterSet::Volatile());
 }
 
 void
 MacroAssembler::tracelogStart(Register logger, Register textId)
 {
-    void (&TraceLogFunc)(TraceLogger*, uint32_t) = TraceLogStartEvent;
+    void (&TraceLogFunc)(TraceLoggerThread *, uint32_t) = TraceLogStartEvent;
 
     PushRegsInMask(RegisterSet::Volatile());
 
     RegisterSet regs = RegisterSet::Volatile();
     regs.takeUnchecked(logger);
     regs.takeUnchecked(textId);
 
     Register temp = regs.takeGeneral();
--- a/js/src/jit/VMFunctions.cpp
+++ b/js/src/jit/VMFunctions.cpp
@@ -766,17 +766,17 @@ DebugPrologue(JSContext *cx, BaselineFra
 }
 
 bool
 DebugEpilogueOnBaselineReturn(JSContext *cx, BaselineFrame *frame, jsbytecode *pc)
 {
     if (!DebugEpilogue(cx, frame, pc, true)) {
         // DebugEpilogue popped the frame by updating jitTop, so run the stop event
         // here before we enter the exception handler.
-        TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+        TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
         TraceLogStopEvent(logger, TraceLogger_Baseline);
         TraceLogStopEvent(logger, TraceLogger_Scripts);
         return false;
     }
 
     return true;
 }
 
--- a/js/src/jit/arm/CodeGenerator-arm.cpp
+++ b/js/src/jit/arm/CodeGenerator-arm.cpp
@@ -54,17 +54,17 @@ CodeGeneratorARM::generatePrologue()
 bool
 CodeGeneratorARM::generateEpilogue()
 {
     MOZ_ASSERT(!gen->compilingAsmJS());
     masm.bind(&returnLabel_);
 
 #ifdef JS_TRACE_LOGGING
     if (gen->info().executionMode() == SequentialExecution) {
-        if (!emitTracelogStopEvent(TraceLogger::IonMonkey))
+        if (!emitTracelogStopEvent(TraceLogger_IonMonkey))
             return false;
         if (!emitTracelogScriptStop())
             return false;
     }
 #endif
 
     masm.freeStack(frameSize());
     MOZ_ASSERT(masm.framePushed() == 0);
--- a/js/src/jit/shared/CodeGenerator-shared.cpp
+++ b/js/src/jit/shared/CodeGenerator-shared.cpp
@@ -1411,17 +1411,17 @@ CodeGeneratorShared::emitTracelogScript(
     Register script = regs.takeGeneral();
 
     masm.Push(logger);
 
     CodeOffsetLabel patchLogger = masm.movWithPatch(ImmPtr(nullptr), logger);
     if (!patchableTraceLoggers_.append(patchLogger))
         return false;
 
-    Address enabledAddress(logger, TraceLogger::offsetOfEnabled());
+    Address enabledAddress(logger, TraceLoggerThread::offsetOfEnabled());
     masm.branch32(Assembler::Equal, enabledAddress, Imm32(0), &done);
 
     masm.Push(script);
 
     CodeOffsetLabel patchScript = masm.movWithPatch(ImmWord(0), script);
     if (!patchableTLScripts_.append(patchScript))
         return false;
 
@@ -1449,17 +1449,17 @@ CodeGeneratorShared::emitTracelogTree(bo
     Register logger = regs.takeGeneral();
 
     masm.Push(logger);
 
     CodeOffsetLabel patchLocation = masm.movWithPatch(ImmPtr(nullptr), logger);
     if (!patchableTraceLoggers_.append(patchLocation))
         return false;
 
-    Address enabledAddress(logger, TraceLogger::offsetOfEnabled());
+    Address enabledAddress(logger, TraceLoggerThread::offsetOfEnabled());
     masm.branch32(Assembler::Equal, enabledAddress, Imm32(0), &done);
 
     if (isStart)
         masm.tracelogStart(logger, textId);
     else
         masm.tracelogStop(logger, textId);
 
     masm.bind(&done);
--- a/js/src/jsgc.cpp
+++ b/js/src/jsgc.cpp
@@ -3555,17 +3555,17 @@ GCHelperState::work()
 {
     MOZ_ASSERT(CanUseExtraThreads());
 
     AutoLockGC lock(rt);
 
     MOZ_ASSERT(!thread);
     thread = PR_GetCurrentThread();
 
-    TraceLogger *logger = TraceLoggerForCurrentThread();
+    TraceLoggerThread *logger = TraceLoggerForCurrentThread();
 
     switch (state()) {
 
       case IDLE:
         MOZ_CRASH("GC helper triggered on idle state");
         break;
 
       case SWEEPING: {
@@ -3588,17 +3588,17 @@ BackgroundAllocTask::BackgroundAllocTask
     chunkPool_(pool),
     enabled_(CanUseExtraThreads() && GetCPUCount() >= 2)
 {
 }
 
 /* virtual */ void
 BackgroundAllocTask::run()
 {
-    TraceLogger *logger = TraceLoggerForCurrentThread();
+    TraceLoggerThread *logger = TraceLoggerForCurrentThread();
     AutoTraceLog logAllocation(logger, TraceLogger_GCAllocation);
 
     AutoLockGC lock(runtime);
     while (!cancel_ && runtime->gc.wantBackgroundAllocation(lock)) {
         Chunk *chunk;
         {
             AutoUnlockGC unlock(lock);
             chunk = Chunk::allocate(runtime);
@@ -6248,17 +6248,17 @@ GCRuntime::collect(bool incremental, Sli
     MOZ_ALWAYS_TRUE(!rt->isHeapBusy());
 
     /* The engine never locks across anything that could GC. */
     MOZ_ASSERT(!rt->currentThreadHasExclusiveAccess());
 
     if (rt->mainThread.suppressGC)
         return;
 
-    TraceLogger *logger = TraceLoggerForMainThread(rt);
+    TraceLoggerThread *logger = TraceLoggerForMainThread(rt);
     AutoTraceLog logGC(logger, TraceLogger_GC);
 
 #ifdef JS_GC_ZEAL
     if (deterministicOnly && !IsDeterministicGCReason(reason))
         return;
 #endif
 
     AutoStopVerifyingBarriers av(rt, reason == JS::gcreason::SHUTDOWN_CC ||
@@ -6459,29 +6459,29 @@ GCRuntime::onOutOfMallocMemory(const Aut
     // malloc request.
     decommitAllWithoutUnlocking(lock);
 }
 
 void
 GCRuntime::minorGC(JS::gcreason::Reason reason)
 {
     minorGCRequested = false;
-    TraceLogger *logger = TraceLoggerForMainThread(rt);
+    TraceLoggerThread *logger = TraceLoggerForMainThread(rt);
     AutoTraceLog logMinorGC(logger, TraceLogger_MinorGC);
     nursery.collect(rt, reason, nullptr);
     MOZ_ASSERT_IF(!rt->mainThread.suppressGC, nursery.isEmpty());
 }
 
 void
 GCRuntime::minorGC(JSContext *cx, JS::gcreason::Reason reason)
 {
     // Alternate to the runtime-taking form above which allows marking type
     // objects as needing pretenuring.
     minorGCRequested = false;
-    TraceLogger *logger = TraceLoggerForMainThread(rt);
+    TraceLoggerThread *logger = TraceLoggerForMainThread(rt);
     AutoTraceLog logMinorGC(logger, TraceLogger_MinorGC);
     Nursery::TypeObjectList pretenureTypes;
     nursery.collect(rt, reason, &pretenureTypes);
     for (size_t i = 0; i < pretenureTypes.length(); i++) {
         if (pretenureTypes[i]->canPreTenure())
             pretenureTypes[i]->setShouldPreTenure(cx);
     }
     MOZ_ASSERT_IF(!rt->mainThread.suppressGC, nursery.isEmpty());
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -308,16 +308,17 @@ if CONFIG['JS_POSIX_NSPR']:
 if CONFIG['MOZ_INSTRUMENTS']:
     SOURCES += [
         'devtools/Instruments.cpp',
     ]
 
 if CONFIG['ENABLE_TRACE_LOGGING']:
     SOURCES += [
         'vm/TraceLogging.cpp',
+        'vm/TraceLoggingGraph.cpp',
     ]
 
 if not CONFIG['ENABLE_ION']:
     UNIFIED_SOURCES += [
         'jit/none/Trampoline-none.cpp'
     ]
 elif CONFIG['JS_CODEGEN_X86'] or CONFIG['JS_CODEGEN_X64']:
     UNIFIED_SOURCES += [
--- a/js/src/vm/HelperThreads.cpp
+++ b/js/src/vm/HelperThreads.cpp
@@ -1053,17 +1053,17 @@ HelperThread::handleIonWorkload()
     if (HelperThread *other = HelperThreadState().lowestPriorityUnpausedIonCompileAtThreshold()) {
         MOZ_ASSERT(other->ionBuilder && !other->pause);
         other->pause = true;
     }
 
     ionBuilder = builder;
     ionBuilder->setPauseFlag(&pause);
 
-    TraceLogger *logger = TraceLoggerForCurrentThread();
+    TraceLoggerThread *logger = TraceLoggerForCurrentThread();
     AutoTraceLog logScript(logger, TraceLogCreateTextId(logger, ionBuilder->script()));
     AutoTraceLog logCompile(logger, TraceLogger_IonCompilation);
 
     JSRuntime *rt = ionBuilder->script()->compartment()->runtimeFromAnyThread();
 
     {
         AutoUnlockHelperThreadState unlock;
         PerThreadData::AutoEnterRuntime enter(threadData.ptr(),
@@ -1123,17 +1123,17 @@ CurrentHelperThread()
     }
     MOZ_ASSERT(thread);
     return thread;
 }
 
 void
 js::PauseCurrentHelperThread()
 {
-    TraceLogger *logger = TraceLoggerForCurrentThread();
+    TraceLoggerThread *logger = TraceLoggerForCurrentThread();
     AutoTraceLog logPaused(logger, TraceLogger_IonCompilationPaused);
 
     HelperThread *thread = CurrentHelperThread();
 
     AutoLockHelperThreadState lock;
     while (thread->pause)
         HelperThreadState().wait(GlobalHelperThreadState::PAUSE);
 }
--- a/js/src/vm/Interpreter.cpp
+++ b/js/src/vm/Interpreter.cpp
@@ -1477,17 +1477,17 @@ Interpret(JSContext *cx, RunState &state
         return false;
 
     InterpreterActivation activation(state, cx, entryFrame);
 
     /* The script is used frequently, so keep a local copy. */
     RootedScript script(cx);
     SET_SCRIPT(REGS.fp()->script());
 
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     uint32_t scriptLogId = TraceLogCreateTextId(logger, script);
     TraceLogStartEvent(logger, scriptLogId);
     TraceLogStartEvent(logger, TraceLogger_Interpreter);
 
     /*
      * Pool of rooters for use in this interpreter frame. References to these
      * are used for local variables within interpreter cases. This avoids
      * creating new rooters each time an interpreter case is entered, and also
--- a/js/src/vm/RegExpObject.cpp
+++ b/js/src/vm/RegExpObject.cpp
@@ -451,17 +451,17 @@ RegExpShared::trace(JSTracer *trc)
             MarkJitCode(trc, &compilation.jitCode, "RegExpShared code");
     }
 }
 
 bool
 RegExpShared::compile(JSContext *cx, HandleLinearString input,
                       CompilationMode mode, ForceByteCodeEnum force)
 {
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
     AutoTraceLog logCompile(logger, TraceLogger_IrregexpCompile);
 
     if (!sticky()) {
         RootedAtom pattern(cx, source);
         return compile(cx, pattern, input, mode, force);
     }
 
     /*
@@ -538,17 +538,17 @@ RegExpShared::compileIfNecessary(JSConte
         return true;
     return compile(cx, input, mode, force);
 }
 
 RegExpRunStatus
 RegExpShared::execute(JSContext *cx, HandleLinearString input, size_t start,
                       MatchPairs *matches)
 {
-    TraceLogger *logger = TraceLoggerForMainThread(cx->runtime());
+    TraceLoggerThread *logger = TraceLoggerForMainThread(cx->runtime());
 
     CompilationMode mode = matches ? Normal : MatchOnly;
 
     /* Compile the code at point-of-use. */
     if (!compileIfNecessary(cx, input, mode, DontForceByteCode))
         return RegExpRunStatus_Error;
 
     /*
--- a/js/src/vm/Runtime.h
+++ b/js/src/vm/Runtime.h
@@ -49,17 +49,17 @@
 #endif
 
 namespace js {
 
 class PerThreadData;
 struct ThreadSafeContext;
 class AutoKeepAtoms;
 #ifdef JS_TRACE_LOGGING
-class TraceLogger;
+class TraceLoggerThread;
 #endif
 
 /* Thread Local Storage slot for storing the runtime for a thread. */
 extern mozilla::ThreadLocal<PerThreadData*> TlsPerThreadData;
 
 } // namespace js
 
 struct DtoaState;
@@ -535,17 +535,17 @@ class PerThreadData : public PerThreadDa
     // For read-only JIT use:
     void *addressOfJitStackLimit() { return &jitStackLimit_; }
     static size_t offsetOfJitStackLimit() { return offsetof(PerThreadData, jitStackLimit_); }
 
     // Information about the heap allocated backtrack stack used by RegExp JIT code.
     irregexp::RegExpStack regexpStack;
 
 #ifdef JS_TRACE_LOGGING
-    TraceLogger         *traceLogger;
+    TraceLoggerThread   *traceLogger;
 #endif
 
   private:
     friend class js::Activation;
     friend class js::ActivationIterator;
     friend class js::jit::JitActivation;
     friend class js::AsmJSActivation;
 #ifdef DEBUG
--- a/js/src/vm/TraceLogging.cpp
+++ b/js/src/vm/TraceLogging.cpp
@@ -2,39 +2,36 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "vm/TraceLogging.h"
 
 #include "mozilla/DebugOnly.h"
-#include "mozilla/Endian.h"
 
 #include <string.h>
 
 #include "jsapi.h"
+#include "jsprf.h"
 #include "jsscript.h"
 
 #include "jit/CompileWrappers.h"
 #include "vm/Runtime.h"
+#include "vm/TraceLoggingGraph.h"
 
 #include "jit/JitFrames-inl.h"
 
 using namespace js;
 using namespace js::jit;
+
+using mozilla::DebugOnly;
 using mozilla::NativeEndian;
 
-#ifndef TRACE_LOG_DIR
-# if defined(_WIN32)
-#  define TRACE_LOG_DIR ""
-# else
-#  define TRACE_LOG_DIR "/tmp/"
-# endif
-#endif
+TraceLoggerThreadState traceLoggers;
 
 #if defined(_WIN32)
 #include <intrin.h>
 static __inline uint64_t
 rdtsc(void)
 {
     return __rdtsc();
 }
@@ -72,126 +69,106 @@ rdtsc(void)
     result = upper;
     result = result<<32;
     result = result|lower;
 
     return result;
 }
 #endif
 
-TraceLogging traceLoggers;
-
-static const char *
-TLTextIdString(TraceLoggerTextId id)
+class AutoTraceLoggerThreadStateLock
 {
-    switch (id) {
-      case TraceLogger_Error:
-        return "TraceLogger failed to process text";
-#define NAME(textId) case TraceLogger_ ## textId: return #textId;
-        TRACELOGGER_TEXT_ID_LIST(NAME)
-#undef NAME
-      default:
-        MOZ_CRASH();
+  TraceLoggerThreadState *logging;
+
+  public:
+    AutoTraceLoggerThreadStateLock(TraceLoggerThreadState *logging MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
+      : logging(logging)
+    {
+        MOZ_GUARD_OBJECT_NOTIFIER_INIT;
+        PR_Lock(logging->lock);
     }
-}
+    ~AutoTraceLoggerThreadStateLock() {
+        PR_Unlock(logging->lock);
+    }
+  private:
+    MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
+};
 
-TraceLogger::TraceLogger()
- : enabled(0),
-   failed(false),
-   nextTextId(0),
-   treeOffset(0),
-   top(nullptr)
+TraceLoggerThread::TraceLoggerThread()
+  : enabled(0),
+    failed(false),
+    graph(),
+    top(nullptr)
 { }
 
 bool
-TraceLogger::init(uint32_t loggerId)
+TraceLoggerThread::init()
 {
     if (!pointerMap.init())
         return false;
-    if (!tree.init())
-        return false;
-    if (!stack.init())
-        return false;
     if (!events.init())
         return false;
 
-    MOZ_ASSERT(loggerId <= 999);
-
-    char dictFilename[sizeof TRACE_LOG_DIR "tl-dict.100.json"];
-    sprintf(dictFilename, TRACE_LOG_DIR "tl-dict.%d.json", loggerId);
-    dictFile = fopen(dictFilename, "w");
-    if (!dictFile)
+    uint64_t start = rdtsc() - traceLoggers.startupTime;
+    if (!graph.init(start))
         return false;
 
-    char treeFilename[sizeof TRACE_LOG_DIR "tl-tree.100.tl"];
-    sprintf(treeFilename, TRACE_LOG_DIR "tl-tree.%d.tl", loggerId);
-    treeFile = fopen(treeFilename, "wb");
-    if (!treeFile) {
-        fclose(dictFile);
-        dictFile = nullptr;
+    // Minimum amount of capacity needed for operation to allow flushing.
+    // Flushing requires space for the actual event and two spaces to log the
+    // start and stop of flushing.
+    if (!events.ensureSpaceBeforeAdd(3))
         return false;
+
+    // Report the textIds to the graph.
+    for (uint32_t i = 0; i < TraceLogger_LastTreeItem; i++) {
+        TraceLoggerTextId id = TraceLoggerTextId(i);
+        graph.addTextId(i, TLTextIdString(id));
     }
 
-    char eventFilename[sizeof TRACE_LOG_DIR "tl-event.100.tl"];
-    sprintf(eventFilename, TRACE_LOG_DIR "tl-event.%d.tl", loggerId);
-    eventFile = fopen(eventFilename, "wb");
-    if (!eventFile) {
-        fclose(dictFile);
-        fclose(treeFile);
-        dictFile = nullptr;
-        treeFile = nullptr;
-        return false;
-    }
-
-    uint64_t start = rdtsc() - traceLoggers.startupTime;
-
-    TreeEntry &treeEntry = tree.pushUninitialized();
-    treeEntry.setStart(start);
-    treeEntry.setStop(0);
-    treeEntry.setTextId(0);
-    treeEntry.setHasChildren(false);
-    treeEntry.setNextId(0);
-
-    StackEntry &stackEntry = stack.pushUninitialized();
-    stackEntry.setTreeId(0);
-    stackEntry.setLastChildId(0);
-    stackEntry.setActive(true);
-
-    int written = fprintf(dictFile, "[");
-    if (written < 0)
-        fprintf(stderr, "TraceLogging: Error while writing.\n");
-
-    // Eagerly create the default textIds, to match their TraceLoggerTextId.
-    for (uint32_t i = 0; i < TraceLogger_LAST; i++) {
+    graph.addTextId(TraceLogger_LastTreeItem, "TraceLogger internal");
+    for (uint32_t i = TraceLogger_LastTreeItem + 1; i < TraceLogger_Last; i++) {
         TraceLoggerTextId id = TraceLoggerTextId(i);
-        mozilla::DebugOnly<uint32_t> textId = createTextId(TLTextIdString(id));
-        MOZ_ASSERT(textId == i);
+        graph.addTextId(i, TLTextIdString(id));
     }
 
     enabled = 1;
+    graph.enable();
+
     return true;
 }
 
+TraceLoggerThread::~TraceLoggerThread()
+{
+    if (!failed)
+        graph.log(events);
+}
+
 bool
-TraceLogger::enable()
+TraceLoggerThread::enable()
 {
     if (enabled > 0) {
         enabled++;
         return true;
     }
 
     if (failed)
         return false;
 
+    // TODO: Remove this. This is so the refactor works with mimimal changes,
+    // It is the intention to remove this by logging TraceLogger_Enable/TraceLogger_Disable.
+    events.clear();
+
     enabled = 1;
+    graph.enable();
+
     return true;
 }
 
 bool
-TraceLogger::enable(JSContext *cx)
+TraceLoggerThread::enable(JSContext *cx)
 {
     if (!enable())
         return false;
 
     if (enabled == 1) {
         // Get the top Activation to log the top script/pc (No inlined frames).
         ActivationIterator iter(cx->runtime());
         Activation *act = iter.activation();
@@ -233,507 +210,197 @@ TraceLogger::enable(JSContext *cx)
         startEvent(createTextId(script));
         startEvent(engine);
     }
 
     return true;
 }
 
 bool
-TraceLogger::disable()
+TraceLoggerThread::disable()
 {
     if (failed)
         return false;
 
     if (enabled == 0)
         return true;
 
     if (enabled > 1) {
         enabled--;
         return true;
     }
 
-    MOZ_ASSERT(enabled == 1);
-    while (stack.size() > 1)
-        stopEvent();
+    graph.log(events);
+    events.clear();
+
+    uint64_t time = rdtsc() - traceLoggers.startupTime;
+    graph.disable(time);
 
     enabled = 0;
 
     return true;
 }
 
-bool
-TraceLogger::flush()
-{
-    MOZ_ASSERT(!failed);
-
-    if (treeFile) {
-        // Format data in big endian.
-        for (size_t i = 0; i < tree.size(); i++)
-            entryToBigEndian(&tree[i]);
-
-        int success = fseek(treeFile, 0, SEEK_END);
-        if (success != 0)
-            return false;
-
-        size_t bytesWritten = fwrite(tree.data(), sizeof(TreeEntry), tree.size(), treeFile);
-        if (bytesWritten < tree.size())
-            return false;
-
-        treeOffset += tree.lastEntryId();
-        tree.clear();
-    }
-
-    if (eventFile) {
-        // Format data in big endian
-        for (size_t i = 0; i < events.size(); i++) {
-            events[i].time = NativeEndian::swapToBigEndian(events[i].time);
-            events[i].textId = NativeEndian::swapToBigEndian(events[i].textId);
-        }
-
-        size_t bytesWritten = fwrite(events.data(), sizeof(EventEntry), events.size(), eventFile);
-        if (bytesWritten < events.size())
-            return false;
-        events.clear();
-    }
-
-    return true;
-}
-
-TraceLogger::~TraceLogger()
-{
-    // Write dictionary to disk
-    if (dictFile) {
-        int written = fprintf(dictFile, "]");
-        if (written < 0)
-            fprintf(stderr, "TraceLogging: Error while writing.\n");
-        fclose(dictFile);
-
-        dictFile = nullptr;
-    }
-
-    if (!failed && treeFile) {
-        // Make sure every start entry has a corresponding stop value.
-        // We temporary enable logging for this. Stop doesn't need any extra data,
-        // so is safe to do, even when we encountered OOM.
-        enabled = 1;
-        while (stack.size() > 1)
-            stopEvent();
-        enabled = 0;
-    }
-
-    if (!failed && !flush()) {
-        fprintf(stderr, "TraceLogging: Couldn't write the data to disk.\n");
-        enabled = 0;
-        failed = true;
-    }
-
-    if (treeFile) {
-        fclose(treeFile);
-        treeFile = nullptr;
-    }
-
-    if (eventFile) {
-        fclose(eventFile);
-        eventFile = nullptr;
-    }
+const char *
+TraceLoggerThread::eventText(uint32_t id) {
+    if (id < TraceLogger_Last)
+        return TLTextIdString(static_cast<TraceLoggerTextId>(id));
+    return extraTextId[id - TraceLogger_Last];
 }
 
 uint32_t
-TraceLogger::createTextId(const char *text)
+TraceLoggerThread::createTextId(const char *text)
 {
     assertNoQuotes(text);
 
     PointerHashMap::AddPtr p = pointerMap.lookupForAdd((const void *)text);
     if (p)
         return p->value();
 
-    uint32_t textId = nextTextId++;
+    size_t len = strlen(text);
+    char *str = js_pod_malloc<char>(len + 1);
+    if (!str)
+        return TraceLogger_Error;
+
+    DebugOnly<size_t> ret = JS_snprintf(str, len + 1, "%s", text);
+    MOZ_ASSERT(ret == len);
+    MOZ_ASSERT(strlen(str) == len);
+
+    if (!extraTextId.append(str))
+        return TraceLogger_Error;
+
+    uint32_t textId = extraTextId.length() - 1 + TraceLogger_Last;
     if (!pointerMap.add(p, text, textId))
         return TraceLogger_Error;
 
-    int written;
-    if (textId > 0)
-        written = fprintf(dictFile, ",\n\"%s\"", text);
-    else
-        written = fprintf(dictFile, "\"%s\"", text);
-
-    if (written < 0)
-        return TraceLogger_Error;
-
+    graph.addTextId(textId, text);
     return textId;
 }
 
 uint32_t
-TraceLogger::createTextId(JSScript *script)
+TraceLoggerThread::createTextId(const char *filename, size_t lineno, size_t colno, const void *ptr)
 {
-    if (!script->filename())
-        return createTextId("");
+    if (!filename)
+        filename = "<unknown>";
 
-    assertNoQuotes(script->filename());
+    assertNoQuotes(filename);
 
     // Only log scripts when enabled otherwise return the global Scripts textId,
     // which will get filtered out.
     if (!traceLoggers.isTextIdEnabled(TraceLogger_Scripts))
         return TraceLogger_Scripts;
 
-    PointerHashMap::AddPtr p = pointerMap.lookupForAdd(script);
+    PointerHashMap::AddPtr p = pointerMap.lookupForAdd(ptr);
     if (p)
         return p->value();
 
-    uint32_t textId = nextTextId++;
-    if (!pointerMap.add(p, script, textId))
+    // Compute the length of the string to create.
+    size_t lenFilename = strlen(filename);
+    size_t lenLineno = 1;
+    for (size_t i = lineno; i /= 10; lenLineno++);
+    size_t lenColno = 1;
+    for (size_t i = colno; i /= 10; lenColno++);
+
+    size_t len = 7 + lenFilename + 1 + lenLineno + 1 + lenColno;
+    char *str = js_pod_malloc<char>(len + 1);
+    if (!str)
         return TraceLogger_Error;
 
-    int written;
-    if (textId > 0) {
-        written = fprintf(dictFile, ",\n\"script %s:%u:%u\"", script->filename(),
-                          (unsigned)script->lineno(), (unsigned)script->column());
-    } else {
-        written = fprintf(dictFile, "\"script %s:%u:%u\"", script->filename(),
-                          (unsigned)script->lineno(), (unsigned)script->column());
-    }
+    DebugOnly<size_t> ret = JS_snprintf(str, len + 1, "script %s:%u:%u", filename, lineno, colno);
+    MOZ_ASSERT(ret == len);
+
+    if (!extraTextId.append(str))
+        return TraceLogger_Error;
 
-    if (written < 0)
+    uint32_t textId = extraTextId.length() - 1 + TraceLogger_Last;
+    if (!pointerMap.add(p, ptr, textId))
         return TraceLogger_Error;
 
+    graph.addTextId(textId, str);
+
     return textId;
 }
 
 uint32_t
-TraceLogger::createTextId(const JS::ReadOnlyCompileOptions &compileOptions)
+TraceLoggerThread::createTextId(JSScript *script)
 {
-    if (!compileOptions.filename())
-        return createTextId("");
-
-    assertNoQuotes(compileOptions.filename());
-
-    // Only log scripts when enabled. Else return the global Scripts textId,
-    // which will get filtered out.
-    if (!traceLoggers.isTextIdEnabled(TraceLogger_Scripts))
-        return TraceLogger_Scripts;
-
-    PointerHashMap::AddPtr p = pointerMap.lookupForAdd(&compileOptions);
-    if (p)
-        return p->value();
+    return createTextId(script->filename(), script->lineno(), script->column(), script);
+}
 
-    uint32_t textId = nextTextId++;
-    if (!pointerMap.add(p, &compileOptions, textId))
-        return TraceLogger_Error;
-
-    int written;
-    if (textId > 0) {
-        written = fprintf(dictFile, ",\n\"script %s:%d:%d\"", compileOptions.filename(),
-                          compileOptions.lineno, compileOptions.column);
-    } else {
-        written = fprintf(dictFile, "\"script %s:%d:%d\"", compileOptions.filename(),
-                          compileOptions.lineno, compileOptions.column);
-    }
-
-    if (written < 0)
-        return TraceLogger_Error;
-
-    return textId;
+uint32_t
+TraceLoggerThread::createTextId(const JS::ReadOnlyCompileOptions &script)
+{
+    return createTextId(script.filename(), script.lineno, script.column, &script);
 }
 
 void
-TraceLogger::logTimestamp(uint32_t id)
+TraceLoggerThread::startEvent(uint32_t id)
+{
+    MOZ_ASSERT(TLTextIdIsTreeEvent(id));
+    if (!traceLoggers.isTextIdEnabled(id))
+       return;
+
+    logTimestamp(id);
+}
+
+void
+TraceLoggerThread::stopEvent(uint32_t id)
+{
+    MOZ_ASSERT(TLTextIdIsTreeEvent(id));
+    if (!traceLoggers.isTextIdEnabled(id))
+        return;
+
+    logTimestamp(TraceLogger_Stop);
+}
+
+void
+TraceLoggerThread::logTimestamp(uint32_t id)
 {
     if (enabled == 0)
         return;
 
     if (!events.ensureSpaceBeforeAdd()) {
-        fprintf(stderr, "TraceLogging: Disabled a tracelogger due to OOM.\n");
-        enabled = 0;
-        return;
+        uint64_t start = rdtsc() - traceLoggers.startupTime;
+
+        graph.log(events);
+        events.clear();
+
+        // Log the time it took to flush the events as being from the
+        // Tracelogger.
+        MOZ_ASSERT(events.capacity() > 2);
+        EventEntry &entryStart = events.pushUninitialized();
+        entryStart.time = start;
+        entryStart.textId = TraceLogger_Internal;
+
+        EventEntry &entryStop = events.pushUninitialized();
+        entryStop.time = rdtsc() - traceLoggers.startupTime;
+        entryStop.textId = TraceLogger_Stop;
     }
 
     uint64_t time = rdtsc() - traceLoggers.startupTime;
 
     EventEntry &entry = events.pushUninitialized();
     entry.time = time;
     entry.textId = id;
 }
 
-void
-TraceLogger::entryToBigEndian(TreeEntry *entry)
-{
-    entry->start_ = NativeEndian::swapToBigEndian(entry->start_);
-    entry->stop_ = NativeEndian::swapToBigEndian(entry->stop_);
-    uint32_t data = (entry->u.s.textId_ << 1) + entry->u.s.hasChildren_;
-    entry->u.value_ = NativeEndian::swapToBigEndian(data);
-    entry->nextId_ = NativeEndian::swapToBigEndian(entry->nextId_);
-}
-
-void
-TraceLogger::entryToSystemEndian(TreeEntry *entry)
-{
-    entry->start_ = NativeEndian::swapFromBigEndian(entry->start_);
-    entry->stop_ = NativeEndian::swapFromBigEndian(entry->stop_);
-
-    uint32_t data = NativeEndian::swapFromBigEndian(entry->u.value_);
-    entry->u.s.textId_ = data >> 1;
-    entry->u.s.hasChildren_ = data & 0x1;
-
-    entry->nextId_ = NativeEndian::swapFromBigEndian(entry->nextId_);
-}
-
-bool
-TraceLogger::getTreeEntry(uint32_t treeId, TreeEntry *entry)
-{
-    // Entry is still in memory
-    if (treeId >= treeOffset) {
-        *entry = tree[treeId];
-        return true;
-    }
-
-    int success = fseek(treeFile, treeId * sizeof(TreeEntry), SEEK_SET);
-    if (success != 0)
-        return false;
-
-    size_t itemsRead = fread((void *)entry, sizeof(TreeEntry), 1, treeFile);
-    if (itemsRead < 1)
-        return false;
-
-    entryToSystemEndian(entry);
-    return true;
-}
-
-bool
-TraceLogger::saveTreeEntry(uint32_t treeId, TreeEntry *entry)
-{
-    int success = fseek(treeFile, treeId * sizeof(TreeEntry), SEEK_SET);
-    if (success != 0)
-        return false;
-
-    entryToBigEndian(entry);
-
-    size_t itemsWritten = fwrite(entry, sizeof(TreeEntry), 1, treeFile);
-    if (itemsWritten < 1)
-        return false;
-
-    return true;
-}
-
-bool
-TraceLogger::updateHasChildren(uint32_t treeId, bool hasChildren)
-{
-    if (treeId < treeOffset) {
-        TreeEntry entry;
-        if (!getTreeEntry(treeId, &entry))
-            return false;
-        entry.setHasChildren(hasChildren);
-        if (!saveTreeEntry(treeId, &entry))
-            return false;
-        return true;
-    }
-
-    tree[treeId - treeOffset].setHasChildren(hasChildren);
-    return true;
-}
-
-bool
-TraceLogger::updateNextId(uint32_t treeId, uint32_t nextId)
-{
-    if (treeId < treeOffset) {
-        TreeEntry entry;
-        if (!getTreeEntry(treeId, &entry))
-            return false;
-        entry.setNextId(nextId);
-        if (!saveTreeEntry(treeId, &entry))
-            return false;
-        return true;
-    }
-
-    tree[treeId - treeOffset].setNextId(nextId);
-    return true;
-}
-
-bool
-TraceLogger::updateStop(uint32_t treeId, uint64_t timestamp)
-{
-    if (treeId < treeOffset) {
-        TreeEntry entry;
-        if (!getTreeEntry(treeId, &entry))
-            return false;
-        entry.setStop(timestamp);
-        if (!saveTreeEntry(treeId, &entry))
-            return false;
-        return true;
-    }
-
-    tree[treeId - treeOffset].setStop(timestamp);
-    return true;
-}
-
-void
-TraceLogger::startEvent(uint32_t id)
-{
-    if (failed || enabled == 0)
-        return;
-
-    if (!tree.hasSpaceForAdd()){
-        uint64_t start = rdtsc() - traceLoggers.startupTime;
-        if (!tree.ensureSpaceBeforeAdd()) {
-            if (!flush()) {
-                fprintf(stderr, "TraceLogging: Couldn't write the data to disk.\n");
-                enabled = 0;
-                failed = true;
-                return;
-            }
-        }
-
-        // Log the time it took to flush the events as being from the
-        // Tracelogger.
-        if (!startEvent(TraceLogger_Internal, start)) {
-            fprintf(stderr, "TraceLogging: Failed to start an event.\n");
-            enabled = 0;
-            failed = true;
-            return;
-        }
-        stopEvent();
-    }
-
-    uint64_t start = rdtsc() - traceLoggers.startupTime;
-    if (!startEvent(id, start)) {
-        fprintf(stderr, "TraceLogging: Failed to start an event.\n");
-        enabled = 0;
-        failed = true;
-        return;
-    }
-}
-
-TraceLogger::StackEntry &
-TraceLogger::getActiveAncestor()
-{
-    uint32_t parentId = stack.lastEntryId();
-    while (!stack[parentId].active())
-        parentId--;
-    return stack[parentId];
-}
-
-bool
-TraceLogger::startEvent(uint32_t id, uint64_t timestamp)
-{
-    if (!stack.ensureSpaceBeforeAdd())
-        return false;
-
-    // When a textId is disabled, a stack entry still needs to be pushed,
-    // together with an annotation that nothing needs to get done when receiving
-    // the stop event.
-    if (!traceLoggers.isTextIdEnabled(id)) {
-        StackEntry &stackEntry = stack.pushUninitialized();
-        stackEntry.setActive(false);
-        return true;
-    }
-
-    // Patch up the tree to be correct. There are two scenarios:
-    // 1) Parent has no children yet. So update parent to include children.
-    // 2) Parent has already children. Update last child to link to the new
-    //    child.
-    StackEntry &parent = getActiveAncestor();
-#ifdef DEBUG
-    TreeEntry entry;
-    if (!getTreeEntry(parent.treeId(), &entry))
-        return false;
-#endif
-
-    if (parent.lastChildId() == 0) {
-        MOZ_ASSERT(!entry.hasChildren());
-        MOZ_ASSERT(parent.treeId() == tree.lastEntryId() + treeOffset);
-
-        if (!updateHasChildren(parent.treeId()))
-            return false;
-    } else {
-        MOZ_ASSERT(entry.hasChildren());
-
-        if (!updateNextId(parent.lastChildId(), tree.size() + treeOffset))
-            return false;
-    }
-
-    // Add a new tree entry.
-    TreeEntry &treeEntry = tree.pushUninitialized();
-    treeEntry.setStart(timestamp);
-    treeEntry.setStop(0);
-    treeEntry.setTextId(id);
-    treeEntry.setHasChildren(false);
-    treeEntry.setNextId(0);
-
-    // Add a new stack entry.
-    StackEntry &stackEntry = stack.pushUninitialized();
-    stackEntry.setTreeId(tree.lastEntryId() + treeOffset);
-    stackEntry.setLastChildId(0);
-    stackEntry.setActive(true);
-
-    // Set the last child of the parent to this newly added entry.
-    parent.setLastChildId(tree.lastEntryId() + treeOffset);
-
-    return true;
-}
-
-void
-TraceLogger::stopEvent(uint32_t id)
-{
-#ifdef DEBUG
-    if (id != TraceLogger_Scripts && id != TraceLogger_Engine &&
-        stack.size() > 1 && stack.lastEntry().active())
-    {
-        TreeEntry entry;
-        MOZ_ASSERT(getTreeEntry(stack.lastEntry().treeId(), &entry));
-        MOZ_ASSERT(entry.textId() == id);
-    }
-#endif
-    stopEvent();
-}
-
-void
-TraceLogger::stopEvent()
-{
-    if (enabled > 0 && stack.lastEntry().active()) {
-        uint64_t stop = rdtsc() - traceLoggers.startupTime;
-        if (!updateStop(stack.lastEntry().treeId(), stop)) {
-            fprintf(stderr, "TraceLogging: Failed to stop an event.\n");
-            enabled = 0;
-            failed = true;
-            return;
-        }
-    }
-    if (stack.size() == 1) {
-        if (enabled == 0)
-            return;
-
-        // Forcefully disable logging. We have no stack information anymore.
-        enabled = 1;
-        disable();
-        return;
-    }
-    stack.pop();
-}
-
-TraceLogging::TraceLogging()
+TraceLoggerThreadState::TraceLoggerThreadState()
 {
     initialized = false;
     enabled = 0;
     mainThreadEnabled = false;
     offThreadEnabled = false;
-    loggerId = 0;
 
     lock = PR_NewLock();
     if (!lock)
         MOZ_CRASH();
 }
 
-TraceLogging::~TraceLogging()
+TraceLoggerThreadState::~TraceLoggerThreadState()
 {
-    if (out) {
-        fprintf(out, "]");
-        fclose(out);
-        out = nullptr;
-    }
-
     for (size_t i = 0; i < mainThreadLoggers.length(); i++)
         delete mainThreadLoggers[i];
 
     mainThreadLoggers.clear();
 
     if (threadLoggers.initialized()) {
         for (ThreadLoggerHashMap::Range r = threadLoggers.all(); !r.empty(); r.popFront())
             delete r.front().value();
@@ -758,28 +425,23 @@ ContainsFlag(const char *str, const char
         if ((index == str || index[-1] == ',') && (index[flaglen] == 0 || index[flaglen] == ','))
             return true;
         index = strstr(index + flaglen, flag);
     }
     return false;
 }
 
 bool
-TraceLogging::lazyInit()
+TraceLoggerThreadState::lazyInit()
 {
     if (initialized)
         return enabled > 0;
 
     initialized = true;
 
-    out = fopen(TRACE_LOG_DIR "tl-data.json", "w");
-    if (!out)
-        return false;
-    fprintf(out, "[");
-
     if (!threadLoggers.init())
         return false;
 
     const char *env = getenv("TLLOG");
     if (!env)
         env = "";
 
     if (strstr(env, "help")) {
@@ -789,30 +451,30 @@ TraceLogging::lazyInit()
             "usage: TLLOG=option,option,option,... where options can be:\n"
             "\n"
             "Collections:\n"
             "  Default        Output all default\n"
             "  IonCompiler    Output all information about compilation\n"
             "\n"
             "Specific log items:\n"
         );
-        for (uint32_t i = 1; i < TraceLogger_LAST; i++) {
+        for (uint32_t i = 1; i < TraceLogger_Last; i++) {
             TraceLoggerTextId id = TraceLoggerTextId(i);
-            if (!TraceLogger::textIdIsToggable(id))
+            if (!TLTextIdIsToggable(id))
                 continue;
             printf("  %s\n", TLTextIdString(id));
         }
         printf("\n");
         exit(0);
         /*NOTREACHED*/
     }
 
-    for (uint32_t i = 1; i < TraceLogger_LAST; i++) {
+    for (uint32_t i = 1; i < TraceLogger_Last; i++) {
         TraceLoggerTextId id = TraceLoggerTextId(i);
-        if (TraceLogger::textIdIsToggable(id))
+        if (TLTextIdIsToggable(id))
             enabledTextIds[i] = ContainsFlag(env, TLTextIdString(id));
         else
             enabledTextIds[i] = true;
     }
 
     if (ContainsFlag(env, "Default")) {
         enabledTextIds[TraceLogger_Bailout] = true;
         enabledTextIds[TraceLogger_Baseline] = true;
@@ -885,123 +547,108 @@ TraceLogging::lazyInit()
            offThreadEnabled = true;
     }
 
     startupTime = rdtsc();
     enabled = 1;
     return true;
 }
 
-TraceLogger *
+TraceLoggerThread *
 js::TraceLoggerForMainThread(CompileRuntime *runtime)
 {
     return traceLoggers.forMainThread(runtime);
 }
 
-TraceLogger *
-TraceLogging::forMainThread(CompileRuntime *runtime)
+TraceLoggerThread *
+TraceLoggerThreadState::forMainThread(CompileRuntime *runtime)
 {
     return forMainThread(runtime->mainThread());
 }
 
-TraceLogger *
+TraceLoggerThread *
 js::TraceLoggerForMainThread(JSRuntime *runtime)
 {
     return traceLoggers.forMainThread(runtime);
 }
 
-TraceLogger *
-TraceLogging::forMainThread(JSRuntime *runtime)
+TraceLoggerThread *
+TraceLoggerThreadState::forMainThread(JSRuntime *runtime)
 {
     return forMainThread(&runtime->mainThread);
 }
 
-TraceLogger *
-TraceLogging::forMainThread(PerThreadData *mainThread)
+TraceLoggerThread *
+TraceLoggerThreadState::forMainThread(PerThreadData *mainThread)
 {
     if (!mainThread->traceLogger) {
-        AutoTraceLoggingLock lock(this);
+        AutoTraceLoggerThreadStateLock lock(this);
 
         if (!lazyInit())
             return nullptr;
 
-        TraceLogger *logger = create();
-        mainThread->traceLogger = logger;
-
-        if (!mainThreadLoggers.append(logger))
+        TraceLoggerThread *logger = create();
+        if (!logger)
             return nullptr;
 
+        if (!mainThreadLoggers.append(logger)) {
+            delete logger;
+            return nullptr;
+        }
+
+        mainThread->traceLogger = logger;
         if (!mainThreadEnabled)
             logger->disable();
     }
 
     return mainThread->traceLogger;
 }
 
-TraceLogger *
+TraceLoggerThread *
 js::TraceLoggerForCurrentThread()
 {
     PRThread *thread = PR_GetCurrentThread();
     return traceLoggers.forThread(thread);
 }
 
-TraceLogger *
-TraceLogging::forThread(PRThread *thread)
+TraceLoggerThread *
+TraceLoggerThreadState::forThread(PRThread *thread)
 {
-    AutoTraceLoggingLock lock(this);
+    AutoTraceLoggerThreadStateLock lock(this);
 
     if (!lazyInit())
         return nullptr;
 
     ThreadLoggerHashMap::AddPtr p = threadLoggers.lookupForAdd(thread);
     if (p)
         return p->value();
 
-    TraceLogger *logger = create();
+    TraceLoggerThread *logger = create();
     if (!logger)
         return nullptr;
 
     if (!threadLoggers.add(p, thread, logger)) {
         delete logger;
         return nullptr;
     }
 
     if (!offThreadEnabled)
         logger->disable();
 
     return logger;
 }
 
-TraceLogger *
-TraceLogging::create()
+TraceLoggerThread *
+TraceLoggerThreadState::create()
 {
-    if (loggerId > 999) {
-        fprintf(stderr, "TraceLogging: Can't create more than 999 different loggers.");
-        return nullptr;
-    }
-
-    if (loggerId > 0) {
-        int written = fprintf(out, ",\n");
-        if (written < 0)
-            fprintf(stderr, "TraceLogging: Error while writing.\n");
-    }
-
-    loggerId++;
-
-    int written = fprintf(out, "{\"tree\":\"tl-tree.%d.tl\", \"events\":\"tl-event.%d.tl\", \"dict\":\"tl-dict.%d.json\", \"treeFormat\":\"64,64,31,1,32\"}",
-                          loggerId, loggerId, loggerId);
-    if (written < 0)
-        fprintf(stderr, "TraceLogging: Error while writing.\n");
-
-
-    TraceLogger *logger = new TraceLogger();
+    TraceLoggerThread *logger = new TraceLoggerThread();
     if (!logger)
         return nullptr;
 
-    if (!logger->init(loggerId)) {
+    if (!logger->init()) {
         delete logger;
         return nullptr;
     }
 
     return logger;
 }
 
 bool
--- a/js/src/vm/TraceLogging.h
+++ b/js/src/vm/TraceLogging.h
@@ -10,16 +10,18 @@
 #include "mozilla/GuardObjects.h"
 
 #include "jsalloc.h"
 #include "jslock.h"
 
 #include "js/HashTable.h"
 #include "js/TypeDecls.h"
 #include "js/Vector.h"
+#include "vm/TraceLoggingGraph.h"
+#include "vm/TraceLoggingTypes.h"
 
 struct JSRuntime;
 
 namespace JS {
     class ReadOnlyCompileOptions;
 }
 
 namespace js {
@@ -31,62 +33,16 @@ namespace jit {
 
 /*
  * Tracelogging overview.
  *
  * Tracelogging makes it possible to trace the timestamp of a single event and/or
  * the duration of an event. This is implemented to give an as low overhead as
  * possible so it doesn't interfere with running.
  *
- * The output of a tracelogging session is saved in /tmp/tl-data.json.
- * The format of that file is a JS array per tracelogger (=thread), with a map
- * containing:
- *  - dict:   Name of the file containing a json table with the log text.
- *            All other files only contain a index to this table when logging.
- *  - events: Name of the file containing a flat list of log events saved
- *            in binary format.
- *            (64bit: Time Stamp Counter, 32bit index to dict)
- *  - tree:   Name of the file containing the events with duration. The content
- *            is already in a tree data structure. This is also saved in a
- *            binary file.
- *  - treeFormat: The format used to encode the tree. By default "64,64,31,1,32".
- *                There are currently no other formats to save the tree.
- *     - 64,64,31,1,31 signifies how many bytes are used for the different
- *       parts of the tree.
- *       => 64 bits: Time Stamp Counter of start of event.
- *       => 64 bits: Time Stamp Counter of end of event.
- *       => 31 bits: Index to dict file containing the log text.
- *       =>  1 bit:  Boolean signifying if this entry has children.
- *                   When true, the child can be found just behind this entry.
- *       => 32 bits: Containing the ID of the next event on the same depth
- *                   or 0 if there isn't an event on the same depth anymore.
- *
- *        /-> The position in the file. Id is this divided by size of entry.
- *        |   So in this case this would be 1 (192bits per entry).
- *        |                              /-> Indicates there are children. The
- *        |                              |   first child is located at current
- *        |                              |   ID + 1. So 1 + 1 in this case: 2.
- *        |                              |   Or 0x00180 in the tree file.
- *        |                              | /-> Next event on the same depth is
- *        |                              | |    located at 4. So 0x00300 in the
- *        |                              | |    tree file.
- *       0x0000C0: [start, end, dictId, 1, 4]
- *
- *
- *       Example:
- *                          0x0: [start, end, dictId, 1, 0]
- *                                        |
- *                      /----------------------------------\
- *                      |                                  |
- *       0xC0: [start, end, dictId, 0, 2]      0x180 [start, end, dictId, 1, 0]
- *                                                      |
- *                                  /----------------------------------\
- *                                  |                                  |
- *         0x240: [start, end, dictId, 0, 4]    0x300 [start, end, dictId, 0, 0]
- *
  *
  * Logging something is done in 3 stages.
  * 1) Get the tracelogger of the current thread.
  *     - TraceLoggerForMainThread(JSRuntime *)
  *     - TraceLoggerForCurrentThread(); // Should NOT be used for the mainthread.
  * 2) Optionally create a textId for the text that needs to get logged. This
  *    step takes some time, so try to do this beforehand, outside the hot
  *    path and don't do unnecessary repetitions, since it will criple
@@ -101,531 +57,227 @@ namespace jit {
  *    or the duration:
  *    - TraceLogStartEvent(logger, textId);
  *    - TraceLogStopEvent(logger, textId);
  *
  *    or the duration with a RAII class:
  *    - AutoTraceLog logger(logger, textId);
  */
 
-#define TRACELOGGER_TEXT_ID_LIST(_)                   \
-    _(Bailout)                                        \
-    _(Baseline)                                       \
-    _(BaselineCompilation)                            \
-    _(Engine)                                         \
-    _(GC)                                             \
-    _(GCAllocation)                                   \
-    _(GCSweeping)                                     \
-    _(Internal)                                       \
-    _(Interpreter)                                    \
-    _(Invalidation)                                   \
-    _(IonCompilation)                                 \
-    _(IonCompilationPaused)                           \
-    _(IonLinking)                                     \
-    _(IonMonkey)                                      \
-    _(IrregexpCompile)                                \
-    _(IrregexpExecute)                                \
-    _(MinorGC)                                        \
-    _(ParserCompileFunction)                          \
-    _(ParserCompileLazy)                              \
-    _(ParserCompileScript)                            \
-    _(Scripts)                                        \
-    _(VM)                                             \
-                                                      \
-    /* Specific passes during ion compilation */      \
-    _(FoldTests)                                      \
-    _(SplitCriticalEdges)                             \
-    _(RenumberBlocks)                                 \
-    _(ScalarReplacement)                              \
-    _(DominatorTree)                                  \
-    _(PhiAnalysis)                                    \
-    _(MakeLoopsContiguous)                            \
-    _(ApplyTypes)                                     \
-    _(ParallelSafetyAnalysis)                         \
-    _(AliasAnalysis)                                  \
-    _(GVN)                                            \
-    _(LICM)                                           \
-    _(RangeAnalysis)                                  \
-    _(LoopUnrolling)                                  \
-    _(EffectiveAddressAnalysis)                       \
-    _(EliminateDeadCode)                              \
-    _(EdgeCaseAnalysis)                               \
-    _(EliminateRedundantChecks)                       \
-    _(GenerateLIR)                                    \
-    _(RegisterAllocation)                             \
-    _(GenerateCode)                                   \
 
-// Predefined IDs for common operations. These IDs can be used
-// without using TraceLogCreateTextId, because they are already created.
-enum TraceLoggerTextId {
-    TraceLogger_Error = 0,
-#   define DEFINE_TEXT_ID(textId) TraceLogger_ ## textId,
-    TRACELOGGER_TEXT_ID_LIST(DEFINE_TEXT_ID)
-#   undef DEFINE_TEXT_ID
-    TraceLogger_LAST
-};
 class AutoTraceLog;
 
-template <class T>
-class ContinuousSpace {
-    T *data_;
-    uint32_t size_;
-    uint32_t capacity_;
-
-  public:
-    ContinuousSpace ()
-     : data_(nullptr)
-    { }
-
-    bool init() {
-        capacity_ = 64;
-        size_ = 0;
-        data_ = (T *) js_malloc(capacity_ * sizeof(T));
-        if (!data_)
-            return false;
-
-        return true;
-    }
-
-    T *data() {
-        return data_;
-    }
-
-    uint32_t capacity() {
-        return capacity_;
-    }
-
-    uint32_t size() {
-        return size_;
-    }
-
-    bool empty() {
-        return size_ == 0;
-    }
-
-    uint32_t lastEntryId() {
-        MOZ_ASSERT(!empty());
-        return size_ - 1;
-    }
-
-    T &lastEntry() {
-        return data()[lastEntryId()];
-    }
-
-    bool hasSpaceForAdd(uint32_t count = 1) {
-        if (size_ + count <= capacity_)
-            return true;
-        return false;
-    }
-
-    bool ensureSpaceBeforeAdd(uint32_t count = 1) {
-        if (hasSpaceForAdd(count))
-            return true;
-
-        uint32_t nCapacity = capacity_ * 2;
-        if (size_ + count > nCapacity)
-            nCapacity = size_ + count;
-        T *entries = (T *) js_realloc(data_, nCapacity * sizeof(T));
-
-        if (!entries)
-            return false;
-
-        data_ = entries;
-        capacity_ = nCapacity;
-
-        return true;
-    }
-
-    T &operator[](size_t i) {
-        MOZ_ASSERT(i < size_);
-        return data()[i];
-    }
-
-    void push(T &data) {
-        MOZ_ASSERT(size_ < capacity_);
-        data()[size_++] = data;
-    }
-
-    T &pushUninitialized() {
-        MOZ_ASSERT(size_ < capacity_);
-        return data()[size_++];
-    }
-
-    void pop() {
-        MOZ_ASSERT(!empty());
-        size_--;
-    }
-
-    void clear() {
-        size_ = 0;
-    }
-};
-
-class TraceLogger
+class TraceLoggerThread
 {
-  public:
-
 #ifdef JS_TRACE_LOGGING
   private:
     typedef HashMap<const void *,
                     uint32_t,
                     PointerHasher<const void *, 3>,
                     SystemAllocPolicy> PointerHashMap;
 
-    // The layout of the tree in memory and in the log file. Readable by JS
-    // using TypedArrays.
-    struct TreeEntry {
-        uint64_t start_;
-        uint64_t stop_;
-        union {
-            struct {
-                uint32_t textId_: 31;
-                uint32_t hasChildren_: 1;
-            } s;
-            uint32_t value_;
-        } u;
-        uint32_t nextId_;
-
-        TreeEntry(uint64_t start, uint64_t stop, uint32_t textId, bool hasChildren,
-                  uint32_t nextId)
-        {
-            start_ = start;
-            stop_ = stop;
-            u.s.textId_ = textId;
-            u.s.hasChildren_ = hasChildren;
-            nextId_ = nextId;
-        }
-        TreeEntry()
-        { }
-        uint64_t start() {
-            return start_;
-        }
-        uint64_t stop() {
-            return stop_;
-        }
-        uint32_t textId() {
-            return u.s.textId_;
-        }
-        bool hasChildren() {
-            return u.s.hasChildren_;
-        }
-        uint32_t nextId() {
-            return nextId_;
-        }
-        void setStart(uint64_t start) {
-            start_ = start;
-        }
-        void setStop(uint64_t stop) {
-            stop_ = stop;
-        }
-        void setTextId(uint32_t textId) {
-            MOZ_ASSERT(textId < uint32_t(1<<31) );
-            u.s.textId_ = textId;
-        }
-        void setHasChildren(bool hasChildren) {
-            u.s.hasChildren_ = hasChildren;
-        }
-        void setNextId(uint32_t nextId) {
-            nextId_ = nextId;
-        }
-    };
-
-    // Helper structure for keeping track of the current entries in
-    // the tree. Pushed by `start(id)`, popped by `stop(id)`. The active flag
-    // is used to know if a subtree doesn't need to get logged.
-    struct StackEntry {
-        uint32_t treeId_;
-        uint32_t lastChildId_;
-        struct {
-            uint32_t textId_: 31;
-            uint32_t active_: 1;
-        } s;
-        StackEntry(uint32_t treeId, uint32_t lastChildId, bool active = true)
-          : treeId_(treeId), lastChildId_(lastChildId)
-        {
-            s.textId_ = 0;
-            s.active_ = active;
-        }
-        uint32_t treeId() {
-            return treeId_;
-        }
-        uint32_t lastChildId() {
-            return lastChildId_;
-        }
-        uint32_t textId() {
-            return s.textId_;
-        }
-        bool active() {
-            return s.active_;
-        }
-        void setTreeId(uint32_t treeId) {
-            treeId_ = treeId;
-        }
-        void setLastChildId(uint32_t lastChildId) {
-            lastChildId_ = lastChildId;
-        }
-        void setTextId(uint32_t textId) {
-            MOZ_ASSERT(textId < uint32_t(1<<31) );
-            s.textId_ = textId;
-        }
-        void setActive(bool active) {
-            s.active_ = active;
-        }
-    };
-
-    // The layout of the event log in memory and in the log file.
-    // Readable by JS using TypedArrays.
-    struct EventEntry {
-        uint64_t time;
-        uint32_t textId;
-        EventEntry(uint64_t time, uint32_t textId)
-          : time(time), textId(textId)
-        { }
-    };
-
-    FILE *dictFile;
-    FILE *treeFile;
-    FILE *eventFile;
-
     uint32_t enabled;
     bool failed;
-    uint32_t nextTextId;
+
+    TraceLoggerGraph graph;
 
     PointerHashMap pointerMap;
+    Vector<char *, 0, js::SystemAllocPolicy> extraTextId;
 
-    ContinuousSpace<TreeEntry> tree;
-    ContinuousSpace<StackEntry> stack;
     ContinuousSpace<EventEntry> events;
 
-    uint32_t treeOffset;
-
   public:
     AutoTraceLog *top;
 
-  private:
-    // Helper functions that convert a TreeEntry in different endianness
-    // in place.
-    void entryToBigEndian(TreeEntry *entry);
-    void entryToSystemEndian(TreeEntry *entry);
-
-    // Helper functions to get/save a tree from file.
-    bool getTreeEntry(uint32_t treeId, TreeEntry *entry);
-    bool saveTreeEntry(uint32_t treeId, TreeEntry *entry);
-
-    // Return the first StackEntry that is active.
-    StackEntry &getActiveAncestor();
-
-    // This contains the meat of startEvent, except the test for enough space,
-    // the test if tracelogger is enabled and the timestamp computation.
-    bool startEvent(uint32_t id, uint64_t timestamp);
-
-    // Update functions that can adjust the items in the tree,
-    // both in memory or already written to disk.
-    bool updateHasChildren(uint32_t treeId, bool hasChildren = true);
-    bool updateNextId(uint32_t treeId, uint32_t nextId);
-    bool updateStop(uint32_t treeId, uint64_t timestamp);
-
-    // Flush the tree and events.
-    bool flush();
-
-  public:
-    TraceLogger();
-    ~TraceLogger();
+    TraceLoggerThread();
+    bool init();
+    ~TraceLoggerThread();
 
     bool init(uint32_t loggerId);
 
-    static bool textIdIsToggable(uint32_t id) {
-        if (id == TraceLogger_Error)
-            return false;
-        if (id == TraceLogger_Internal)
-            return false;
-        // Cannot toggle the logging of one engine on/off, because at the stop
-        // event it is sometimes unknown which engine was running.
-        if (id == TraceLogger_IonMonkey || id == TraceLogger_Baseline || id == TraceLogger_Interpreter)
-            return false;
-        return true;
-    }
-
     bool enable();
     bool enable(JSContext *cx);
     bool disable();
 
+    const char *eventText(uint32_t id);
+
     // The createTextId functions map a unique input to a logger ID.
-    // This ID can be used to log something. Calls to these functions should be
+    // This can be used to give start and stop events. Calls to these functions should be
     // limited if possible, because of the overhead.
+    // Note: it is not allowed to use them in logTimestamp.
     uint32_t createTextId(const char *text);
     uint32_t createTextId(JSScript *script);
     uint32_t createTextId(const JS::ReadOnlyCompileOptions &script);
+  private:
+    uint32_t createTextId(const char *filename, size_t lineno, size_t colno, const void *p);
 
+  public:
     // Log an event (no start/stop, only the timestamp is recorded).
     void logTimestamp(uint32_t id);
 
     // Record timestamps for start and stop of an event.
-    // In the stop method, the ID is only used in debug builds to test
-    // correctness.
     void startEvent(uint32_t id);
     void stopEvent(uint32_t id);
+
   private:
     void stopEvent();
 
   public:
     static unsigned offsetOfEnabled() {
-        return offsetof(TraceLogger, enabled);
+        return offsetof(TraceLoggerThread, enabled);
     }
 
   private:
     void assertNoQuotes(const char *text) {
 #ifdef DEBUG
         const char *quote = strchr(text, '"');
         MOZ_ASSERT(!quote);
 #endif
     }
 #endif
 };
 
-class TraceLogging
+class TraceLoggerThreadState
 {
 #ifdef JS_TRACE_LOGGING
     typedef HashMap<PRThread *,
-                    TraceLogger *,
+                    TraceLoggerThread *,
                     PointerHasher<PRThread *, 3>,
                     SystemAllocPolicy> ThreadLoggerHashMap;
-    typedef Vector<TraceLogger *, 1, js::SystemAllocPolicy > MainThreadLoggers;
+    typedef Vector<TraceLoggerThread *, 1, js::SystemAllocPolicy > MainThreadLoggers;
 
     bool initialized;
     bool enabled;
-    bool enabledTextIds[TraceLogger_LAST];
+    bool enabledTextIds[TraceLogger_Last];
     bool mainThreadEnabled;
     bool offThreadEnabled;
     ThreadLoggerHashMap threadLoggers;
     MainThreadLoggers mainThreadLoggers;
-    uint32_t loggerId;
-    FILE *out;
 
   public:
     uint64_t startupTime;
     PRLock *lock;
 
-    TraceLogging();
-    ~TraceLogging();
+    TraceLoggerThreadState();
+    ~TraceLoggerThreadState();
 
-    TraceLogger *forMainThread(JSRuntime *runtime);
-    TraceLogger *forMainThread(jit::CompileRuntime *runtime);
-    TraceLogger *forThread(PRThread *thread);
+    TraceLoggerThread *forMainThread(JSRuntime *runtime);
+    TraceLoggerThread *forMainThread(jit::CompileRuntime *runtime);
+    TraceLoggerThread *forThread(PRThread *thread);
 
     bool isTextIdEnabled(uint32_t textId) {
-        if (textId < TraceLogger_LAST)
+        if (textId < TraceLogger_Last)
             return enabledTextIds[textId];
         return true;
     }
 
   private:
-    TraceLogger *forMainThread(PerThreadData *mainThread);
-    TraceLogger *create();
+    TraceLoggerThread *forMainThread(PerThreadData *mainThread);
+    TraceLoggerThread *create();
     bool lazyInit();
 #endif
 };
 
 #ifdef JS_TRACE_LOGGING
-TraceLogger *TraceLoggerForMainThread(JSRuntime *runtime);
-TraceLogger *TraceLoggerForMainThread(jit::CompileRuntime *runtime);
-TraceLogger *TraceLoggerForCurrentThread();
+TraceLoggerThread *TraceLoggerForMainThread(JSRuntime *runtime);
+TraceLoggerThread *TraceLoggerForMainThread(jit::CompileRuntime *runtime);
+TraceLoggerThread *TraceLoggerForCurrentThread();
 #else
-inline TraceLogger *TraceLoggerForMainThread(JSRuntime *runtime) {
+inline TraceLoggerThread *TraceLoggerForMainThread(JSRuntime *runtime) {
     return nullptr;
 };
-inline TraceLogger *TraceLoggerForMainThread(jit::CompileRuntime *runtime) {
+inline TraceLoggerThread *TraceLoggerForMainThread(jit::CompileRuntime *runtime) {
     return nullptr;
 };
-inline TraceLogger *TraceLoggerForCurrentThread() {
+inline TraceLoggerThread *TraceLoggerForCurrentThread() {
     return nullptr;
 };
 #endif
 
-inline bool TraceLoggerEnable(TraceLogger *logger) {
+inline bool TraceLoggerEnable(TraceLoggerThread *logger) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         return logger->enable();
 #endif
     return false;
 }
-inline bool TraceLoggerEnable(TraceLogger *logger, JSContext *cx) {
+inline bool TraceLoggerEnable(TraceLoggerThread *logger, JSContext *cx) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         return logger->enable(cx);
 #endif
     return false;
 }
-inline bool TraceLoggerDisable(TraceLogger *logger) {
+inline bool TraceLoggerDisable(TraceLoggerThread *logger) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         return logger->disable();
 #endif
     return false;
 }
 
-inline uint32_t TraceLogCreateTextId(TraceLogger *logger, JSScript *script) {
+inline uint32_t TraceLogCreateTextId(TraceLoggerThread *logger, JSScript *script) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         return logger->createTextId(script);
 #endif
     return TraceLogger_Error;
 }
-inline uint32_t TraceLogCreateTextId(TraceLogger *logger,
+inline uint32_t TraceLogCreateTextId(TraceLoggerThread *logger,
                                      const JS::ReadOnlyCompileOptions &compileOptions)
 {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         return logger->createTextId(compileOptions);
 #endif
     return TraceLogger_Error;
 }
-inline uint32_t TraceLogCreateTextId(TraceLogger *logger, const char *text) {
+inline uint32_t TraceLogCreateTextId(TraceLoggerThread *logger, const char *text) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         return logger->createTextId(text);
 #endif
     return TraceLogger_Error;
 }
 #ifdef JS_TRACE_LOGGING
 bool TraceLogTextIdEnabled(uint32_t textId);
 #else
 inline bool TraceLogTextIdEnabled(uint32_t textId) {
     return false;
 }
 #endif
-inline void TraceLogTimestamp(TraceLogger *logger, uint32_t textId) {
+inline void TraceLogTimestamp(TraceLoggerThread *logger, uint32_t textId) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         logger->logTimestamp(textId);
 #endif
 }
-inline void TraceLogStartEvent(TraceLogger *logger, uint32_t textId) {
+inline void TraceLogStartEvent(TraceLoggerThread *logger, uint32_t textId) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         logger->startEvent(textId);
 #endif
 }
-inline void TraceLogStopEvent(TraceLogger *logger, uint32_t textId) {
+inline void TraceLogStopEvent(TraceLoggerThread *logger, uint32_t textId) {
 #ifdef JS_TRACE_LOGGING
     if (logger)
         logger->stopEvent(textId);
 #endif
 }
 
 // Automatic logging at the start and end of function call.
 class AutoTraceLog {
 #ifdef JS_TRACE_LOGGING
-    TraceLogger *logger;
+    TraceLoggerThread *logger;
     uint32_t textId;
     bool executed;
     AutoTraceLog *prev;
 
   public:
-    AutoTraceLog(TraceLogger *logger, uint32_t textId MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
+    AutoTraceLog(TraceLoggerThread *logger, uint32_t textId MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
       : logger(logger),
         textId(textId),
         executed(false)
     {
         MOZ_GUARD_OBJECT_NOTIFIER_INIT;
         if (logger) {
             TraceLogStartEvent(logger, textId);
 
@@ -649,41 +301,21 @@ class AutoTraceLog {
             TraceLogStopEvent(logger, textId);
         }
 
         if (logger->top == this)
             logger->top = prev;
     }
 #else
   public:
-    AutoTraceLog(TraceLogger *logger, uint32_t textId MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
+    AutoTraceLog(TraceLoggerThread *logger, uint32_t textId MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
     {
         MOZ_GUARD_OBJECT_NOTIFIER_INIT;
     }
 #endif
 
   private:
     MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
-#ifdef JS_TRACE_LOGGING
-class AutoTraceLoggingLock
-{
-  TraceLogging *logging;
-
-  public:
-    AutoTraceLoggingLock(TraceLogging *logging MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
-      : logging(logging)
-    {
-        MOZ_GUARD_OBJECT_NOTIFIER_INIT;
-        PR_Lock(logging->lock);
-    }
-    ~AutoTraceLoggingLock() {
-        PR_Unlock(logging->lock);
-    }
-  private:
-    MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
-#endif
-
 }  /* namedata js */
 
 #endif /* TraceLogging_h */
new file mode 100644
--- /dev/null
+++ b/js/src/vm/TraceLoggingGraph.cpp
@@ -0,0 +1,538 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sts=4 et sw=4 tw=99:
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "vm/TraceLoggingGraph.h"
+
+#include "mozilla/Endian.h"
+
+#include "vm/TraceLogging.h"
+
+#ifndef TRACE_LOG_DIR
+# if defined(_WIN32)
+#  define TRACE_LOG_DIR ""
+# else
+#  define TRACE_LOG_DIR "/tmp/"
+# endif
+#endif
+
+using mozilla::NativeEndian;
+
+TraceLoggerGraphState traceLoggersGraph;
+
+bool
+TraceLoggerGraphState::ensureInitialized()
+{
+    if (out)
+        return true;
+
+    out = fopen(TRACE_LOG_DIR "tl-data.json", "w");
+    if (!out)
+        return false;
+
+    fprintf(out, "[");
+    return true;
+}
+
+TraceLoggerGraphState::~TraceLoggerGraphState()
+{
+    if (out) {
+        fprintf(out, "]");
+        fclose(out);
+        out = nullptr;
+    }
+}
+
+uint32_t
+TraceLoggerGraphState::nextLoggerId()
+{
+// TODO: lock
+    if (!ensureInitialized()) {
+        fprintf(stderr, "TraceLogging: Couldn't create the main log file.");
+        return uint32_t(-1);
+    }
+
+    if (numLoggers > 999) {
+        fprintf(stderr, "TraceLogging: Can't create more than 999 different loggers.");
+        return uint32_t(-1);
+    }
+
+    if (numLoggers > 0) {
+        int written = fprintf(out, ",\n");
+        if (written < 0) {
+            fprintf(stderr, "TraceLogging: Error while writing.\n");
+            return uint32_t(-1);
+        }
+    }
+
+    int written = fprintf(out, "{\"tree\":\"tl-tree.%d.tl\", \"events\":\"tl-event.%d.tl\", "
+                               "\"dict\":\"tl-dict.%d.json\", \"treeFormat\":\"64,64,31,1,32\"}",
+                          numLoggers, numLoggers, numLoggers);
+    if (written < 0) {
+        fprintf(stderr, "TraceLogging: Error while writing.\n");
+        return uint32_t(-1);
+    }
+
+    return numLoggers++;
+}
+
+bool
+TraceLoggerGraph::init(uint64_t startTimestamp)
+{
+    if (!events.init()) {
+        failed = true;
+        return false;
+    }
+    if (!tree.init()) {
+        failed = true;
+        return false;
+    }
+    if (!stack.init()) {
+        failed = true;
+        return false;
+    }
+
+    uint32_t loggerId = traceLoggersGraph.nextLoggerId();
+    if (loggerId == uint32_t(-1)) {
+        failed = true;
+        return false;
+    }
+
+    char dictFilename[sizeof TRACE_LOG_DIR "tl-dict.100.json"];
+    sprintf(dictFilename, TRACE_LOG_DIR "tl-dict.%d.json", loggerId);
+    dictFile = fopen(dictFilename, "w");
+    if (!dictFile) {
+        failed = true;
+        return false;
+    }
+
+    char treeFilename[sizeof TRACE_LOG_DIR "tl-tree.100.tl"];
+    sprintf(treeFilename, TRACE_LOG_DIR "tl-tree.%d.tl", loggerId);
+    treeFile = fopen(treeFilename, "w+b");
+    if (!treeFile) {
+        fclose(dictFile);
+        dictFile = nullptr;
+        failed = true;
+        return false;
+    }
+
+    char eventFilename[sizeof TRACE_LOG_DIR "tl-event.100.tl"];
+    sprintf(eventFilename, TRACE_LOG_DIR "tl-event.%d.tl", loggerId);
+    eventFile = fopen(eventFilename, "wb");
+    if (!eventFile) {
+        fclose(dictFile);
+        fclose(treeFile);
+        dictFile = nullptr;
+        treeFile = nullptr;
+        failed = true;
+        return false;
+    }
+
+    // Create the top tree node and corresponding first stack item.
+    TreeEntry &treeEntry = tree.pushUninitialized();
+    treeEntry.setStart(startTimestamp);
+    treeEntry.setStop(0);
+    treeEntry.setTextId(0);
+    treeEntry.setHasChildren(false);
+    treeEntry.setNextId(0);
+
+    StackEntry &stackEntry = stack.pushUninitialized();
+    stackEntry.setTreeId(0);
+    stackEntry.setLastChildId(0);
+    stackEntry.setActive(true);
+
+    int written = fprintf(dictFile, "[");
+    if (written < 0) {
+        fprintf(stderr, "TraceLogging: Error while writing.\n");
+        fclose(dictFile);
+        fclose(treeFile);
+        fclose(eventFile);
+        dictFile = nullptr;
+        treeFile = nullptr;
+        eventFile = nullptr;
+        failed = true;
+        return false;
+    }
+
+    return true;
+}
+
+TraceLoggerGraph::~TraceLoggerGraph()
+{
+    // Write dictionary to disk
+    if (dictFile) {
+        int written = fprintf(dictFile, "]");
+        if (written < 0)
+            fprintf(stderr, "TraceLogging: Error while writing.\n");
+        fclose(dictFile);
+
+        dictFile = nullptr;
+    }
+
+    if (!failed && treeFile) {
+        // Make sure every start entry has a corresponding stop value.
+        // We temporary enable logging for this. Stop doesn't need any extra data,
+        // so is safe to do, even when we encountered OOM.
+        enabled = 1;
+        while (stack.size() > 1)
+            stopEvent(0);
+        enabled = 0;
+    }
+
+    if (!failed && !flush()) {
+        fprintf(stderr, "TraceLogging: Couldn't write the data to disk.\n");
+        enabled = 0;
+        failed = true;
+    }
+
+    if (treeFile) {
+        fclose(treeFile);
+        treeFile = nullptr;
+    }
+
+    if (eventFile) {
+        fclose(eventFile);
+        eventFile = nullptr;
+    }
+}
+
+bool
+TraceLoggerGraph::flush()
+{
+    MOZ_ASSERT(!failed);
+
+    if (treeFile) {
+        // Format data in big endian.
+        for (size_t i = 0; i < tree.size(); i++)
+            entryToBigEndian(&tree[i]);
+
+        int success = fseek(treeFile, 0, SEEK_END);
+        if (success != 0)
+            return false;
+
+        size_t bytesWritten = fwrite(tree.data(), sizeof(TreeEntry), tree.size(), treeFile);
+        if (bytesWritten < tree.size())
+            return false;
+
+        treeOffset += tree.lastEntryId();
+        tree.clear();
+    }
+
+    if (eventFile) {
+        // Format data in big endian
+        for (size_t i = 0; i < events.size(); i++) {
+            events[i].time = NativeEndian::swapToBigEndian(events[i].time);
+            events[i].textId = NativeEndian::swapToBigEndian(events[i].textId);
+        }
+
+        size_t bytesWritten = fwrite(events.data(), sizeof(EventEntry), events.size(), eventFile);
+        if (bytesWritten < events.size())
+            return false;
+        events.clear();
+    }
+
+    return true;
+}
+
+void
+TraceLoggerGraph::entryToBigEndian(TreeEntry *entry)
+{
+    entry->start_ = NativeEndian::swapToBigEndian(entry->start_);
+    entry->stop_ = NativeEndian::swapToBigEndian(entry->stop_);
+    uint32_t data = (entry->u.s.textId_ << 1) + entry->u.s.hasChildren_;
+    entry->u.value_ = NativeEndian::swapToBigEndian(data);
+    entry->nextId_ = NativeEndian::swapToBigEndian(entry->nextId_);
+}
+
+void
+TraceLoggerGraph::entryToSystemEndian(TreeEntry *entry)
+{
+    entry->start_ = NativeEndian::swapFromBigEndian(entry->start_);
+    entry->stop_ = NativeEndian::swapFromBigEndian(entry->stop_);
+
+    uint32_t data = NativeEndian::swapFromBigEndian(entry->u.value_);
+    entry->u.s.textId_ = data >> 1;
+    entry->u.s.hasChildren_ = data & 0x1;
+
+    entry->nextId_ = NativeEndian::swapFromBigEndian(entry->nextId_);
+}
+
+void
+TraceLoggerGraph::startEvent(uint32_t id, uint64_t timestamp)
+{
+    if (failed || enabled == 0)
+        return;
+
+    if (!tree.hasSpaceForAdd()) {
+        if (!tree.ensureSpaceBeforeAdd()) {
+            if (!flush()) {
+                fprintf(stderr, "TraceLogging: Couldn't write the data to disk.\n");
+                enabled = 0;
+                failed = true;
+                return;
+            }
+        }
+    }
+
+    if (!startEventInternal(id, timestamp)) {
+        fprintf(stderr, "TraceLogging: Failed to start an event.\n");
+        enabled = 0;
+        failed = true;
+        return;
+    }
+}
+
+TraceLoggerGraph::StackEntry &
+TraceLoggerGraph::getActiveAncestor()
+{
+    uint32_t parentId = stack.lastEntryId();
+    while (!stack[parentId].active())
+        parentId--;
+    return stack[parentId];
+}
+
+bool
+TraceLoggerGraph::startEventInternal(uint32_t id, uint64_t timestamp)
+{
+    if (!stack.ensureSpaceBeforeAdd())
+        return false;
+
+    // Patch up the tree to be correct. There are two scenarios:
+    // 1) Parent has no children yet. So update parent to include children.
+    // 2) Parent has already children. Update last child to link to the new
+    //    child.
+    StackEntry &parent = getActiveAncestor();
+#ifdef DEBUG
+    TreeEntry entry;
+    if (!getTreeEntry(parent.treeId(), &entry))
+        return false;
+#endif
+
+    if (parent.lastChildId() == 0) {
+        MOZ_ASSERT(!entry.hasChildren());
+        MOZ_ASSERT(parent.treeId() == tree.lastEntryId() + treeOffset);
+
+        if (!updateHasChildren(parent.treeId()))
+            return false;
+    } else {
+        MOZ_ASSERT(entry.hasChildren());
+
+        if (!updateNextId(parent.lastChildId(), tree.size() + treeOffset))
+            return false;
+    }
+
+    // Add a new tree entry.
+    TreeEntry &treeEntry = tree.pushUninitialized();
+    treeEntry.setStart(timestamp);
+    treeEntry.setStop(0);
+    treeEntry.setTextId(id);
+    treeEntry.setHasChildren(false);
+    treeEntry.setNextId(0);
+
+    // Add a new stack entry.
+    StackEntry &stackEntry = stack.pushUninitialized();
+    stackEntry.setTreeId(tree.lastEntryId() + treeOffset);
+    stackEntry.setLastChildId(0);
+    stackEntry.setActive(true);
+
+    // Set the last child of the parent to this newly added entry.
+    parent.setLastChildId(tree.lastEntryId() + treeOffset);
+
+    return true;
+}
+
+void
+TraceLoggerGraph::stopEvent(uint32_t id, uint64_t timestamp)
+{
+#ifdef DEBUG
+    if (id != TraceLogger_Scripts &&
+        id != TraceLogger_Engine &&
+        stack.size() > 1 &&
+        stack.lastEntry().active())
+    {
+        TreeEntry entry;
+        MOZ_ASSERT(getTreeEntry(stack.lastEntry().treeId(), &entry));
+        MOZ_ASSERT(entry.textId() == id);
+    }
+#endif
+
+    stopEvent(timestamp);
+}
+
+void
+TraceLoggerGraph::stopEvent(uint64_t timestamp)
+{
+    if (enabled && stack.lastEntry().active()) {
+        if (!updateStop(stack.lastEntry().treeId(), timestamp)) {
+            fprintf(stderr, "TraceLogging: Failed to stop an event.\n");
+            enabled = 0;
+            failed = true;
+            return;
+        }
+    }
+    if (stack.size() == 1) {
+        if (!enabled)
+            return;
+
+        // Forcefully disable logging. We have no stack information anymore.
+        disable(timestamp);
+        return;
+    }
+    stack.pop();
+}
+
+void
+TraceLoggerGraph::logTimestamp(uint32_t id, uint64_t timestamp)
+{
+    if (!enabled)
+        return;
+
+    if (!events.ensureSpaceBeforeAdd()) {
+        fprintf(stderr, "TraceLogging: Disabled a tracelogger due to OOM.\n");
+        enabled = 0;
+        return;
+    }
+
+    EventEntry &entry = events.pushUninitialized();
+    entry.time = timestamp;
+    entry.textId = id;
+}
+
+bool
+TraceLoggerGraph::getTreeEntry(uint32_t treeId, TreeEntry *entry)
+{
+    // Entry is still in memory
+    if (treeId >= treeOffset) {
+        *entry = tree[treeId - treeOffset];
+        return true;
+    }
+
+    int success = fseek(treeFile, treeId * sizeof(TreeEntry), SEEK_SET);
+    if (success != 0)
+        return false;
+
+    size_t itemsRead = fread((void *)entry, sizeof(TreeEntry), 1, treeFile);
+    if (itemsRead < 1)
+        return false;
+
+    entryToSystemEndian(entry);
+    return true;
+}
+
+bool
+TraceLoggerGraph::saveTreeEntry(uint32_t treeId, TreeEntry *entry)
+{
+    int success = fseek(treeFile, treeId * sizeof(TreeEntry), SEEK_SET);
+    if (success != 0)
+        return false;
+
+    entryToBigEndian(entry);
+
+    size_t itemsWritten = fwrite(entry, sizeof(TreeEntry), 1, treeFile);
+    if (itemsWritten < 1)
+        return false;
+
+    return true;
+}
+
+bool
+TraceLoggerGraph::updateHasChildren(uint32_t treeId, bool hasChildren)
+{
+    if (treeId < treeOffset) {
+        TreeEntry entry;
+        if (!getTreeEntry(treeId, &entry))
+            return false;
+        entry.setHasChildren(hasChildren);
+        if (!saveTreeEntry(treeId, &entry))
+            return false;
+        return true;
+    }
+
+    tree[treeId - treeOffset].setHasChildren(hasChildren);
+    return true;
+}
+
+bool
+TraceLoggerGraph::updateNextId(uint32_t treeId, uint32_t nextId)
+{
+    if (treeId < treeOffset) {
+        TreeEntry entry;
+        if (!getTreeEntry(treeId, &entry))
+            return false;
+        entry.setNextId(nextId);
+        if (!saveTreeEntry(treeId, &entry))
+            return false;
+        return true;
+    }
+
+    tree[treeId - treeOffset].setNextId(nextId);
+    return true;
+}
+
+bool
+TraceLoggerGraph::updateStop(uint32_t treeId, uint64_t timestamp)
+{
+    if (treeId < treeOffset) {
+        TreeEntry entry;
+        if (!getTreeEntry(treeId, &entry))
+            return false;
+        entry.setStop(timestamp);
+        if (!saveTreeEntry(treeId, &entry))
+            return false;
+        return true;
+    }
+
+    tree[treeId - treeOffset].setStop(timestamp);
+    return true;
+}
+
+void
+TraceLoggerGraph::enable()
+{
+    enabled = true;
+}
+
+void
+TraceLoggerGraph::disable(uint64_t timestamp)
+{
+    MOZ_ASSERT(enabled);
+    while (stack.size() > 1)
+        stopEvent(timestamp);
+
+    enabled = false;
+}
+
+void
+TraceLoggerGraph::log(ContinuousSpace<EventEntry> &events)
+{
+    for (uint32_t i = 0; i < events.size(); i++) {
+        if (events[i].textId == TraceLogger_Stop)
+            stopEvent(events[i].time);
+        else if (TLTextIdIsTreeEvent(events[i].textId))
+            startEvent(events[i].textId, events[i].time);
+        else
+            logTimestamp(events[i].textId, events[i].time);
+    }
+}
+
+void
+TraceLoggerGraph::addTextId(uint32_t id, const char *text)
+{
+    if (failed)
+        return;
+
+    // Assume ids are given in order. Which is currently true.
+    MOZ_ASSERT(id == nextTextId);
+    nextTextId++;
+
+    int written;
+    if (id > 0)
+        written = fprintf(dictFile, ",\n\"%s\"", text);
+    else
+        written = fprintf(dictFile, "\"%s\"", text);
+
+    if (written < 0)
+        failed = true;
+}
new file mode 100644
--- /dev/null
+++ b/js/src/vm/TraceLoggingGraph.h
@@ -0,0 +1,256 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sts=4 et sw=4 tw=99:
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef TraceLoggingGraph_h
+#define TraceLoggingGraph_h
+
+#include "mozilla/DebugOnly.h"
+
+#include "js/TypeDecls.h"
+#include "vm/TraceLoggingTypes.h"
+
+/*
+ * The output of a tracelogging session is saved in /tmp/tl-data.json.
+ * The format of that file is a JS array per tracelogger (=thread), with a map
+ * containing:
+ *  - dict:   Name of the file containing a json table with the log text.
+ *            All other files only contain a index to this table when logging.
+ *  - events: Name of the file containing a flat list of log events saved
+ *            in binary format.
+ *            (64bit: Time Stamp Counter, 32bit index to dict)
+ *  - tree:   Name of the file containing the events with duration. The content
+ *            is already in a tree data structure. This is also saved in a
+ *            binary file.
+ *  - treeFormat: The format used to encode the tree. By default "64,64,31,1,32".
+ *                There are currently no other formats to save the tree.
+ *     - 64,64,31,1,31 signifies how many bytes are used for the different
+ *       parts of the tree.
+ *       => 64 bits: Time Stamp Counter of start of event.
+ *       => 64 bits: Time Stamp Counter of end of event.
+ *       => 31 bits: Index to dict file containing the log text.
+ *       =>  1 bit:  Boolean signifying if this entry has children.
+ *                   When true, the child can be found just right after this entry.
+ *       => 32 bits: Containing the ID of the next event on the same depth
+ *                   or 0 if there isn't an event on the same depth anymore.
+ *
+ *        /-> The position in the file. Id is this divided by size of entry.
+ *        |   So in this case this would be 1 (192bits per entry).
+ *        |                              /-> Indicates there are children. The
+ *        |                              |   first child is located at current
+ *        |                              |   ID + 1. So 1 + 1 in this case: 2.
+ *        |                              |   Or 0x00180 in the tree file.
+ *        |                              | /-> Next event on the same depth is
+ *        |                              | |    located at 4. So 0x00300 in the
+ *        |                              | |    tree file.
+ *       0x0000C0: [start, end, dictId, 1, 4]
+ *
+ *
+ *       Example:
+ *                          0x0: [start, end, dictId, 1, 0]
+ *                                        |
+ *                      /----------------------------------\
+ *                      |                                  |
+ *       0xC0: [start, end, dictId, 0, 2]      0x180 [start, end, dictId, 1, 0]
+ *                                                      |
+ *                                  /----------------------------------\
+ *                                  |                                  |
+ *         0x240: [start, end, dictId, 0, 4]    0x300 [start, end, dictId, 0, 0]
+ */
+
+class TraceLoggerGraphState
+{
+    uint32_t numLoggers;
+
+    // File pointer to the "tl-data.json" file. (Explained above).
+    FILE *out;
+
+  public:
+    TraceLoggerGraphState()
+      : numLoggers(0),
+        out(nullptr)
+    { }
+    ~TraceLoggerGraphState();
+
+    uint32_t nextLoggerId();
+
+  private:
+    bool ensureInitialized();
+};
+
+class TraceLoggerGraph
+{
+    // The layout of the tree in memory and in the log file. Readable by JS
+    // using TypedArrays.
+    struct TreeEntry {
+        uint64_t start_;
+        uint64_t stop_;
+        union {
+            struct {
+                uint32_t textId_: 31;
+                uint32_t hasChildren_: 1;
+            } s;
+            uint32_t value_;
+        } u;
+        uint32_t nextId_;
+
+        TreeEntry(uint64_t start, uint64_t stop, uint32_t textId, bool hasChildren,
+                  uint32_t nextId)
+        {
+            start_ = start;
+            stop_ = stop;
+            u.s.textId_ = textId;
+            u.s.hasChildren_ = hasChildren;
+            nextId_ = nextId;
+        }
+        TreeEntry()
+        { }
+        uint64_t start() {
+            return start_;
+        }
+        uint64_t stop() {
+            return stop_;
+        }
+        uint32_t textId() {
+            return u.s.textId_;
+        }
+        bool hasChildren() {
+            return u.s.hasChildren_;
+        }
+        uint32_t nextId() {
+            return nextId_;
+        }
+        void setStart(uint64_t start) {
+            start_ = start;
+        }
+        void setStop(uint64_t stop) {
+            stop_ = stop;
+        }
+        void setTextId(uint32_t textId) {
+            MOZ_ASSERT(textId < uint32_t(1 << 31));
+            u.s.textId_ = textId;
+        }
+        void setHasChildren(bool hasChildren) {
+            u.s.hasChildren_ = hasChildren;
+        }
+        void setNextId(uint32_t nextId) {
+            nextId_ = nextId;
+        }
+    };
+
+    // Helper structure for keeping track of the current entries in
+    // the tree. Pushed by `start(id)`, popped by `stop(id)`. The active flag
+    // is used to know if a subtree doesn't need to get logged.
+    struct StackEntry {
+        uint32_t treeId_;
+        uint32_t lastChildId_;
+        struct {
+            uint32_t textId_: 31;
+            uint32_t active_: 1;
+        } s;
+        StackEntry(uint32_t treeId, uint32_t lastChildId, bool active = true)
+          : treeId_(treeId), lastChildId_(lastChildId)
+        {
+            s.textId_ = 0;
+            s.active_ = active;
+        }
+        uint32_t treeId() {
+            return treeId_;
+        }
+        uint32_t lastChildId() {
+            return lastChildId_;
+        }
+        uint32_t textId() {
+            return s.textId_;
+        }
+        bool active() {
+            return s.active_;
+        }
+        void setTreeId(uint32_t treeId) {
+            treeId_ = treeId;
+        }
+        void setLastChildId(uint32_t lastChildId) {
+            lastChildId_ = lastChildId;
+        }
+        void setTextId(uint32_t textId) {
+            MOZ_ASSERT(textId < uint32_t(1<<31));
+            s.textId_ = textId;
+        }
+        void setActive(bool active) {
+            s.active_ = active;
+        }
+    };
+
+  public:
+    TraceLoggerGraph()
+      : failed(false),
+        enabled(false),
+        nextTextId(0),
+        treeOffset(0)
+    { }
+    ~TraceLoggerGraph();
+
+    bool init(uint64_t timestamp);
+
+    // Link a textId with a particular text.
+    void addTextId(uint32_t id, const char *text);
+
+    // Create a tree out of all the given events.
+    void log(ContinuousSpace<EventEntry> &events);
+
+    // Disable/enable the logger.
+    void disable(uint64_t timestamp);
+    void enable();
+
+  private:
+    bool failed;
+    bool enabled;
+    mozilla::DebugOnly<uint32_t> nextTextId;
+
+    FILE *dictFile;
+    FILE *treeFile;
+    FILE *eventFile;
+
+    ContinuousSpace<TreeEntry> tree;
+    ContinuousSpace<StackEntry> stack;
+    uint32_t treeOffset;
+
+    ContinuousSpace<EventEntry> events;
+
+    // Helper functions that convert a TreeEntry in different endianness
+    // in place.
+    void entryToBigEndian(TreeEntry *entry);
+    void entryToSystemEndian(TreeEntry *entry);
+
+    // Helper functions to get/save a tree from file.
+    bool getTreeEntry(uint32_t treeId, TreeEntry *entry);
+    bool saveTreeEntry(uint32_t treeId, TreeEntry *entry);
+
+    // Return the first StackEntry that is active.
+    StackEntry &getActiveAncestor();
+
+    // This contains the meat of startEvent, except the test for enough space,
+    // the test if tracelogger is enabled and the timestamp computation.
+    void startEvent(uint32_t id, uint64_t timestamp);
+    bool startEventInternal(uint32_t id, uint64_t timestamp);
+
+    // Update functions that can adjust the items in the tree,
+    // both in memory or already written to disk.
+    bool updateHasChildren(uint32_t treeId, bool hasChildren = true);
+    bool updateNextId(uint32_t treeId, uint32_t nextId);
+    bool updateStop(uint32_t treeId, uint64_t timestamp);
+
+    // Flush the tree and events.
+    bool flush();
+
+    // Stop a tree event.
+    void stopEvent(uint32_t id, uint64_t timestamp);
+    void stopEvent(uint64_t timestamp);
+
+    // Log an (non-tree) event.
+    void logTimestamp(uint32_t id, uint64_t timestamp);
+};
+
+#endif /* TraceLoggingGraph_h */
new file mode 100644
--- /dev/null
+++ b/js/src/vm/TraceLoggingTypes.h
@@ -0,0 +1,225 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sts=4 et sw=4 tw=99:
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef TraceLoggingTypes_h
+#define TraceLoggingTypes_h
+
+#include "jsalloc.h"
+
+#define TRACELOGGER_TREE_ITEMS(_)                     \
+    _(Baseline)                                       \
+    _(BaselineCompilation)                            \
+    _(Engine)                                         \
+    _(GC)                                             \
+    _(GCAllocation)                                   \
+    _(GCSweeping)                                     \
+    _(Internal)                                       \
+    _(Interpreter)                                    \
+    _(Invalidation)                                   \
+    _(IrregexpCompile)                                \
+    _(IrregexpExecute)                                \
+    _(IonCompilation)                                 \
+    _(IonCompilationPaused)                           \
+    _(IonLinking)                                     \
+    _(IonMonkey)                                      \
+    _(MinorGC)                                        \
+    _(ParserCompileFunction)                          \
+    _(ParserCompileLazy)                              \
+    _(ParserCompileScript)                            \
+    _(Scripts)                                        \
+    _(VM)                                             \
+                                                      \
+    /* Specific passes during ion compilation */      \
+    _(FoldTests)                                      \
+    _(SplitCriticalEdges)                             \
+    _(RenumberBlocks)                                 \
+    _(ScalarReplacement)                              \
+    _(DominatorTree)                                  \
+    _(PhiAnalysis)                                    \
+    _(MakeLoopsContiguous)                            \
+    _(ApplyTypes)                                     \
+    _(ParallelSafetyAnalysis)                         \
+    _(AliasAnalysis)                                  \
+    _(GVN)                                            \
+    _(LICM)                                           \
+    _(RangeAnalysis)                                  \
+    _(LoopUnrolling)                                  \
+    _(EffectiveAddressAnalysis)                       \
+    _(EliminateDeadCode)                              \
+    _(EdgeCaseAnalysis)                               \
+    _(EliminateRedundantChecks)                       \
+    _(GenerateLIR)                                    \
+    _(RegisterAllocation)                             \
+    _(GenerateCode)
+
+#define TRACELOGGER_LOG_ITEMS(_)                      \
+    _(Bailout)                                        \
+    _(Stop)
+
+// Predefined IDs for common operations. These IDs can be used
+// without using TraceLogCreateTextId, because there are already created.
+enum TraceLoggerTextId {
+    TraceLogger_Error = 0,
+#define DEFINE_TEXT_ID(textId) TraceLogger_ ## textId,
+    TRACELOGGER_TREE_ITEMS(DEFINE_TEXT_ID)
+    TraceLogger_LastTreeItem,
+    TRACELOGGER_LOG_ITEMS(DEFINE_TEXT_ID)
+#undef DEFINE_TEXT_ID
+    TraceLogger_Last
+};
+
+inline const char *
+TLTextIdString(TraceLoggerTextId id)
+{
+    switch (id) {
+      case TraceLogger_Error:
+        return "TraceLogger failed to process text";
+#define NAME(textId) case TraceLogger_ ## textId: return #textId;
+        TRACELOGGER_TREE_ITEMS(NAME)
+        TRACELOGGER_LOG_ITEMS(NAME)
+#undef NAME
+      default:
+        MOZ_CRASH();
+    }
+}
+
+inline bool
+TLTextIdIsToggable(uint32_t id)
+{
+    if (id == TraceLogger_Error)
+        return false;
+    if (id == TraceLogger_Internal)
+        return false;
+    if (id == TraceLogger_Stop)
+        return false;
+    // Actually never used. But added here so it doesn't show as toggle
+    if (id == TraceLogger_LastTreeItem)
+        return false;
+    if (id == TraceLogger_Last)
+        return false;
+    // Cannot toggle the logging of one engine on/off, because at the stop
+    // event it is sometimes unknown which engine was running.
+    if (id == TraceLogger_IonMonkey || id == TraceLogger_Baseline || id == TraceLogger_Interpreter)
+        return false;
+    return true;
+}
+
+inline bool
+TLTextIdIsTreeEvent(uint32_t id)
+{
+    // Everything between TraceLogger_Error and TraceLogger_LastTreeItem are tree events and
+    // atm also every custom event.
+    return (id > TraceLogger_Error && id < TraceLogger_LastTreeItem) ||
+           id >= TraceLogger_Last;
+}
+
+template <class T>
+class ContinuousSpace {
+    T *data_;
+    uint32_t size_;
+    uint32_t capacity_;
+
+  public:
+    ContinuousSpace ()
+     : data_(nullptr)
+    { }
+
+    bool init() {
+        capacity_ = 64;
+        size_ = 0;
+        data_ = (T *) js_malloc(capacity_ * sizeof(T));
+        if (!data_)
+            return false;
+
+        return true;
+    }
+
+    T *data() {
+        return data_;
+    }
+
+    uint32_t capacity() {
+        return capacity_;
+    }
+
+    uint32_t size() {
+        return size_;
+    }
+
+    bool empty() {
+        return size_ == 0;
+    }
+
+    uint32_t lastEntryId() {
+        MOZ_ASSERT(!empty());
+        return size_ - 1;
+    }
+
+    T &lastEntry() {
+        return data()[lastEntryId()];
+    }
+
+    bool hasSpaceForAdd(uint32_t count = 1) {
+        if (size_ + count <= capacity_)
+            return true;
+        return false;
+    }
+
+    bool ensureSpaceBeforeAdd(uint32_t count = 1) {
+        MOZ_ASSERT(data_);
+        if (hasSpaceForAdd(count))
+            return true;
+
+        uint32_t nCapacity = capacity_ * 2;
+        if (size_ + count > nCapacity)
+            nCapacity = size_ + count;
+        T *entries = (T *) js_realloc(data_, nCapacity * sizeof(T));
+
+        if (!entries)
+            return false;
+
+        data_ = entries;
+        capacity_ = nCapacity;
+
+        return true;
+    }
+
+    T &operator[](size_t i) {
+        MOZ_ASSERT(i < size_);
+        return data()[i];
+    }
+
+    void push(T &data) {
+        MOZ_ASSERT(size_ < capacity_);
+        data()[size_++] = data;
+    }
+
+    T &pushUninitialized() {
+        MOZ_ASSERT(size_ < capacity_);
+        return data()[size_++];
+    }
+
+    void pop() {
+        MOZ_ASSERT(!empty());
+        size_--;
+    }
+
+    void clear() {
+        size_ = 0;
+    }
+};
+
+// The layout of the event log in memory and in the log file.
+// Readable by JS using TypedArrays.
+struct EventEntry {
+    uint64_t time;
+    uint32_t textId;
+    EventEntry(uint64_t time, uint32_t textId)
+      : time(time), textId(textId)
+    { }
+};
+
+#endif /* TraceLoggingTypes_h */