StaticAnalyzer.scala 12.8 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2
package uvm.staticanalysis

Kunshan Wang's avatar
Kunshan Wang committed
3 4 5 6 7 8 9 10 11 12
import uvm._
import uvm.types._
import uvm.ssavariables._
import org.slf4j.LoggerFactory
import com.typesafe.scalalogging.Logger

object StaticAnalyzer {
  val logger: Logger = Logger(LoggerFactory.getLogger(getClass.getName))
}

Kunshan Wang's avatar
Kunshan Wang committed
13
class StaticAnalyzer {
Kunshan Wang's avatar
Kunshan Wang committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
  import StaticAnalyzer._

  type MutableSet[T] = collection.mutable.HashSet[T]
  val MutableSet = collection.mutable.HashSet
  type MutableMap[K, V] = collection.mutable.HashMap[K, V]
  val MutableMap = collection.mutable.HashMap
  type MutableQueue[T] = collection.mutable.Queue[T]
  val MutableQueue = collection.mutable.Queue
  type MutableStack[T] = collection.mutable.Stack[T]
  val MutableStack = collection.mutable.Stack

  def checkBundle(bundle: Bundle, parentBundle: Option[GlobalBundle]): Unit = {
    new BundleChecker(bundle, parentBundle).check()
  }

  class BundleChecker(bundle: Bundle, parentBundle: Option[GlobalBundle]) {
    def check(): Unit = {
      checkTypes()
      checkSigs()
      checkConsts()
34 35 36
      checkGlobals()
      checkExpFuncs()
      checkFuncs()
Kunshan Wang's avatar
Kunshan Wang committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 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 141 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    }

    def checkTypes(): Unit = {
      val compositeTypes = bundle.typeNs.all.flatMap {
        case ty: AbstractCompositeType => Some(ty)
        case _                         => None
      }.toSeq
      checkCompositeTypesNotRecursive(compositeTypes)
    }

    def checkCompositeTypesNotRecursive(compTys: Seq[AbstractCompositeType]): Unit = {
      val world = MutableSet(compTys: _*) // All types in this bundle. Assume all other types are valid.
      val visited = MutableSet[Type]()

      for (rootTy <- world if !visited.contains(rootTy)) {
        val inStack = MutableSet[AbstractCompositeType]()

        def visit(ty: AbstractCompositeType): Unit = {
          logger.debug("Checking composite type %s".format(ty.repr))
          visited(ty) = true
          inStack(ty) = true
          val succs = ty match {
            case TypeStruct(fieldTys)        => fieldTys
            case TypeArray(elemTy, _)        => Seq(elemTy)
            case TypeVector(elemTy, _)       => Seq(elemTy)
            case TypeHybrid(fixedTys, varTy) => fixedTys ++ Seq(varTy)
          }

          succs foreach {
            case succ @ TypeHybrid(fixedTys, varTy) =>
              throw error("Composite type %s contains hybrid %s".format(ty.repr, succ.repr),
                pretty = Seq(ty, succ))
            case succ @ TypeVoid() =>
              throw error("Composite type %s contains void %s".format(ty.repr, succ.repr),
                pretty = Seq(ty, succ))
            case succ: AbstractCompositeType => {
              if (inStack(succ)) {
                throw error("Composite type %s contains itself or its parent %s".format(ty.repr, succ.repr),
                  pretty = Seq(ty, succ))
              } else if (!visited(succ) && world.contains(succ)) {
                visit(succ)
              } else {
                // Ignore visited or out-of-bundle types.
              }
            }
            case _ => // do nothing if it is not composite
          }
          inStack(ty) = false
        }

        visit(rootTy)
      }
    }

    def checkValueType(ty: Type): Unit = {
      val invalidTypeKind = ty match {
        case _: TypeWeakRef => Some("weak reference")
        case _: TypeHybrid  => Some("hybrid")
        case _: TypeVoid    => Some("void")
        case _              => None
      }

      invalidTypeKind.foreach { kind =>
        throw error("%s %s cannot be the type of an SSA variable".format(kind, ty.repr),
          pretty = Seq(ty))
      }
    }

    def checkSigs(): Unit = {
      for (sig <- bundle.funcSigNs.all) {
        checkSig(sig)
      }
    }

    def checkSig(sig: FuncSig): Unit = {
      for (ty <- sig.paramTys ++ sig.retTys) try {
        checkValueType(ty)
      } catch {
        case e: StaticCheckingException => throw error("In function signature %s: %s".format(sig.repr, e.getMessage),
          pretty = Seq(sig), cause = e.getCause)
      }
    }

