Merge pull request #614 from aofei/min-max
ssa: add support for `min` and `max` built-in functions
This commit is contained in:
30
ssa/expr.go
30
ssa/expr.go
@@ -383,7 +383,7 @@ var boolPredOpToLLVM = []llvm.IntPredicate{
|
||||
token.NEQ - predOpBase: llvm.IntNE,
|
||||
}
|
||||
|
||||
// EQL NEQ LSS LEQ GTR GEQ == != < <= < >=
|
||||
// EQL NEQ LSS LEQ GTR GEQ == != < <= > >=
|
||||
func isPredOp(op token.Token) bool {
|
||||
return op >= predOpBase && op <= predOpLast
|
||||
}
|
||||
@@ -392,7 +392,7 @@ func isPredOp(op token.Token) bool {
|
||||
// op can be:
|
||||
// ADD SUB MUL QUO REM + - * / %
|
||||
// AND OR XOR SHL SHR AND_NOT & | ^ << >> &^
|
||||
// EQL NEQ LSS LEQ GTR GEQ == != < <= < >=
|
||||
// EQL NEQ LSS LEQ GTR GEQ == != < <= > >=
|
||||
func (b Builder) BinOp(op token.Token, x, y Expr) Expr {
|
||||
if debugInstr {
|
||||
log.Printf("BinOp %d, %v, %v\n", op, x.impl, y.impl)
|
||||
@@ -490,7 +490,7 @@ func (b Builder) BinOp(op token.Token, x, y Expr) Expr {
|
||||
llop := logicOpToLLVM[op-logicOpBase]
|
||||
return Expr{llvm.CreateBinOp(b.impl, llop, x.impl, y.impl), x.Type}
|
||||
}
|
||||
case isPredOp(op): // op: == != < <= < >=
|
||||
case isPredOp(op): // op: == != < <= > >=
|
||||
prog := b.Prog
|
||||
tret := prog.Bool()
|
||||
kind := x.kind
|
||||
@@ -1014,6 +1014,22 @@ func (b Builder) Do(da DoAction, fn Expr, args ...Expr) (ret Expr) {
|
||||
return
|
||||
}
|
||||
|
||||
// compareSelect performs a series of comparisons and selections based on the
|
||||
// given comparison op. It's used to implement operations like min and max.
|
||||
//
|
||||
// The function iterates through the provided expressions, comparing each with
|
||||
// the current result using the specified comparison op. It selects the
|
||||
// appropriate value based on the comparison.
|
||||
func (b Builder) compareSelect(op token.Token, x Expr, y ...Expr) Expr {
|
||||
ret := x
|
||||
for _, v := range y {
|
||||
cond := b.BinOp(op, ret, v)
|
||||
sel := llvm.CreateSelect(b.impl, cond.impl, ret.impl, v.impl)
|
||||
ret = Expr{sel, ret.Type}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// A Builtin represents a specific use of a built-in function, e.g. len.
|
||||
//
|
||||
// Builtins are immutable values. Builtins do not have addresses.
|
||||
@@ -1124,6 +1140,14 @@ func (b Builder) BuiltinCall(fn string, args ...Expr) (ret Expr) {
|
||||
b.Call(b.Pkg.rtFunc("MapClear"), t, m)
|
||||
return
|
||||
}
|
||||
case "min":
|
||||
if len(args) > 0 {
|
||||
return b.compareSelect(token.LSS, args[0], args[1:]...)
|
||||
}
|
||||
case "max":
|
||||
if len(args) > 0 {
|
||||
return b.compareSelect(token.GTR, args[0], args[1:]...)
|
||||
}
|
||||
}
|
||||
panic("todo: " + fn)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user