Skip to content

Commit 8c55116

Browse files
committed
Backport -Yprofile-trace from Scala 2
Adapt PresentationCompiler to always set (by default noop) profiler
1 parent 7dc4d3d commit 8c55116

File tree

8 files changed

+531
-20
lines changed

8 files changed

+531
-20
lines changed

Diff for: compiler/src/dotty/tools/dotc/config/ScalaSettings.scala

+2
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,8 @@ private sealed trait YSettings:
411411
//.withPostSetHook( _ => YprofileEnabled.value = true )
412412
val YprofileRunGcBetweenPhases: Setting[List[String]] = PhasesSetting("-Yprofile-run-gc", "Run a GC between phases - this allows heap size to be accurate at the expense of more time. Specify a list of phases, or *", "_")
413413
//.withPostSetHook( _ => YprofileEnabled.value = true )
414+
val YprofileTrace: Setting[String] = StringSetting("-Yprofile-trace", "file", "Capture trace of compilation in Chrome Trace format", "profile.trace")
415+
//.withPostSetHook( _ => YprofileEnabled.value = true )
414416

415417
// Experimental language features
416418
val YnoKindPolymorphism: Setting[Boolean] = BooleanSetting("-Yno-kind-polymorphism", "Disable kind polymorphism.")

Diff for: compiler/src/dotty/tools/dotc/core/Phases.scala

