ChoosePrecisionPhase.scala 8.59 KB
Newer Older
='s avatar
= committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
package daisy
package analysis

import scala.collection.immutable.Seq
import scala.io.Source

import lang.NumAnnotation
import lang.Trees._
import lang.Types._
import lang.Extractors._
import utils._
import FinitePrecision._
import Rational._
import lang.Identifiers._
import lang.TreeOps.allVariablesOf


object ChoosePrecisionPhase extends DaisyPhase {

  override val name = "Choose Precision"
  override val description = "Chooses the precision of each variable" 

  // todo: need to start timer?
  var reporter: Reporter = null

  override def run(ctx:Context, prg:Program): (Context, Program) = {

    reporter = ctx.reporter
    reporter.info(s"\nStarting $name phase")

    val fncsToConsider: Seq[String] = functionsToConsider(ctx, prg)

    var randomMP = false
='s avatar
= committed
34
    var precFile = ""
='s avatar
= committed
35 36
    for (opt <- ctx.options) opt match {
      case FlagOption("randomMP") => randomMP = true
='s avatar
= committed
37
      case ParamOption("precFile", p) => precFile = p
='s avatar
= committed
38 39 40
      case _ =>
    }

='s avatar
= committed
41 42 43
    if(randomMP && precFile != "")
      reporter.fatalError("You can only use precFile XOR randomMP.")

Raphaël Monat's avatar
Raphaël Monat committed
44 45 46



='s avatar
= committed
47 48 49
    var varPrecisionMap: Map[Identifier, Map[Identifier, Precision]] = Map()
    val uniformPrecision = ctx.constantPrecision

='s avatar
= committed
50 51 52 53 54 55 56 57 58 59 60
    if(precFile != ""){
      val (fncIdMap, varIdMap) = buildIdentifierMap(prg)
      varPrecisionMap = parseFile(precFile, fncIdMap, varIdMap, reporter, prg.id)
      // need to check typing and complete it (with max available precision?) if needed.
    } else {
      prg.defs.filter(fnc =>
        !fnc.precondition.isEmpty &&
          !fnc.body.isEmpty &&
          fncsToConsider.contains(fnc.id.toString)).map(fnc => {
            var precisionMap: Map[Identifier, Precision] = Map()
            // todo: need to change program to match this precisionMap?
='s avatar
= committed
61 62 63 64 65 66 67 68 69 70
            if(randomMP) {
              precisionMap = precisionMap ++ fnc.params.map(e => e match { case ValDef(v) => (v -> getRandomPrecision())}).toMap
              fnc.body match {
                case Some(e) =>
                  precisionMap = randomType(e, precisionMap, uniformPrecision)._1
                case None => ()
              }
            } else {
              precisionMap = allVariablesOf(fnc.body.get).map(id => (id -> uniformPrecision)).toMap
            }
='s avatar
= committed
71 72 73 74
            reporter.info(s"Chosen Precision map is for ${fnc.id} ${precisionMap.toString}")
            varPrecisionMap += fnc.id -> precisionMap
          })
    }
='s avatar
= committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    val newprg = Program(prg.id,
      prg.defs.map({
        case FunDef(id, retT, params, pre, body, post, isField) =>
          val newb = body match {
            case Some(e) => Some(introduceDowncast(e, varPrecisionMap(id), uniformPrecision)._1)
            case None => None   }
          FunDef(id, retT, params, pre, newb, post, isField)}))

    (ctx.copy(precision=varPrecisionMap), newprg)
  }

  def randomType(e:Expr, m:Map[Identifier, Precision], c:Precision) : (Map[Identifier,Precision], Precision) = {
    e match {
      case Variable(id) => (m, m(id))

      case RealLiteral(r) => (m, c)

      case ArithOperator(Seq(l, r), recons) =>
        val (map_l, t_l) = randomType(l, m, c)
        val (map_r, t_r) = randomType(r, map_l, c)
        val prec = getUpperBound(t_l, t_r)
        (map_r, prec)

      case ArithOperator(Seq(u), recons) =>
        randomType(u, m, c)

      case Let(id, value, body) =>
        val (map_value, type_value) = randomType(value, m, c)
        val prec_id = getRandomPrecision(highestPrec=type_value)
        if(prec_id < type_value) {

        }
        val new_map = map_value + (id -> prec_id)
        randomType(body, new_map, c)
    }
  }

  def introduceDowncast(e:Expr, m:Map[Identifier, Precision], c:Precision) : (Expr, Precision) = {
    e match {
      case Variable(id) => (e, m(id))
      case RealLiteral(r) => (e, c)
      case ArithOperator(Seq(l, r), recons) =>
        val (new_l, t_l) = introduceDowncast(l, m, c)
        val (new_r, t_r) = introduceDowncast(r, m, c)
        val prec = getUpperBound(t_l, t_r)
        (recons(Seq(new_l, new_r)), prec)
      case ArithOperator(Seq(u), recons) =>
        val (res, prec) = introduceDowncast(u, m, c)
        (recons(Seq(res)), prec)
      case Let(id, value, body) =>
        val (nv, tv) = introduceDowncast(value, m, c)
        val new_value =
          if (m(id) < tv) {
            Downcast(nv, FinitePrecisionType(m(id)))
          } else nv
        val (new_body, prec_body) = introduceDowncast(body, m, c)
        (Let(id, new_value, new_body), prec_body)
    }
  }