    def checkConsts(): Unit = {
      for (c <- bundle.constantNs.all) {
        checkScalarConst(c)
      }
      val compositeConsts = bundle.constantNs.all.flatMap {
        case c: ConstSeq => Some(c)
        case _           => None
      }.toSeq
      checkCompositeConstantsNotRecursive(compositeConsts)
    }

    def checkScalarConst(c: Constant): Unit = {
      c match {
        case cc @ ConstInt(ty, _) => ty match {
          case TypeInt(_)      =>
          case TypeUPtr(_)     =>
          case TypeUFuncPtr(_) =>
          case _ => {
            throw error("Constant %s: int literal is not suitable for type %s".format(c.repr, ty.repr),
              pretty = Seq(c, ty))
          }
        }
        case cc @ ConstFloat(ty, _) => ty match {
          case TypeFloat() =>
          case _ => {
            throw error("Constant %s: float literal is not suitable for type %s".format(c.repr, ty.repr),
              pretty = Seq(c, ty))
          }
        }
        case cc @ ConstDouble(ty, _) => ty match {
          case TypeDouble() =>
          case _ => {
            throw error("Constant %s: double literal is not suitable for type %s".format(c.repr, ty.repr),
              pretty = Seq(c, ty))
          }
        }
        case cc @ ConstNull(ty) => ty match {
          case TypeRef(_)  =>
          case TypeIRef(_) =>
          case TypeWeakRef(_) => {
            throw error("Constant %s: type %s is a weakref, which cannot have values.".format(c.repr, ty.repr),
              pretty = Seq(c, ty))
          }
          case TypeFuncRef(_)       =>
          case TypeStackRef()       =>
          case TypeThreadRef()      =>
          case TypeFrameCursorRef() =>
          case _ => {
            throw error("Constant %s: NULL literal is not suitable for type %s".format(c.repr, ty.repr),
              pretty = Seq(c, ty))
          }
        }
        case cc @ ConstSeq(ty, elems) => // Ignore for now
      }
    }

    def checkCompositeConstantsNotRecursive(compConsts: Seq[ConstSeq]): Unit = {
      val world = MutableSet(compConsts: _*) // All ConstSeq instances in this bundle. Assume all other constants are valid.
      val visited = MutableSet[ConstSeq]()

      for (rootConst <- world if !visited.contains(rootConst)) {
        val inStack = MutableSet[ConstSeq]()

        def visit(c: ConstSeq): Unit = {
          logger.debug("Checking composite constant %s".format(c.repr))
          visited(c) = true
          inStack(c) = true
          val succs = c match {
            case ConstSeq(ty, elems) => {
              val expectedArity = ty match {
                case t @ TypeStruct(fieldTys)   => fieldTys.length
                case t @ TypeArray(elemTy, sz)  => sz
                case t @ TypeVector(elemTy, sz) => sz
                case _ => throw error("Constant %s: sequence literal is not suitable for type %s".format(c.repr, ty.repr),
                  pretty = Seq(c, ty))
              }

              val actualArity = elems.length
              if (actualArity != expectedArity) {
                throw error("Constant %s: type %s expects %d elements, but %d found".format(c.repr, ty.repr,
                  expectedArity, actualArity), pretty = Seq(c, ty))
              }

              elems
            }
          }

          succs foreach {
            case succ: ConstSeq => {
              if (inStack(succ)) {
                throw error("Constant %s contains itself or its parent %s".format(c.repr, succ.repr),
                  pretty = Seq(c, succ))
              } else if (!visited.contains(succ) && world.contains(succ)) {
                visit(succ)
              } else {
                // Ignore visited or out-of-bundle types.
              }
            }
            case _ => // do nothing if it is not composite
          }
          inStack(c) = false
        }

        visit(rootConst)
      }
    }

    def lookupSourceInfo(obj: AnyRef): SourceInfo = {
      val si1 = bundle.sourceInfoRepo(obj)
      if (si1 == NoSourceInfo && parentBundle.isDefined) {
        return parentBundle.get.sourceInfoRepo(obj)
      } else {
        return si1
      }
    }

    def error(msg: String, pretty: Seq[AnyRef] = Seq(), cause: Throwable = null): StaticCheckingException = {
      val prettyMsgs = pretty.map(o => lookupSourceInfo(o).prettyPrint())
      new StaticCheckingException("%s\n%s".format(msg, prettyMsgs.mkString("\n")), cause)
    }
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    def checkGlobals(): Unit = {
      for (g <- bundle.globalCellNs.all) {
        g.cellTy match {
          case ty: TypeVoid => throw error("Global cell %s: Global cell cannot have void type.".format(g.repr),
            pretty = Seq(g, ty))
          case ty: TypeHybrid => throw error("Global cell %s: Global cell cannot have hybrid type.".format(g.repr),
            pretty = Seq(g, ty))
        }
      }
    }

