Skip to content

Commit

Permalink
Optimize AliasAnalysis hotspot
Browse files Browse the repository at this point in the history
`scopeFor` is a real hotspot that hasn't been particularly optimized.
By using iterator and a simple variable instead of a list and checking
its length I was able to get 10% speedup.
Note that it seems tempting to throw the exception within the loop but
that seems to create a less optimized code.
  • Loading branch information
hubertp committed Jan 8, 2024
1 parent 94e1d5d commit ef26afc
Showing 1 changed file with 30 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1010,16 +1010,10 @@ case object AliasAnalysis extends IRPass {
def resolveLocalUsage(
occurrence: Graph.Occurrence.Use
): Option[Graph.Link] = {
scopeFor(occurrence.id) match {
case Some(scope) =>
scope.resolveUsage(occurrence) match {
case Some(link) =>
links += link
Some(link)
case None => None
}
case None => None
}
scopeFor(occurrence.id).flatMap(_.resolveUsage(occurrence).map { link =>
links += link
link
})
}

/** Resolves any links for the given usage of a symbol, assuming the symbol
Expand Down Expand Up @@ -1457,20 +1451,35 @@ case object AliasAnalysis extends IRPass {
def scopeFor(id: Graph.Id): Option[Scope] = {
val possibleCandidates = occurrences.filter(o => o.id == id)

if (possibleCandidates.size == 1) {
Some(this)
} else if (possibleCandidates.isEmpty) {
val childCandidates = childScopes.map(_.scopeFor(id)).collect {
case Some(scope) => scope
}

if (childCandidates.length == 1) {
Some(childCandidates.head)
} else if (childCandidates.isEmpty) {
if (possibleCandidates.isEmpty) {
if (childScopes.isEmpty) {
None
} else {
throw new CompilerError(s"ID $id defined in multiple scopes.")
var childCandidate: Scope = null
val iter = childScopes.iterator
var moreThanOne = false
while (iter.hasNext && !moreThanOne) {
iter.next().scopeFor(id) match {
case Some(s) =>
if (childCandidate == null) {
childCandidate = s
} else {
moreThanOne = true
}
case None =>
}
}

if (childCandidate == null) {
None
} else if (moreThanOne) {
throw new CompilerError(s"ID $id defined in multiple scopes.")
} else {
Some(childCandidate)
}
}
} else if (possibleCandidates.size == 1) {
Some(this)
} else {
throw new CompilerError(s"Multiple occurrences found for ID $id.")
}
Expand Down

0 comments on commit ef26afc

Please sign in to comment.