forked from scala/scala3
-
Notifications
You must be signed in to change notification settings - Fork 1
Optionally use VarHandles for Lazy Vals when targeting JDK 9+ #637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
WojciechMazur
wants to merge
2
commits into
scala:lts-3.3
Choose a base branch
from
WojciechMazur:lts/varhandle-lazy-vals
base: lts-3.3
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,7 +9,7 @@ import core.Contexts.* | |
| import core.Decorators.* | ||
| import core.DenotTransformers.IdentityDenotTransformer | ||
| import core.Flags.* | ||
| import core.NameKinds.{ExpandedName, LazyBitMapName, LazyLocalInitName, LazyLocalName} | ||
| import core.NameKinds.{ExpandedName, LazyBitMapName, LazyLocalInitName, LazyLocalName, LazyVarHandleName} | ||
| import core.StdNames.nme | ||
| import core.Symbols.* | ||
| import core.Types.* | ||
|
|
@@ -27,8 +27,10 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| * The map contains the list of the offset trees. | ||
| */ | ||
| class OffsetInfo(var defs: List[Tree], var ord: Int = 0) | ||
| class VarHandleInfo(var defs: List[Tree]) | ||
|
|
||
| private val appendOffsetDefs = mutable.Map.empty[Symbol, OffsetInfo] | ||
| private val appendVarHandleDefs = mutable.Map.empty[Symbol, VarHandleInfo] | ||
|
|
||
| override def phaseName: String = LazyVals.name | ||
|
|
||
|
|
@@ -108,12 +110,19 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| */ | ||
| override def transformTemplate(template: Template)(using Context): Tree = { | ||
| val cls = ctx.owner.asClass | ||
| appendOffsetDefs.get(cls) match { | ||
| case None => template | ||
| case Some(data) => | ||
| data.defs.foreach(defin => defin.symbol.addAnnotation(Annotation(defn.ScalaStaticAnnot, defin.symbol.span))) | ||
| cpy.Template(template)(body = addInFront(data.defs, template.body)) | ||
| } | ||
| if !selectImpl.useVarHandles then //ctx.settings.YlegacyLazyVals.value then | ||
| appendOffsetDefs.get(cls) match { | ||
| case None => template | ||
| case Some(data) => | ||
| data.defs.foreach(defin => defin.symbol.addAnnotation(Annotation(defn.ScalaStaticAnnot, defin.symbol.span))) | ||
| cpy.Template(template)(body = addInFront(data.defs, template.body)) | ||
| } | ||
| else | ||
| appendVarHandleDefs.get(cls) match { | ||
| case None => template | ||
| case Some(data) => | ||
| cpy.Template(template)(body = addInFront(data.defs, template.body)) | ||
| } | ||
| } | ||
|
|
||
| private def addInFront(prefix: List[Tree], stats: List[Tree]) = stats match { | ||
|
|
@@ -273,6 +282,33 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| } | ||
| } | ||
|
|
||
| private object selectImpl { | ||
| inline def apply[T](usingOffset: => T, usingVarHandle: => T)(using Context): T = | ||
| if useVarHandles(using ctx) then usingVarHandle else usingOffset | ||
|
|
||
| private def checkVarHandlesAllowed(using Context) = | ||
| !ctx.settings.YlegacyLazyVals.value && { | ||
| val releaseVersion = ctx.settings.javaOutputVersion.value | ||
| if releaseVersion.nonEmpty then | ||
| releaseVersion.toInt >= 9 | ||
| else | ||
| scala.util.Properties.isJavaAtLeast("9") | ||
| } | ||
WojciechMazur marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Check if environment allows VarHandles, cached per run | ||
| private var canUseVarHandles: Boolean = compiletime.uninitialized | ||
| private var cachedContext: Context = compiletime.uninitialized | ||
| def useVarHandles(using Context) = { | ||
|
Comment on lines
+298
to
+301
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There's plenty of usages, the check might allocate on each usage mostly due to |
||
| if ctx eq cachedContext then | ||
| canUseVarHandles | ||
| else | ||
| canUseVarHandles = checkVarHandlesAllowed | ||
| cachedContext = ctx | ||
| canUseVarHandles | ||
| } | ||
| } | ||
|
|
||
|
|
||
| /** | ||
| * Create a threadsafe lazy accessor and function that computes the field's value. `Evaluating` and | ||
| * `NullValue` are represented by `object`s and `Waiting` by a class that allows awaiting the completion | ||
|
|
@@ -327,20 +363,30 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| * @param memberDef the transformed lazy field member definition | ||
| * @param claz the class containing this lazy val field | ||
| * @param target the target synthetic field | ||
| * @param offset the offset of the field in the storage allocation of the class | ||
| * @param offsetOrVarHandle the offset of the field in the storage allocation or its VarHandle | ||
| * @param thiz a reference to the transformed class | ||
| */ | ||
| def mkThreadSafeDef(memberDef: ValOrDefDef, | ||
| claz: ClassSymbol, | ||
| target: Symbol, | ||
| offset: Tree, | ||
| offsetOrVarHandle: Tree, | ||
| thiz: Tree)(using Context): (DefDef, DefDef) = { | ||
| def varHandle = offsetOrVarHandle.ensuring(selectImpl.useVarHandles, "Unexpected VarHandle usage") | ||
| def offset = offsetOrVarHandle.ensuring(!selectImpl.useVarHandles, "Unexpected Offset usage") | ||
|
|
||
| val tp = memberDef.tpe.widenDealias.resultType.widenDealias | ||
| val waiting = ref(defn.LazyValsWaitingState) | ||
| val controlState = ref(defn.LazyValsControlState) | ||
| val evaluating = Select(ref(defn.LazyValsModule), lazyNme.RLazyVals.evaluating) | ||
| val nullValue = Select(ref(defn.LazyValsModule), lazyNme.RLazyVals.nullValue) | ||
| val objCasFlag = Select(ref(defn.LazyValsModule), lazyNme.RLazyVals.objCas) | ||
| val casFlag = selectImpl( | ||
| usingOffset = Select(ref(defn.LazyValsModule), lazyNme.RLazyVals.objCas), | ||
| usingVarHandle = typer.Applications.retypeSignaturePolymorphicFn( // must be retyped to avoid wrapping into Array[Object] | ||
| Select(varHandle, lazyNme.compareAndSet), | ||
| MethodType(List(defn.ObjectType,defn.ObjectType,defn.ObjectType), defn.BooleanType) | ||
| ) | ||
| ) | ||
|
|
||
| val accessorMethodSymbol = memberDef.symbol.asTerm | ||
| val lazyInitMethodName = LazyLocalInitName.fresh(memberDef.name.asTermName) | ||
| val lazyInitMethodSymbol = newSymbol(claz, lazyInitMethodName, Synthetic | Method | Private, MethodType(Nil)(_ => Nil, _ => defn.ObjectType)) | ||
|
|
@@ -382,12 +428,18 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| val lockRel = { | ||
| val lockSymb = newSymbol(lazyInitMethodSymbol, lazyNme.lock, Synthetic, waiting.typeOpt) | ||
| Block(ValDef(lockSymb, ref(target).cast(waiting.typeOpt)) | ||
| :: objCasFlag.appliedTo(thiz, offset, ref(lockSymb), ref(resSymb)) :: Nil, | ||
| :: selectImpl( | ||
| usingOffset = casFlag.appliedTo(thiz, offset, ref(lockSymb), ref(resSymb)), | ||
| usingVarHandle = casFlag.appliedTo(thiz, ref(lockSymb), ref(resSymb)) | ||
| ) :: Nil, | ||
| ref(lockSymb).select(lazyNme.RLazyVals.waitingRelease).ensureApplied) | ||
| } | ||
| // finally block | ||
| val fin = If( | ||
| objCasFlag.appliedTo(thiz, offset, evaluating, ref(resSymb)).select(nme.UNARY_!).appliedToNone, | ||
| selectImpl( | ||
| usingOffset = casFlag.appliedTo(thiz, offset, evaluating, ref(resSymb)), | ||
| usingVarHandle = casFlag.appliedTo(thiz, evaluating, ref(resSymb)) | ||
| ).select(nme.UNARY_!).appliedToNone, | ||
| lockRel, | ||
| unitLiteral | ||
| ) | ||
|
|
@@ -408,7 +460,10 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| ) | ||
| // if CAS(_, null, Evaluating) | ||
| If( | ||
| objCasFlag.appliedTo(thiz, offset, nullLiteral, evaluating), | ||
| selectImpl( | ||
| usingOffset = casFlag.appliedTo(thiz, offset, nullLiteral, evaluating), | ||
| usingVarHandle = casFlag.appliedTo(thiz, nullLiteral, evaluating) | ||
| ), | ||
| Block(ValDef(resSymb, nullLiteral) :: ValDef(resSymbNullable, nullLiteral) :: evaluate :: Nil, // var result: AnyRef = null | ||
| Return(ref(resSymbNullable), lazyInitMethodSymbol)), | ||
| unitLiteral | ||
|
|
@@ -424,7 +479,10 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| ref(current).select(defn.Object_eq).appliedTo(evaluating), | ||
| // if is Evaluating then CAS(_, Evaluating, new Waiting) | ||
| Block( | ||
| objCasFlag.appliedTo(thiz, offset, ref(current), Select(New(waiting), StdNames.nme.CONSTRUCTOR).ensureApplied) :: Nil, | ||
| selectImpl( | ||
| usingOffset = casFlag.appliedTo(thiz, offset, ref(current), Select(New(waiting), StdNames.nme.CONSTRUCTOR).ensureApplied), | ||
| usingVarHandle = casFlag.appliedTo(thiz, ref(current), Select(New(waiting), StdNames.nme.CONSTRUCTOR).ensureApplied) | ||
| ) :: Nil, | ||
| unitLiteral | ||
| ), | ||
| // if not Evaluating | ||
|
|
@@ -470,23 +528,43 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer { | |
| Select(ref(defn.LazyValsModule), lazyNme.RLazyVals.getOffsetStatic) | ||
| val containerTree = ValDef(containerSymbol, nullLiteral) | ||
|
|
||
| // create an offset for this lazy val | ||
| val offsetSymbol: TermSymbol = appendOffsetDefs.get(claz) match | ||
| case Some(info) => | ||
| newSymbol(claz, offsetName(info.defs.size), Synthetic, defn.LongType).enteredAfter(this) | ||
| case None => | ||
| newSymbol(claz, offsetName(0), Synthetic, defn.LongType).enteredAfter(this) | ||
| offsetSymbol.nn.addAnnotation(Annotation(defn.ScalaStaticAnnot, offsetSymbol.nn.span)) | ||
| val fieldTree = thizClass.select(lazyNme.RLazyVals.getDeclaredField).appliedTo(Literal(Constant(containerName.mangledString))) | ||
| val offsetTree = ValDef(offsetSymbol.nn, getOffset.appliedTo(fieldTree)) | ||
| val offsetInfo = appendOffsetDefs.getOrElseUpdate(claz, new OffsetInfo(Nil)) | ||
| offsetInfo.defs = offsetTree :: offsetInfo.defs | ||
| val offset = ref(offsetSymbol.nn) | ||
| val offsetOrVarHandle = selectImpl( | ||
| usingOffset = { | ||
| // create an offset for this lazy val | ||
| val offsetSymbol: TermSymbol = appendOffsetDefs.get(claz) match | ||
| case Some(info) => | ||
| newSymbol(claz, offsetName(info.defs.size), Synthetic, defn.LongType).enteredAfter(this) | ||
| case None => | ||
| newSymbol(claz, offsetName(0), Synthetic, defn.LongType).enteredAfter(this) | ||
| offsetSymbol.nn.addAnnotation(Annotation(defn.ScalaStaticAnnot, offsetSymbol.nn.span)) | ||
| val fieldTree = thizClass.select(lazyNme.RLazyVals.getDeclaredField).appliedTo(Literal(Constant(containerName.mangledString))) | ||
| val offsetTree = ValDef(offsetSymbol.nn, getOffset.appliedTo(fieldTree)) | ||
| val offsetInfo = appendOffsetDefs.getOrElseUpdate(claz, new OffsetInfo(Nil)) | ||
| offsetInfo.defs = offsetTree :: offsetInfo.defs | ||
| ref(offsetSymbol.nn) | ||
| }, | ||
| usingVarHandle = { | ||
| // create a VarHandle for this lazy val | ||
| val varHandleSymbol: TermSymbol = newSymbol(claz, LazyVarHandleName(containerName), Private | Synthetic, defn.VarHandleClass.typeRef).enteredAfter(this) | ||
| varHandleSymbol.addAnnotation(Annotation(defn.ScalaStaticAnnot, varHandleSymbol.span)) | ||
| val getVarHandle = | ||
| ref(defn.MethodHandlesClass).select(defn.MethodHandles_lookup).appliedToNone | ||
| .select(defn.MethodHandlesLookup_FindVarHandle).appliedTo( | ||
| thizClass, Literal(Constant(containerName.mangledString)), Literal(Constant(defn.ObjectType)) | ||
| ) | ||
| val varHandleTree = ValDef(varHandleSymbol, getVarHandle) | ||
| val varHandle = ref(varHandleSymbol) | ||
|
|
||
| val varHandleInfo = appendVarHandleDefs.getOrElseUpdate(claz, new VarHandleInfo(Nil)) | ||
| varHandleInfo.defs = varHandleTree :: varHandleInfo.defs | ||
| varHandle | ||
| } | ||
| ) | ||
|
|
||
| val swapOver = | ||
| This(claz) | ||
|
|
||
| val (accessorDef, initMethodDef) = mkThreadSafeDef(x, claz, containerSymbol, offset, swapOver) | ||
| val (accessorDef, initMethodDef) = mkThreadSafeDef(x, claz, containerSymbol, offsetOrVarHandle, swapOver) | ||
| Thicket(containerTree, accessorDef, initMethodDef) | ||
| } | ||
|
|
||
|
|
@@ -686,5 +764,6 @@ object LazyVals { | |
| val current: TermName = "current".toTermName | ||
| val lock: TermName = "lock".toTermName | ||
| val discard: TermName = "discard".toTermName | ||
| val compareAndSet: TermName = "compareAndSet".toTermName | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
6 changes: 3 additions & 3 deletions
6
.../printing/transformed/lazy-vals-new.check → ...ng/transformed/lazy-vals-new-offset.check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| -java-output-version:8 | ||
| -Ylegacy-lazy-vals:false |
File renamed without changes.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No need to explicitlly guard these on JDK8: their usage is not reachable on JDK8