Is it possible to perform bit operations with LLVM TableGen? - llvm

Suppose I have a pattern :
def SET : R<Opcode7<"SET",0b0000000>,
(outs GPR:$rd),
(ins GPR:$src, i32imm:$IMM5),
"SET $rd, #$IMM5",
[(set GPR:$rd, (or GPR:$src, imm:$IMM5))]>;
class R<Opcode7 opcode, dag outs, dag ins, string asmstr, list<dag> pattern>
: Inst16<outs, ins, asmstr, pattern, InstFormatR> {
bits<7> Opcode = opcode.Value;
bits<5> IMM5;
bits<4> rd;
let Inst{6-0} = Opcode;
let Inst{8-7} = IMM5{4-3};
let Inst{12-9} = rd;
let Inst{15-13} = IMM5{2-0};
}
Although IMM5 matches the constant in bc well, it should minus 1 because the index starts from 0.
Expected behavior:
SET rd, 0
Actual behavior:
SET rd, 1
I don't know how and where to implement that.

Related

Second order combinatoric probabilities

Let say I have a set of symbols s = {a,b,c, ... } and a corpus1 :
a b g k.
o p a r b.
......
by simple counting I can calculate probabilities p(sym), p(sym1,sym2), p(sym1|sym2)
will use upper-case for set S and CORPUS2 and PROBABILITIES related to them
now I create Set 'S' of all combinations of 's', S = { ab,ac,ad,bc,bd,... }, such that I create CORPUS2 from corpus1 in the following manner :
ab ag ak, bg bk, gk.
op oa or ob, pa pr pb, ar ab, rb.
......
i.e all pairs combinations, order does not matter ab == ba. Commas are for visual purpose.
My question : Is it possible to express probabilities P(SYM), P(SYM1,SYM2), P(SYM1|SYM2) via p(sym), p(sym1,sym2), p(sym1|sym2) i.e. have a formula
PS> In my thinking I'm stuck at the following dilema ...
p(sym) = count(sym) / n
but to calculate P(SYM) w/o materializing CORPUS2 there seems to be no way, because it depends on p(sub-sym1),p(sub-sym2) multiplied by the lenght of the sequences they participate in. SYM = sub-sym1:sub-sym2
may be : ~P(SYM) = p(sub-sym1,sub-sym2) * p(sub-sym1) * p(sub-sym2) * avg-seq-len
P(SYM) = for seq in corpus1 :
total += ( len(seq) * (len(seq)+1)) / 2
for sub-sym1 and sub-sym2 in combinations(seq,2) :
if sub-sym1 and sub-sym2 == SYM :
count += 1
return count/total
there is a condition and hidden/random parameter/length involved ..
P(SYM1,SYM2), P(SYM1|SYM2) ??
Probabilities are defined/calculated in the usual way by counting .. for lower case symbols using corpus1 and for upper case symbols using CORPUS2.

