asm/AJGeneratedCode.st
changeset 3 483729eb4432
child 4 f2d0d2859193
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/asm/AJGeneratedCode.st	Tue Dec 15 23:18:02 2015 +0000
@@ -0,0 +1,108 @@
+"{ Package: 'jv:dragonfly/asm' }"
+
+"{ NameSpace: Smalltalk }"
+
+Object subclass:#AJGeneratedCode
+	instanceVariableNames:'bytes labels'
+	classVariableNames:''
+	poolDictionaries:''
+	category:'AsmJit-Core'
+!
+
+AJGeneratedCode comment:''
+!
+
+!AJGeneratedCode class methodsFor:'instance creation'!
+
+fromInstructions: instructions
+    ^ self new fromInstructions: instructions
+! !
+
+!AJGeneratedCode methodsFor:'accessing'!
+
+bytes
+    ^ bytes
+!
+
+bytes: aBytes 
+
+    bytes := aBytes
+    
+!
+
+labels: aLabels
+
+    "turn labels into a simple name->offset pairs"
+    aLabels keysAndValuesDo: [:name :lbl |
+        labels at: name put: lbl paddedOffset ].
+        
+!
+
+offsetAt: aLabelName
+    ^ labels at: aLabelName
+! !
+
+!AJGeneratedCode methodsFor:'initialize-release'!
+
+fromInstructions: instructions
+    
+    bytes := ByteArray new: 100 streamContents: [:stream|
+        instructions do: [ :each |
+            each extractLabels: [:name :pos | labels at: name put: pos ].
+            each storeOn: stream ]].
+!
+
+initialize
+    labels := Dictionary new.
+    
+! !
+
+!AJGeneratedCode methodsFor:'output'!
+
+dumpWithLabels
+
+    "dump the native code , interspersed with labels"
+    
+    | offsets i str |
+    
+    offsets := OrderedCollection new.
+
+    labels keysAndValuesDo: [ :name :offset |
+        offsets add: (offset -> name)
+    ].
+
+    offsets := offsets sort: [:a :b | a key < b key ].
+    
+    str := String new writeStream.
+    i := 0.
+    
+    offsets do: [:offset |
+        i to: offset key -1 do: [:x | str nextPutAll: ((bytes at: i+1) printStringBase: 16 nDigits: 2) ; space. i:=i+1. ].
+        str cr; nextPutAll: offset value; cr.
+    ].
+
+    i to: bytes size-1 do: [:x | str nextPutAll: ((bytes at: i+1) printStringBase: 16 nDigits: 2) ; space. i := i + 1] .
+    ^ str contents
+!
+
+saveToFile
+    self saveToFile: 'asm.bin'
+!
+
+saveToFile: fileName
+
+    (FileStream forceNewFileNamed: fileName)  
+        nextPutAll: bytes;
+        close  
+! !
+
+!AJGeneratedCode methodsFor:'printing'!
+
+printOn: aStream
+
+    bytes notNil ifTrue: [
+        aStream nextPutAll: self dumpWithLabels
+        
+        ]
+! !
+