+4-1
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@ object Phases {
346346
val doSkipJava = ctx.settings.YjavaTasty.value && this <= picklerPhase && skipIfJava
347347
for unit <- units do
348348
given unitCtx: Context = runCtx.fresh.setPhase(this.start).setCompilationUnit(unit).withRootImports
349+
ctx.profiler.beforeUnit(this, unit)
349350
if ctx.run.enterUnit(unit) then
350351
try
351352
if doSkipJava && unit.typedAsJava then
@@ -355,7 +356,9 @@ object Phases {
355356
catch case ex: Throwable if !ctx.run.enrichedErrorMessage =>
356357
println(ctx.run.enrichErrorMessage(s"unhandled exception while running $phaseName on $unit"))
357358
throw ex
358-
finally ctx.run.advanceUnit()
359+
finally
360+
ctx.profiler.afterUnit(this, unit)
361+
ctx.run.advanceUnit()
359362
buf += unitCtx.compilationUnit
360363
end if
361364
end for
+190
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
// Scala 2 compiler backport of https://github.com/scala/scala/pull/7364
2+
/*
3+
* Scala (https://www.scala-lang.org)
4+
*
5+
* Copyright EPFL and Lightbend, Inc.
6+
*
7+
* Licensed under Apache License 2.0
8+
* (http://www.apache.org/licenses/LICENSE-2.0).
9+
*
10+
* See the NOTICE file distributed with this work for
11+
* additional information regarding copyright ownership.
12+
*/
13+
14+
package dotty.tools.dotc.profile
15+
16+
import scala.language.unsafeNulls
17+
18+
import java.io.Closeable
19+
import java.lang.management.ManagementFactory
20+
import java.nio.file.{Files, Path}
21+
import java.util
22+
import java.util.concurrent.TimeUnit
23+
24+
import scala.collection.mutable
25+
26+
object ChromeTrace {
27+
private object EventType {
28+
final val Start = "B"
29+
final val Instant = "I"
30+
final val End = "E"
31+
final val Complete = "X"
32+
33+
final val Counter = "C"
34+
35+
final val AsyncStart = "b"
36+
final val AsyncInstant = "n"
37+
final val AsyncEnd = "e"
38+
}
39+
}
40+
41+
/** Allows writing a subset of https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#
42+
* for use in Chrome's about://tracing or the tooling in https://www.google.com.au/search?q=catapult+tracing&oq=catapult+tracing+&aqs=chrome..69i57.3974j0j4&sourceid=chrome&ie=UTF-8 */
43+
final class ChromeTrace(f: Path) extends Closeable {
44+
import ChromeTrace.EventType
45+
private val traceWriter = FileUtils.newAsyncBufferedWriter(f)
46+
private val context = mutable.Stack[JsonContext](TopContext)
47+
private val tidCache = new ThreadLocal[String]() {
48+
override def initialValue(): String = "%05d".format(Thread.currentThread().getId())
49+
}
50+
objStart()
51+
fld("traceEvents")
52+
context.push(ValueContext)
53+
arrStart()
54+
traceWriter.newLine()
55+
56+
private val pid = ManagementFactory.getRuntimeMXBean().getName().replaceAll("@.*", "")
57+
58+
override def close(): Unit = {
59+
arrEnd()
60+
objEnd()
61+
context.pop()
62+
tidCache.remove()
63+
traceWriter.close()
64+
}
65+
66+
def traceDurationEvent(name: String, startNanos: Long, durationNanos: Long, tid: String = this.tid(), pidSuffix: String = ""): Unit = {
67+
val durationMicros = nanosToMicros(durationNanos)
68+
val startMicros = nanosToMicros(startNanos)
69+
objStart()
70+
str("cat", "scalac")
71+
str("name", name)
72+
str("ph", EventType.Complete)
73+
str("tid", tid)
74+
writePid(pidSuffix)
75+
lng("ts", startMicros)
76+
lng("dur", durationMicros)
77+
objEnd()
78+
traceWriter.newLine()
79+
}
80+
81+
private def writePid(pidSuffix: String) = {
82+
if (pidSuffix == "")
83+
str("pid", pid)
84+
else
85+
str2("pid", pid, "-", pidSuffix)
86+
}
87+
88+
def traceCounterEvent(name: String, counterName: String, count: Long, processWide: Boolean): Unit = {
89+
objStart()
90+
str("cat", "scalac")
91+
str("name", name)
92+
str("ph", EventType.Counter)
93+
str("tid", tid())
94+
writePid(pidSuffix = if (processWide) "" else tid())
95+
lng("ts", microTime())
96+
fld("args")
97+
objStart()
98+
lng(counterName, count)
99+
objEnd()
100+
objEnd()
101+
traceWriter.newLine()
102+
}
103+
104+
def traceDurationEventStart(cat: String, name: String, colour: String = "", pidSuffix: String = tid()): Unit = traceDurationEventStartEnd(EventType.Start, cat, name, colour, pidSuffix)
105+
def traceDurationEventEnd(cat: String, name: String, colour: String = "", pidSuffix: String = tid()): Unit = traceDurationEventStartEnd(EventType.End, cat, name, colour, pidSuffix)
106+
107+
private def traceDurationEventStartEnd(eventType: String, cat: String, name: String, colour: String, pidSuffix: String = ""): Unit = {
108+
objStart()
109+
str("cat", cat)
110+
str("name", name)
111+
str("ph", eventType)
112+
writePid(pidSuffix)
113+
str("tid", tid())
114+
lng("ts", microTime())
115+
if (colour != "") {
116+
str("cname", colour)
117+
}
118+
objEnd()
119+
traceWriter.newLine()
120+
}
121+
122+
private def tid(): String = tidCache.get()
123+
124+
private def nanosToMicros(t: Long): Long = TimeUnit.NANOSECONDS.toMicros(t)
125+
126+
private def microTime(): Long = nanosToMicros(System.nanoTime())
127+
128+
sealed abstract class JsonContext
129+
case class ArrayContext(var first: Boolean) extends JsonContext
130+
case class ObjectContext(var first: Boolean) extends JsonContext
131+
case object ValueContext extends JsonContext
132+
case object TopContext extends JsonContext
133+
134+
private def str(name: String, value: String): Unit = {
135+
fld(name)
136+
traceWriter.write("\"")
137+
traceWriter.write(value) // This assumes no escaping is needed
138+
traceWriter.write("\"")
139+
}
140+
private def str2(name: String, value: String, valueContinued1: String, valueContinued2: String): Unit = {
141+
fld(name)
142+
traceWriter.write("\"")
143+
traceWriter.write(value) // This assumes no escaping is needed
144+
traceWriter.write(valueContinued1) // This assumes no escaping is needed
145+
traceWriter.write(valueContinued2) // This assumes no escaping is needed
146+
traceWriter.write("\"")
147+
}
148+
private def lng(name: String, value: Long): Unit = {
149+
fld(name)
150+
traceWriter.write(String.valueOf(value))
151+
traceWriter.write("")
152+
}
153+
private def objStart(): Unit = {
154+
context.top match {
155+
case ac @ ArrayContext(first) =>
156+
if (first) ac.first = false
157+
else traceWriter.write(",")
158+
case _ =>
159+
}
160+
context.push(ObjectContext(true))
161+
traceWriter.write("{")
162+
}
163+
private def objEnd(): Unit = {
164+
traceWriter.write("}")
165+
context.pop()
166+
}
167+
private def arrStart(): Unit = {
168+
traceWriter.write("[")
169+
context.push(ArrayContext(true))
170+
}
171+
private def arrEnd(): Unit = {
172+
traceWriter.write("]")
173+
context.pop()
174+
}
175+
176+
private def fld(name: String) = {
177+
val topContext = context.top
178+
topContext match {
179+
case oc @ ObjectContext(first) =>
180+
if (first) oc.first = false
181+
else traceWriter.write(",")
182+
case context =>
183+
throw new IllegalStateException("Wrong context: " + context)
184+
}
185+
traceWriter.write("\"")
186+
traceWriter.write(name)
187+
traceWriter.write("\"")
188+
traceWriter.write(":")
189+
}
190+
}

0 commit comments

Comments
 (0)