  def buildIdentifierMap(prg:Program) : (Map[String, Identifier], Map[String, Map[String, Identifier]]) = {
    def buildIdentifierMapFunction(f:FunDef): Map[String, Identifier] = {
      allVariablesOf(f.body.get).map(id => ((id.toString) -> id)).toMap
    }

    (prg.defs.map(fnc => (fnc.id.name -> fnc.id)).toMap,
Raphaël Monat's avatar
Raphaël Monat committed
141
      prg.defs.map(fnc => (fnc.id.name -> buildIdentifierMapFunction(fnc))).toMap)
='s avatar
= committed
142 143
  }

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  // def typeCheckAndComplete(fnc:FunDef, varMap: Map[Identifier, Precision], defaultPrecision:Precision, constantPrecision:Precision, reporter:Reporter) : Map[Identifier, Precision] = {

  //   def recurse(e:Expr, defPrec:Precision, cPrec:Precision, precMap:Map[Identifier, Precision]) : (Map[Identifier, Precision], Precision) = {
  //     e match {
  //       case Variable(id) =>
  //         precMap.get(id) match {
  //           case Some(m) => (precMap, m)
  //           case None => (precMap + (id -> defPrec), defPrec)
  //         }
  //       case RealLiteral(r) => (precMap, cPrec)
  //       case ArithOperator(Seq(l, r), recons) =>
  //         val (map_l, prec_l) = recurse(l, defPrec, cPrec, precMap)
  //         val (map_r, prec_r) = recurse(r, defPrec, cPrec, map_l)
  //         val prec = getUpperBound(prec_l, prec_r)
  //         (map_r, prec)
  //       case ArithOperator(Seq(u), recons) =>
  //         recurse(u, defPrec, cPrec, precMap)
  //       case Let(id, value, body) =>
  //         val (map_v, prec_v) = recurse(value, defPrec, cPrec, precMap)
  //         precMap.get(id) match {
  //           case Some(m) =>
  //             if(m <= prec_v)
  //               recurse(body, defPrec, cPrec, map_v)
  //             else
  //               reporter.fatalError(s"Contradiction in typing of Let $id.")
  //           case None =>
  //             recurse(body, defPrec, cPrec, map_v + (id -> prec_v))

  //         }
  //     }
  //   }

  //   def checkParams(p:Seq[ValDef], defPrec:Precision, precMap:Map[Identifier, Precision]) : Map[Identifier, Precision] = {
  //     p.map(e => e match { case ValDef(v) =>
  //       precMap.get(v) match {
  //         case None => (v -> defPrec)
  //         case Some(m) =>
  //       }}).toMap
  //   }

  //   val map_p = checkParams(fnc.params, defaultPrecision, varMap)
  //   val final_map = recurse(fnc.body

  // }

='s avatar
= committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  def parseFile(f:String, fncIdMap:Map[String, Identifier], varIdMap:Map[String, Map[String, Identifier]], reporter:Reporter, dummyId:Identifier) : Map[Identifier, Map[Identifier, Precision]] = {
    val bufferedSource = io.Source.fromFile(f)
    var currentFunction = ""
    var currentTypes:Array[String] = Array()
    var currentIdentifier:Identifier = dummyId
    var currentFunctionMap:Map[Identifier, Precision] = Map()
    var typeMap:Map[Identifier, Map[Identifier, Precision]] = Map()

    // input format:
    // functionName:
    //    variablei=typei

    // todo: regexp?

    for (line <- bufferedSource.getLines) {
      if(line.contains(":"))
      {
        if(!currentFunctionMap.isEmpty) {
          typeMap += (currentIdentifier -> currentFunctionMap)
        }
        currentFunction = line.split(':').head
        fncIdMap.get(currentFunction) match {
          case Some(i) =>
            currentIdentifier = i
Raphaël Monat's avatar
Raphaël Monat committed
213
            currentFunctionMap = Map()
='s avatar
= committed
214 215
          case None => reporter.fatalError(s"$currentFunction was not found in the identifier map.")
        }
Raphaël Monat's avatar
Raphaël Monat committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229
      }
      else if(line.contains("="))
      {
        currentTypes = line.split('=').map(_.trim)
        varIdMap(currentFunction).get(currentTypes(0)) match {
          case Some(id_v) =>
            val type_v = currentTypes(1) match {
              case "Float" => Float32
              case "Double" => Float64
              case "DoubleDouble" => DoubleDouble
              case "QuadDouble" => QuadDouble
              case _ => reporter.fatalError(s"The type of variable $id_v in function $currentFunction is unknown.") }
            currentFunctionMap += (id_v -> type_v)
          case None => reporter.fatalError(s"${currentTypes(0)} not found in the identifier map of $currentFunction.")
='s avatar
= committed
230 231
        }
      }
Raphaël Monat's avatar
Raphaël Monat committed
232 233
      else
        reporter.fatalError(s"Format error in $f")
='s avatar
= committed
234
    }
Raphaël Monat's avatar
Raphaël Monat committed
235
    bufferedSource.close
='s avatar
= committed
236 237
    typeMap += (currentIdentifier -> currentFunctionMap)
    typeMap
Raphaël Monat's avatar
Raphaël Monat committed
238
  }
='s avatar
= committed
239 240
}