When I defined a function I got: error unexpected token: (

I have already seen the community of Crystal, but I couldn't find this problem.
def Twosum(a = [] of Int32, target = 0)
map = {} of Int32 : Int32
a.each_index do |i|
diff = target - a[i]
if map.key?(diff):
return [map.fetch(diff), i]
elsif
map[a[i]] = i
end
end
return 0`enter code here`
end
a = [1,4,6,3]
target = 7
puts(Twosum(a,target))
What's the problem?
Many problems. The one you ask about is: Crystal is very opinionated regarding case. Methods must start with lowercase; yours starts with uppercase, which Crystal does not like at all. Some other problems:
{} of Int32 : Int32 should use a fat arrow, not a colon: {} of Int32 => Int32
if statement does not end with a colon, it is not Python.
There is no method named key?; use has_key?
fetch (in current Crystal version) requires either a block or a second argument that specifies a default; if you do not need to specify a default behaviour (and you don't, since you check whether the key exists), you can just use [].
I'm really not sure what the code is intended to do, so I can't comment on the logic, semantics and style; but here's your code without syntax errors:
def twosum(a = [] of Int32, target = 0)
map = {} of Int32 => Int32
a.each_index do |i|
diff = target - a[i]
if map.has_key?(diff)
return [map[diff], i]
elsif
map[a[i]] = i
end
end
return 0
end
a = [1, 4, 6, 3]
target = 7
puts(twosum(a, target))

expression evaluator in scala (with maybe placeholders?)

I am reading something like this from my configuration file :
metric1.critical = "<2000 || >20000"
metric1.okay = "=1"
metric1.warning = "<=3000"
metric2.okay = ">0.9 && < 1.1 "
metric3.warning ="( >0.9 && <1.5) || (<500 &&>200)"
and I have a
metric1.value = //have some value
My aim is to basically evaluate
if(metric1.value<2000 || metric1.value > 20000)
metric1.setAlert("critical");
else if(metric1.value=1)
metric.setAlert("okay");
//and so on
I am not really good with regex so I am going to try not to use it. I am coding in Scala and wanted to know if any existing library can help with this. Maybe i need to put placeholders to fill in the blanks and then evaluate the expression? But how do I evaluate the expression most efficiently and with less overhead?
EDIT:
In java how we have expression evaluator Libraries i was hoping i could find something similar for my code . Maybe I can add placeholders in the config file like "?" these to substitute my metric1.value (read variables) and then use an evaluator?
OR
Can someone suggest a good regex for this?
Thanks in advance!
This sounds like you want to define your own syntax using a parser combinator library.
There is a parser combinator built into the scala class library. Since the scala library has been modularized, it is now a separate project that lives at https://github.com/scala/scala-parser-combinators.
Update: everybody looking for a parser combinator library that is conceptually similar to scala-parser-combinators should take a look at fastparse. It is very fast, and does not use macros. So it can serve as a drop-in replacement for scala-parser-combinators.
There are some examples on how to use it in Programming in Scala, Chapter 33, "Combinator Parsing".
Here is a little grammar, ast and evaluator to get you started. This is missing a lot of things such as whitespace handling, operator priority etc. You should also not use strings for encoding the different comparison operators. But I think with this and the chapter from Programming in Scala you should be able to come up with something that suits your needs.
import scala.util.parsing.combinator.{JavaTokenParsers, PackratParsers}
sealed abstract class AST
sealed abstract class BooleanExpression extends AST
case class BooleanOperation(op: String, lhs: BooleanExpression, rhs:BooleanExpression) extends BooleanExpression
case class Comparison(op:String, rhs:Constant) extends BooleanExpression
case class Constant(value: Double) extends AST
object ConditionParser extends JavaTokenParsers with PackratParsers {
val booleanOperator : PackratParser[String] = literal("||") | literal("&&")
val comparisonOperator : PackratParser[String] = literal("<=") | literal(">=") | literal("==") | literal("!=") | literal("<") | literal(">")
val constant : PackratParser[Constant] = floatingPointNumber.^^ { x => Constant(x.toDouble) }
val comparison : PackratParser[Comparison] = (comparisonOperator ~ constant) ^^ { case op ~ rhs => Comparison(op, rhs) }
lazy val p1 : PackratParser[BooleanExpression] = booleanOperation | comparison
val booleanOperation = (p1 ~ booleanOperator ~ p1) ^^ { case lhs ~ op ~ rhs => BooleanOperation(op, lhs, rhs) }
}
object Evaluator {
def evaluate(expression:BooleanExpression, value:Double) : Boolean = expression match {
case Comparison("<=", Constant(c)) => value <= c
case Comparison(">=", Constant(c)) => value >= c
case Comparison("==", Constant(c)) => value == c
case Comparison("!=", Constant(c)) => value != c
case Comparison("<", Constant(c)) => value < c
case Comparison(">", Constant(c)) => value > c
case BooleanOperation("||", a, b) => evaluate(a, value) || evaluate(b, value)
case BooleanOperation("&&", a, b) => evaluate(a, value) && evaluate(b, value)
}
}
object Test extends App {
def parse(text:String) : BooleanExpression = ConditionParser.parseAll(ConditionParser.p1, text).get
val texts = Seq(
"<2000",
"<2000||>20000",
"==1",
"<=3000",
">0.9&&<1.1")
val xs = Seq(0.0, 1.0, 100000.0)
for {
text <- texts
expression = parse(text)
x <- xs
result = Evaluator.evaluate(expression, x)
} {
println(s"$text $expression $x $result")
}
}
Scala has built in Interpreter library which you can use. The library provides functionalities similar to eval() in many other languages. You can pass Scala code snippet as String to the .interpret method and it will evaluate it.
import scala.tools.nsc.{ Interpreter, Settings }
val settings = new Settings
settings.usejavacp.value = true
val in = new Interpreter(settings)
val lowerCritical = "<2000" // set the value from config
val value = 200
in.interpret(s"$value $lowerCritical") //> res0: Boolean = true
val value1 = 20000 //> value1 : Int = 20000
in.interpret(s"$value1 $lowerCritical") //> res1: Boolean = false
You want to use an actual parser for this.
Most answers are suggesting Scala's parser combinators, and that's a perfectly valid choice, if a bit out-of-date.
I'd suggest Parboiled2, an other parser combinator implementation that has the distinct advantage of being written as Scala macros - without getting too technical, it means your parser is generated at compile time rather than runtime, which can yield significant performance improvements. Some benchmarks have Parboiled2 up to 200 times as fast as Scala's parser combinator.
And since parser combinators are now in a separate dependency (as of 2.11, I believe), there really is no good reason to prefer them to Parboiled2.
I recently faced the same problem and I ended up writing my own expression evaluation library scalexpr. It is a simple library but it can validate / evaluate expressions that are similar to the ones in the question. You can do things like:
val ctx = Map("id" -> 10L, "name" -> "sensor1")
val parser = ExpressionParser()
val expr = parser.parseBooleanExpression(""" id == 10L || name == "sensor1" """).get
println(expr3.resolve(ctx3)) // prints true
If you don't want to use the library, I recommend the fastparse parser... It is much faster than parser combinators, a little bit slower than parboiled, but much easier to use than both.

How to emulate .net Int64 in VB6?

How can store an Int64 number in VB6, to work with Win32 functions?
Is there a way to define a type like Int64 in .net? And simply evaluate the number.
I think many of VB6 programmers need something like this,
Because some of the Win32 API's use _int64 as their parameters.
I wrote a function to cast a currency into an API compatible structure.
Put these codes in a module file.
Private Declare Sub CopyMemory lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Const SIZEOF_INT64 As Long = 8
Public Type Int64 'LowPart must be the first one in LittleEndian systems
'required part
LowPart As Long
HighPart As Long
'optional part
SignBit As Byte 'define this as long if you want to get minimum CPU access time.
End Type
'with the SignBit you can emulate both Int64 and UInt64 without changing the real sign bit in HighPart.
'but if you want to change it you can access it like this mySign = (myVar.HighPart And &H80000000)
'or turn on the sign bit using myVar.HighPart = (myVar.HighPart Or &H80000000)
Public Function CInt64(ByVal vCur As Currency) As Int64
vCur = (CCur(vCur) * 0.0001#)
Call CopyMemory(CInt64, vCur, SIZEOF_INT64)
End Function
Now you can simply use CInt64 to create an Int64 number.
ex:
myRetVal = Win32APIFunctionWithOneInt64Param(CInt64(10000000))
'----OR
Dim myNum As Int64
myNum = CInt64(10000000)
And for more operations:
Public Sub Op_Ev(Dest As Int64, Src As Int64) 'for setting the value.
Call CopyMemory(Dest, Src, SIZEOF_INT64)
End Sub
Public Function Op_Eq(V1 As Int64, V2 As Int64) As Boolean 'for equal comparison.
Op_Eq = (V1.LowPart = V2.LowPart) : If Not Op_Eq Then Exit Function
Op_Eq = (V1.HighPart = V2.HighPart)
End Function
Public Function Op_Gr(V1 As Int64, V2 As Int64, Optional ByVal IsUnsignedComparison As Boolean = False) As Boolean 'for grater comparison.
If IsUnsignedComparison Then
Dim H1 As Long, H2 As Long 'don't change the location of these definitions to optimize the function to prevent to execute two or more {SUB ESP, 4}
H1 = (V1.HighPart And &H7FFFFFFF) : H2 = (V2.HighPart And &H7FFFFFFF)
Op_Gr = (H1 > H2) : If (H1 <> H2) Then Exit Function
Dim HBS1 As Long, HBS2 As Long 'don't change the type of these two vars to byte to keep alignment for local variables.
HBS1 = ((V1.HighPart And &H80000000) / &H80000000) 'export the sign bit and shift it to the right.
HBS2 = ((V2.HighPart And &H80000000) / &H80000000) 'export the sign bit and shift it to the right.
Op_Gr = (HBS1 > HBS2) : If (HBS1 <> HBS2) Then Exit Function
Else
Op_Gr = (V1.HighPart > V2.HighPart) : If (V1.HighPart <> V2.HighPart) Then Exit Function
End If
Op_Gr = (V1.LowPart > V2.LowPart)
End Function
Public Function Op_Ls(V1 As Int64, V2 As Int64, Optional ByVal IsUnsignedComparison As Boolean = False) As Boolean 'for less comparison.
If IsUnsignedComparison Then
Dim H1 As Long, H2 As Long 'don't change the location of these definitions to optimize the function to prevent to execute two or more {SUB ESP, 4}
H1 = (V1.HighPart And &H7FFFFFFF) : H2 = (V2.HighPart And &H7FFFFFFF)
Op_Ls = (H1 < H2) : If (H1 <> H2) Then Exit Function
Dim HBS1 As Long, HBS2 As Long 'don't change the type of these two vars to byte to keep alignment for local variables.
HBS1 = ((V1.HighPart And &H80000000) / &H80000000) 'export the sign bit and shift it to the right.
HBS2 = ((V2.HighPart And &H80000000) / &H80000000) 'export the sign bit and shift it to the right.
Op_Ls = (HBS1 < HBS2) : If (HBS1 <> HBS2) Then Exit Function
Else
Op_Ls = (V1.HighPart < V2.HighPart) : If (V1.HighPart <> V2.HighPart) Then Exit Function
End If
Op_Ls = (V1.LowPart < V2.LowPart)
End Function
Public Function Op_Cmp(V1 As Int64, V2 As Int64, Optional ByVal IsUnsignedComparison As Boolean = False) As Long 'for comparison.
If Op_Gr(V1, V2, IsUnsignedComparison) Then
Op_Cmp = 1
ElseIf Op_Ls(V1, V2, IsUnsignedComparison) Then
Op_Cmp = -1
Else
Op_Cmp = 0
End If
End Function

Regular expression puzzle

This is not homework, but an old exam question. I am curious to see the answer.
We are given an alphabet S={0,1,2,3,4,5,6,7,8,9,+}. Define the language L as the set of strings w from this alphabet such that w is in L if:
a) w is a number such as 42 or w is the (finite) sum of numbers such as 34 + 16 or 34 + 2 + 10
and
b) The number represented by w is divisible by 3.
Write a regular expression (and a DFA) for L.
This should work:
^(?:0|(?:(?:[369]|[147](?:0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147]0*(?:\+?(?:0\
+)*[369]0*)*\+?(?:0\+)*[258])*(?:0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[258]|0*(?:
\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147]0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147])|[
258](?:0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[258]0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0
\+)*[147])*(?:0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147]|0*(?:\+?(?:0\+)*[369]0*)
*\+?(?:0\+)*[258]0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[258]))0*)+)(?:\+(?:0|(?:(?
:[369]|[147](?:0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147]0*(?:\+?(?:0\+)*[369]0*)
*\+?(?:0\+)*[258])*(?:0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[258]|0*(?:\+?(?:0\+)*
[369]0*)*\+?(?:0\+)*[147]0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147])|[258](?:0*(?
:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[258]0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147])*
(?:0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[147]|0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)
*[258]0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*[258]))0*)+))*$
It works by having three states representing the sum of the digits so far modulo 3. It disallows leading zeros on numbers, and plus signs at the start and end of the string, as well as two consecutive plus signs.
Generation of regular expression and test bed:
a = r'0*(?:\+?(?:0\+)*[369]0*)*\+?(?:0\+)*'
b = r'a[147]'
c = r'a[258]'
r1 = '[369]|[147](?:bc)*(?:c|bb)|[258](?:cb)*(?:b|cc)'
r2 = '(?:0|(?:(?:' + r1 + ')0*)+)'
r3 = '^' + r2 + r'(?:\+' + r2 + ')*$'
r = r3.replace('b', b).replace('c', c).replace('a', a)
print r
# Test on 10000 examples.
import random, re
random.seed(1)
r = re.compile(r)
for _ in range(10000):
x = ''.join(random.choice('0123456789+') for j in range(random.randint(1,50)))
if re.search(r'(?:\+|^)(?:\+|0[0-9])|\+$', x):
valid = False
else:
valid = eval(x) % 3 == 0
result = re.match(r, x) is not None
if result != valid:
print 'Failed for ' + x
Note that my memory of DFA syntax is woefully out of date, so my answer is undoubtedly a little broken. Hopefully this gives you a general idea. I've chosen to ignore + completely. As AmirW states, abc+def and abcdef are the same for divisibility purposes.
Accept state is C.
A=1,4,7,BB,AC,CA
B=2,5,8,AA,BC,CB
C=0,3,6,9,AB,BA,CC
Notice that the above language uses all 9 possible ABC pairings. It will always end at either A,B,or C, and the fact that every variable use is paired means that each iteration of processing will shorten the string of variables.
Example:
1490 = AACC = BCC = BC = B (Fail)
1491 = AACA = BCA = BA = C (Success)
Not a full solution, just an idea:
(B) alone: The "plus" signs don't matter here. abc + def is the same as abcdef for the sake of divisibility by 3. For the latter case, there is a regexp here: http://blog.vkistudios.com/index.cfm/2008/12/30/Regular-Expression-to-determine-if-a-base-10-number-is-divisible-by-3
to combine this with requirement (A), we can take the solution of (B) and modify it:
First read character must be in 0..9 (not a plus)
Input must not end with a plus, so: Duplicate each state (will use S for the original state and S' for the duplicate to distinguish between them). If we're in state S and we read a plus we'll move to S'.
When reading a number we'll go to the new state as if we were in S. S' states cannot accept (another) plus.
Also, S' is not "accept state" even if S is. (because input must not end with a plus).