    def checkExpFuncs(): Unit = {
      for (ef <- bundle.expFuncNs.all) {
        ef.cookie.constTy match {
          case TypeInt(64) =>
          case ty => throw error("Exposed function %s: cookie must be a 64-bit int. %s found.".format(ef.repr, ty.repr),
            pretty = Seq(ef, ty))
        }
      }
    }

    def checkFuncs(): Unit = {
      for (fv <- bundle.funcVerNs.all) {
        checkFuncVer(fv)
      }
    }

    def checkFuncVer(fv: FuncVer): Unit = {
      val sig = fv.sig
      val fsig = fv.func.sig
      if (fsig.paramTys.length != sig.paramTys.length || fsig.retTys.length != sig.retTys.length) {
        throw error("Function version %s has different parameter or return value arity as its function %s".format(
          fv.repr, fv.func.repr), pretty = Seq(fv, sig, fv.func, fsig))
      }

      val entry = fv.entry
      if (entry.norParams.length != sig.paramTys.length) {
        throw error("Function version %s: the entry block has %d parameters, but the function takes %s parameters."
          .format(fv.repr, entry.norParams.length, sig.paramTys.length),
          pretty = Seq(fv, entry, sig))
      }

      if (entry.excParam.isDefined) {
        throw error("Function version %s: the entry block should not have exceptional parameter."
          .format(fv.repr),
          pretty = Seq(fv, entry))
      }

      for (bb <- fv.bbs) {
        checkBasicBlock(fv, entry, bb)
      }
    }

    def checkBasicBlock(fv: FuncVer, entry: BasicBlock, bb: BasicBlock): Unit = {
      if (bb.insts.isEmpty) {
        throw error("Function version %s: basic block %s is empty"
          .format(fv.repr, bb.repr),
          pretty = Seq(fv, bb))
      }
      val lastInst = bb.insts.last match {
        case i: MaybeTerminator if i.canTerminate => i
        case i => throw error("FuncVer %s BB %s: The last instruction %s is not a valid basic block terminator"
          .format(fv.repr, bb.repr, i.repr),
          pretty = Seq(fv, bb, i))
      }

      for ((dest, isNormal) <- bbDests(lastInst)) {
        if (dest.bb == entry) {
          throw error("FuncVer %s BB %s Inst %s: Cannot branch to the entry block"
            .format(fv.repr, bb.repr, lastInst.repr),
            pretty = Seq(fv, bb, lastInst))
        }

        val destBB = dest.bb
        val nParams = destBB.norParams.length
        val nArgs = dest.args.length
        if (nParams != nArgs) {
          throw error(("FuncVer %s BB %s Inst %s: Destination %s has %d normal parameters, but %d arguments found.\n" +
            "DestClause: %s")
            .format(fv.repr, bb.repr, lastInst.repr, destBB.repr, nParams, nArgs, dest),
            pretty = Seq(lastInst, destBB))
        }

        if (isNormal) {
          if (destBB.excParam.isDefined) {
            throw error(("FuncVer %s BB %s Inst %s: Normal destination %s should not have exceptional parameter.\n" +
              "DestClause: %s")
              .format(fv.repr, bb.repr, lastInst.repr, destBB.repr, dest),
              pretty = Seq(lastInst, destBB))
          }
        } else {
          if (!destBB.excParam.isDefined) {
            throw error(("FuncVer %s BB %s Inst %s: Exceptional destination %s must have exceptional parameter.\n" +
              "DestClause: %s")
              .format(fv.repr, bb.repr, lastInst.repr, destBB.repr, dest),
              pretty = Seq(lastInst, destBB))
          }
        }
      }
    }

    def bbDests(lastInst: MaybeTerminator): Seq[(DestClause, Boolean)] = lastInst match {
      case i: InstBranch     => Seq(i.dest).map(d => (d, true))
      case i: InstBranch2    => Seq(i.ifTrue, i.ifFalse).map(d => (d, true))
      case i: InstSwitch     => i.cases.map(_._2).map(d => (d, true))
      case i: InstTailCall   => Seq()
      case i: InstRet        => Seq()
      case i: InstThrow      => Seq()
      case i: InstWatchPoint => Seq(i.dis, i.ena).map(d => (d, true)) ++ i.exc.map(d => (d, false)).toSeq
      case i: InstWPBranch   => Seq(i.dis, i.ena).map(d => (d, true))
      case i: HasExcClause   => i.excClause.map(e => Seq((e.nor, true), (e.exc, false))).getOrElse(Seq())
    }
Kunshan Wang's avatar
Kunshan Wang committed
353 354 355 356
  }
}

class StaticCheckingException(message: String = null, cause: Throwable = null) extends UvmException(message, cause)