To protect your data, the CISO officer has suggested users to enable GitLab 2FA as soon as possible.

UIRTextReader.scala 25.6 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1
2
3
4
package uvm.ir.textinput

import org.antlr.v4.runtime._
import org.antlr.v4.runtime.tree.TerminalNode
Kunshan Wang's avatar
Kunshan Wang committed
5
import uvm._
Kunshan Wang's avatar
Kunshan Wang committed
6
import uvm.comminsts.CommInsts
Kunshan Wang's avatar
Kunshan Wang committed
7
8
9
10
11
import uvm.ir.textinput.gen.UIRParser._
import uvm.ir.textinput.gen._
import uvm.ssavariables._
import uvm.types._
import scala.collection.JavaConversions._
Kunshan Wang's avatar
Kunshan Wang committed
12
import scala.collection.mutable.ArrayBuffer
13
14
15
import scala.collection.immutable.Stream
import java.io.StringWriter
import java.nio.CharBuffer
16
import uvm.ir.textinput.gen.UIRParser.TypePtrContext
Kunshan Wang's avatar
Kunshan Wang committed
17

Kunshan Wang's avatar
Kunshan Wang committed
18
19
class UIRTextReader(val idFactory: IDFactory) {
  import uvm.ir.textinput.Later.Laterable
Kunshan Wang's avatar
Kunshan Wang committed
20

Kunshan Wang's avatar
Kunshan Wang committed
21
  def read(ir: String, globalBundle: Bundle): Bundle = {
Kunshan Wang's avatar
Kunshan Wang committed
22
    val input = new ANTLRInputStream(ir)
23
    read(ir, input, globalBundle)
Kunshan Wang's avatar
Kunshan Wang committed
24
25
  }

Kunshan Wang's avatar
Kunshan Wang committed
26
  def read(ir: java.io.Reader, globalBundle: Bundle): Bundle = {
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    val sb = new StringBuilder()
    val cb = new Array[Char](4096)

    var finished = false
    while (!finished) {
      val actualRead = ir.read(cb, 0, 4096)
      if (actualRead > 0) {
        sb.appendAll(cb, 0, actualRead)
      } else {
        finished = true
      }
    }

    read(sb.toString(), globalBundle)
Kunshan Wang's avatar
Kunshan Wang committed
41
42
  }

43
  class AccumulativeAntlrErrorListener(source: String) extends BaseErrorListener {
Kunshan Wang's avatar
Kunshan Wang committed
44
45
    val buf = new ArrayBuffer[String]()
    var hasError = false
46
47
48

    lazy val sourceLines = ArrayBuffer(source.lines.toSeq: _*)

Kunshan Wang's avatar
Kunshan Wang committed
49
    override def syntaxError(recognizer: Recognizer[_, _], offendingSymbol: Object,
50
                             line: Int, charPositionInLine: Int, msg: String, e: RecognitionException): Unit = {
51
52
53
      val theLine = sourceLines(line - 1)
      val marker = " " * charPositionInLine + "^"
      buf.add("line %d:%d %s\n%s\n%s".format(line, charPositionInLine, msg, theLine, marker))
Kunshan Wang's avatar
Kunshan Wang committed
54
55
      hasError = true
    }
56

Kunshan Wang's avatar
Kunshan Wang committed
57
58
59
    def getMessages(): String = buf.mkString("\n")
  }

60
61
62
63
64
65
  def read(source: String, ais: ANTLRInputStream, globalBundle: Bundle): Bundle = {
    val ea = new AccumulativeAntlrErrorListener(source)

    val lexer = new UIRLexer(ais)
    lexer.removeErrorListeners()
    lexer.addErrorListener(ea)
Kunshan Wang's avatar
Kunshan Wang committed
66
67
    val tokens = new CommonTokenStream(lexer)
    val parser = new UIRParser(tokens)
Kunshan Wang's avatar
Kunshan Wang committed
68
69
    parser.removeErrorListeners()
    parser.addErrorListener(ea)
Kunshan Wang's avatar
Kunshan Wang committed
70
    val ast = parser.ir()
Kunshan Wang's avatar
Kunshan Wang committed
71
    if (ea.hasError) {
72
      throw new TextIRParsingException("Syntax error:\n" + ea.getMessages)
Kunshan Wang's avatar
Kunshan Wang committed
73
    }
Kunshan Wang's avatar
Kunshan Wang committed
74
    read(ast, globalBundle)
Kunshan Wang's avatar
Kunshan Wang committed
75

Kunshan Wang's avatar
Kunshan Wang committed
76
77
78
  }

  implicit def terminalToString(tn: TerminalNode): String = tn.getText()
Kunshan Wang's avatar
Kunshan Wang committed
79
80
81
82
  implicit def nameToString(name: NameContext): String = name.getText()
  implicit def tokenToString(tok: Token): String = tok.getText()

  val IntRe = """([+-]?)(0x|0|)([0-9a-fA-F]*)""".r
Kunshan Wang's avatar
Kunshan Wang committed
83
84
85

  implicit def IntLiteralToBigInt(il: IntLiteralContext): BigInt = {
    val txt = il.getText()
Kunshan Wang's avatar
Kunshan Wang committed
86
87
88
89
90
91

    txt match {
      case IntRe(sign, prefix, nums) => {
        val neg = sign match {
          case "+" => false
          case "-" => true
92
          case ""  => false
Kunshan Wang's avatar
Kunshan Wang committed
93
94
95
        }
        val abs = prefix match {
          case "0x" => BigInt(nums, 16)
96
97
          case "0"  => if (nums == "") BigInt(0) else BigInt(nums, 8)
          case ""   => BigInt(nums, 10)
Kunshan Wang's avatar
Kunshan Wang committed
98
99
100
        }
        return if (neg) -abs else abs
      }
Kunshan Wang's avatar
Kunshan Wang committed
101
102
103
104
    }
  }

  implicit def floatLiteralToFloat(fl: FloatLiteralContext): Float = fl match {
Kunshan Wang's avatar
Kunshan Wang committed
105
106
107
    case num: FloatNumberContext => num.FP_NUM.getText.toFloat
    case fi: FloatInfContext => {
      if (fi.getText.startsWith("-"))
Kunshan Wang's avatar
Kunshan Wang committed
108
        java.lang.Float.NEGATIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
109
      else java.lang.Float.POSITIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
110
    }
111
    case _: FloatNanContext     => java.lang.Float.NaN
Kunshan Wang's avatar
Kunshan Wang committed
112
    case bits: FloatBitsContext => java.lang.Float.intBitsToFloat(bits.intLiteral().intValue())
Kunshan Wang's avatar
Kunshan Wang committed
113
  }
Kunshan Wang's avatar
Kunshan Wang committed
114

Kunshan Wang's avatar
Kunshan Wang committed
115
  implicit def doubleLiteralToDouble(dl: DoubleLiteralContext): Double = dl match {
Kunshan Wang's avatar
Kunshan Wang committed
116
117
118
    case num: DoubleNumberContext => num.FP_NUM.getText.toDouble
    case fi: DoubleInfContext => {
      if (fi.getText.startsWith("-"))
Kunshan Wang's avatar
Kunshan Wang committed
119
        java.lang.Double.NEGATIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
120
      else java.lang.Double.POSITIVE_INFINITY
Kunshan Wang's avatar
Kunshan Wang committed
121
    }
122
    case _: DoubleNanContext     => java.lang.Double.NaN
Kunshan Wang's avatar
Kunshan Wang committed
123
    case bits: DoubleBitsContext => java.lang.Double.longBitsToDouble(bits.intLiteral().longValue())
Kunshan Wang's avatar
Kunshan Wang committed
124
125
  }

Kunshan Wang's avatar
Kunshan Wang committed
126
  def cascadeLookup[T <: Identified](name: String, ns1: Namespace[T], ns2: Namespace[T]): T =
Kunshan Wang's avatar
Kunshan Wang committed
127
    ns1.get(name).getOrElse(ns2(name))
Kunshan Wang's avatar
Kunshan Wang committed
128

Kunshan Wang's avatar
Kunshan Wang committed
129
130
131
132
133
134
135
136
137
138
139
140
  // Printing context information (line, column, near some token)

  def inCtx(ctx: ParserRuleContext, s: String): String = nearTok(ctx.getStart, s)
  def inCtx(ctx: TerminalNode, s: String): String = nearTok(ctx.getSymbol, s)

  def nearTok(tok: Token, s: String): String = {
    val line = tok.getLine()
    val column = tok.getCharPositionInLine()
    val near = tok.getText()
    return "At %d:%d near '%s': %s".format(line, column, near, s)
  }

Kunshan Wang's avatar
Kunshan Wang committed
141
142
143
144
145
146
  def catchIn[T](ctx: ParserRuleContext, s: String)(func: => T): T = try {
    func
  } catch {
    case e: Exception => throw new TextIRParsingException(inCtx(ctx, s), e)
  }

Kunshan Wang's avatar
Kunshan Wang committed
147
  def read(ir: IrContext, globalBundle: Bundle): Bundle = {
Kunshan Wang's avatar
Kunshan Wang committed
148
149
    val bundle = new Bundle()

Kunshan Wang's avatar
Kunshan Wang committed
150
    // Resolve global entities. (If any resXxxx is not present, that's because it is simply not currently used)
Kunshan Wang's avatar
Kunshan Wang committed
151

Kunshan Wang's avatar
Kunshan Wang committed
152
    implicit def resTy(ctx: TypeContext): Type = catchIn(ctx, "Unable to resolve type") { resTyByName(ctx.getText) }
Kunshan Wang's avatar
Kunshan Wang committed
153
    def resTyByName(name: String): Type = cascadeLookup(name, bundle.typeNs, globalBundle.typeNs)
Kunshan Wang's avatar
Kunshan Wang committed
154

Kunshan Wang's avatar
Kunshan Wang committed
155
    implicit def resSig(ctx: FuncSigContext): FuncSig = catchIn(ctx, "Unable to resolve sig") { resSigByName(ctx.getText) }
Kunshan Wang's avatar
Kunshan Wang committed
156
    def resSigByName(name: String): FuncSig = cascadeLookup(name, bundle.funcSigNs, globalBundle.funcSigNs)
Kunshan Wang's avatar
Kunshan Wang committed
157

Kunshan Wang's avatar
Kunshan Wang committed
158
    implicit def resConst(ctx: ConstantContext): Constant = catchIn(ctx, "Unable to resolve const") { resConstByName(ctx.getText) }
Kunshan Wang's avatar
Kunshan Wang committed
159
    def resConstByName(name: String): Constant = cascadeLookup(name, bundle.constantNs, globalBundle.constantNs)
Kunshan Wang's avatar
Kunshan Wang committed
160
161

    def resGlobalVar(name: String): GlobalVariable = cascadeLookup(name, bundle.globalVarNs, globalBundle.globalVarNs)
162
163
164
165
    def resFunc(name: String): Function = cascadeLookup(name, bundle.funcNs, globalBundle.funcNs)

    implicit def convFlag(f: FlagContext): Flag = Flag(f.FLAG().getText)
    implicit def convFlagList(a: FlagListContext): Seq[Flag] = a.flag().map(convFlag)
Kunshan Wang's avatar
Kunshan Wang committed
166

Kunshan Wang's avatar
Kunshan Wang committed
167
168
    // Add entities to namespaces.

169
    def addTy(obj: Type): Unit = {
170
      bundle.add(obj)
171
172
    }
    def addSig(obj: FuncSig): Unit = {
173
      bundle.add(obj)
174
    }
Kunshan Wang's avatar
Kunshan Wang committed
175
    def addConst(obj: Constant): Unit = {
176
      bundle.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
177
178
    }
    def addGlobalCell(obj: GlobalCell): Unit = {
179
      bundle.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
180
181
    }
    def addFunc(obj: Function): Unit = {
182
      bundle.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
183
    }
184
185
186
    def addExpFunc(obj: ExposedFunc): Unit = {
      bundle.add(obj)
    }
Kunshan Wang's avatar
Kunshan Wang committed
187
188
    def addLocalVar(obj: LocalVariable, localNs: Namespace[LocalVariable]) = {
      localNs.add(obj)
189
      bundle.add(obj)
190
191
    }
    def addFuncVer(obj: FuncVer): Unit = {
192
      bundle.add(obj)
Kunshan Wang's avatar
Kunshan Wang committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    }

    // Resolve types, with parse-time checking.

    def needType[E <: Type](tc: TypeContext, expectedType: Class[E], n: String): E = {
      val t = resTy(tc)
      if (!(expectedType.isAssignableFrom(t.getClass))) {
        throw new UnexpectedTypeException(inCtx(tc, "Expected %s, actually %s.".format(n, t)))
      }
      t.asInstanceOf[E]
    }

    def needInt[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeInt], "int")
    def needStruct[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeStruct], "struct")
    def needArray[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeArray], "array")
    def needVector[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeVector], "vector")
    def needHybrid[T <: Type](tc: TypeContext) = needType(tc, classOf[TypeHybrid], "hybrid")
Kunshan Wang's avatar
Kunshan Wang committed
210
    def needSeq[T <: Type](tc: TypeContext) = needType(tc, classOf[AbstractSeqType], "array or vector")
Kunshan Wang's avatar
Kunshan Wang committed
211

212
213
214
215
216
217
218
219
    def needConstInt64(ctx: ParserRuleContext, name: String): ConstInt = {
      val c = resConstByName(name)
      if (!c.isInstanceOf[ConstInt]) {
        throw new UnexpectedTypeException(inCtx(ctx, "Expected 64-bit integer constant, actually %s.".format(c.getClass)))
      }
      c.asInstanceOf[ConstInt]
    }

Kunshan Wang's avatar
Kunshan Wang committed
220
221
    // Make types and sigs

Kunshan Wang's avatar
Kunshan Wang committed
222
    val phase1 = new Later() // Resolve inter-references between types and sigs
Kunshan Wang's avatar
Kunshan Wang committed
223

Kunshan Wang's avatar
Kunshan Wang committed
224
225
    def mkType(tc: TypeConstructorContext): Type = {
      val ty = tc match {
226
227
228
229
230
231
232
233
234
235
236
237
238
        case t: TypeIntContext      => TypeInt(t.length.intValue())
        case t: TypeFloatContext    => TypeFloat()
        case t: TypeDoubleContext   => TypeDouble()
        case t: TypeRefContext      => TypeRef(null).later(phase1) { _.ty = resTy(t.`type`()) }
        case t: TypeIRefContext     => TypeIRef(null).later(phase1) { _.ty = resTy(t.`type`()) }
        case t: TypeWeakRefContext  => TypeWeakRef(null).later(phase1) { _.ty = resTy(t.`type`()) }
        case t: TypeStructContext   => TypeStruct(null).later(phase1) { _.fieldTy = t.`type`().map(resTy) }
        case t: TypeArrayContext    => TypeArray(null, t.length.longValue()).later(phase1) { _.elemTy = resTy(t.`type`()) }
        case t: TypeHybridContext   => TypeHybrid(null, null).later(phase1) { tt => tt.fixedTy = resTy(t.fixedTy); tt.varTy = resTy(t.varTy) }
        case t: TypeVoidContext     => TypeVoid()
        case t: TypeFuncContext     => TypeFunc(null).later(phase1) { _.sig = resSig(t.funcSig()) }
        case t: TypeThreadContext   => TypeThread()
        case t: TypeStackContext    => TypeStack()
Kunshan Wang's avatar
Kunshan Wang committed
239
        case t: TypeTagRef64Context => TypeTagRef64()
240
        case t: TypeVectorContext   => TypeVector(null, t.length.longValue()).later(phase1) { _.elemTy = resTy(t.`type`()) }
241
242
        case t: TypePtrContext      => TypePtr(null).later(phase1) { _.ty = resTy(t.`type`()) }
        case t: TypeFuncPtrContext  => TypeFuncPtr(null).later(phase1) { _.sig = resSig(t.funcSig()) }
243
        case _                      => throw new TextIRParsingException("foo")
Kunshan Wang's avatar
Kunshan Wang committed
244
245
246
247
248
249
      }
      return ty
    }

    def mkSig(fsc: FuncSigConstructorContext): FuncSig = {
      val sig = FuncSig(null, null).later(phase1) { sig =>
Kunshan Wang's avatar
Kunshan Wang committed
250
        sig.retTy = resTy(fsc.retTy)
Kunshan Wang's avatar
Kunshan Wang committed
251
        sig.paramTy = for (t <- fsc.paramTy) yield resTy(t)
Kunshan Wang's avatar
Kunshan Wang committed
252
253
254
255
      }
      return sig
    }

Kunshan Wang's avatar
Kunshan Wang committed
256
    ir.topLevelDef.map(_.getChild(0)).foreach {
Kunshan Wang's avatar
Kunshan Wang committed
257
258
      case td: TypeDefContext => {
        val ty = mkType(td.typeConstructor)
Kunshan Wang's avatar
Kunshan Wang committed
259
260
        ty.id = idFactory.getID()
        ty.name = Some(td.nam)
Kunshan Wang's avatar
Kunshan Wang committed
261
        addTy(ty)
Kunshan Wang's avatar
Kunshan Wang committed
262
263
264
      }
      case fsd: FuncSigDefContext => {
        val sig = mkSig(fsd.funcSigConstructor)
Kunshan Wang's avatar
Kunshan Wang committed
265
266
        sig.id = idFactory.getID()
        sig.name = Some(fsd.nam)
Kunshan Wang's avatar
Kunshan Wang committed
267
        addSig(sig)
Kunshan Wang's avatar
Kunshan Wang committed
268
      }
Kunshan Wang's avatar
Kunshan Wang committed
269
      case _ =>
Kunshan Wang's avatar
Kunshan Wang committed
270
271
272
273
    }

    phase1.doAll()

Kunshan Wang's avatar
Kunshan Wang committed
274
    val phase2 = new Later() // Resolve inter-references from constants to other global variables
Kunshan Wang's avatar
Kunshan Wang committed
275

Kunshan Wang's avatar
Kunshan Wang committed
276
    def mkConst(t: Type, c: ConstConstructorContext): Constant = {
Kunshan Wang's avatar
Kunshan Wang committed
277
      val con = c match {
278
279
280
281
        case cc: ConstIntContext => t match {
          case _: TypeInt             => ConstInt(t, cc.intLiteral)
          case _: AbstractPointerType => ConstPointer(t, cc.intLiteral().longValue())
        }
282
        case cc: ConstFloatContext  => ConstFloat(t, cc.floatLiteral)
Kunshan Wang's avatar
Kunshan Wang committed
283
284
285
286
287
288
289
        case cc: ConstDoubleContext => ConstDouble(t, cc.doubleLiteral)
        case cc: ConstStructContext => ConstStruct(t, null).later(phase2) {
          _.fields = for (gn <- cc.GLOBAL_NAME()) yield resGlobalVar(gn)
        }
        case _: ConstNullContext => ConstNull(t)
        case cc: ConstVectorContext => ConstVector(t, null).later(phase2) {
          _.elems = for (c <- cc.constant()) yield resConst(c)
Kunshan Wang's avatar
Kunshan Wang committed
290
291
292
293
294
        }
      }
      return con
    }

Kunshan Wang's avatar
Kunshan Wang committed
295
    def mkGlobalCell(t: Type): GlobalCell = GlobalCell(t)
Kunshan Wang's avatar
Kunshan Wang committed
296
297
298
299
300
301
302

    def mkFunc(sig: FuncSig): Function = {
      val func = new Function()
      func.sig = sig
      return func
    }

303
304
305
306
307
308
309
310
    def mkExpo(c: ExposeDefContext): ExposedFunc = {
      val efun = ExposedFunc(null, c.callConv, null).later(phase2) { ee =>
        ee.func = resFunc(c.funcName)
        ee.cookie = needConstInt64(c, c.cookie)
      }
      return efun
    }

Kunshan Wang's avatar
Kunshan Wang committed
311
312
313
314
315
316
317
318
    def tryReuseFuncID(name: String): Option[Int] = {
      globalBundle.funcNs.get(name).map(_.id)
    }

    def declFunc(n: String, s: FuncSigContext): Function = {
      val sig = resSig(s)
      val func = mkFunc(sig)
      val maybeOldID = tryReuseFuncID(n)
Kunshan Wang's avatar
Kunshan Wang committed
319
      func.id = maybeOldID.getOrElse(idFactory.getID())
Kunshan Wang's avatar
Kunshan Wang committed
320
      func.name = Some(n)
Kunshan Wang's avatar
Kunshan Wang committed
321
      addFunc(func)
Kunshan Wang's avatar
Kunshan Wang committed
322
323
324
325

      return func
    }

Kunshan Wang's avatar
Kunshan Wang committed
326
    var funcDefs: List[(Function, FuncDefContext)] = Nil
Kunshan Wang's avatar
Kunshan Wang committed
327

Kunshan Wang's avatar
Kunshan Wang committed
328
    ir.topLevelDef().map(_.getChild(0)).foreach {
Kunshan Wang's avatar
Kunshan Wang committed
329
330
      case cdctx: ConstDefContext => {
        val ty = resTy(cdctx.`type`)
Kunshan Wang's avatar
Kunshan Wang committed
331
332
333
        val con = mkConst(ty, cdctx.constConstructor)
        con.id = idFactory.getID()
        con.name = Some(cdctx.nam)
Kunshan Wang's avatar
Kunshan Wang committed
334
        addConst(con)
Kunshan Wang's avatar
Kunshan Wang committed
335
336
337
      }
      case gdctx: GlobalDefContext => {
        val ty = resTy(gdctx.`type`)
Kunshan Wang's avatar
Kunshan Wang committed
338
        val gc = mkGlobalCell(ty)
Kunshan Wang's avatar
Kunshan Wang committed
339
        gc.id = idFactory.getID()
Kunshan Wang's avatar
Kunshan Wang committed
340
        gc.name = Some(gdctx.nam)
Kunshan Wang's avatar
Kunshan Wang committed
341
        addGlobalCell(gc)
Kunshan Wang's avatar
Kunshan Wang committed
342
343
      }
      case fdecl: FuncDeclContext => {
Kunshan Wang's avatar
Kunshan Wang committed
344
        declFunc(fdecl.nam, fdecl.funcSig)
Kunshan Wang's avatar
Kunshan Wang committed
345

Kunshan Wang's avatar
Kunshan Wang committed
346
347
      }
      case fdef: FuncDefContext => {
Kunshan Wang's avatar
Kunshan Wang committed
348
        val func = declFunc(fdef.nam, fdef.funcSig)
Kunshan Wang's avatar
Kunshan Wang committed
349
        funcDefs = (func, fdef) :: funcDefs
Kunshan Wang's avatar
Kunshan Wang committed
350
      }
351
352
353
354
355
356
      case edef: ExposeDefContext => {
        val efun = mkExpo(edef)
        efun.id = idFactory.getID()
        efun.name = Some(edef.nam)
        addExpFunc(efun)
      }
Kunshan Wang's avatar
Kunshan Wang committed
357
358
359
360
361
      case _ => {}
    }

    phase2.doAll()

Kunshan Wang's avatar
Kunshan Wang committed
362
    def defFunc(func: Function, fDefCtx: FuncDefContext) {
Kunshan Wang's avatar
Kunshan Wang committed
363
      val ver = new FuncVer()
Kunshan Wang's avatar
Kunshan Wang committed
364
365
366
367
      ver.id = idFactory.getID()
      ver.name = Some(fDefCtx.ver)
      addFuncVer(ver)

Kunshan Wang's avatar
Kunshan Wang committed
368
369
370
      ver.func = func
      func.versions = ver :: func.versions

Kunshan Wang's avatar
Kunshan Wang committed
371
      def globalize(name: String): String = UIRTextReader.globalize(name, ver.name.get)
Kunshan Wang's avatar
Kunshan Wang committed
372

Kunshan Wang's avatar
Kunshan Wang committed
373
      ver.params = fDefCtx.params.name().zipWithIndex.map {
Kunshan Wang's avatar
Kunshan Wang committed
374
        case (n, i) =>
Kunshan Wang's avatar
Kunshan Wang committed
375
376
377
          val param = Parameter(ver, i)
          param.id = idFactory.getID()
          param.name = Some(globalize(n))
Kunshan Wang's avatar
Kunshan Wang committed
378
          addLocalVar(param, ver.localVarNs)
Kunshan Wang's avatar
Kunshan Wang committed
379
380
381
          param
      }

Kunshan Wang's avatar
Kunshan Wang committed
382
      val phase4 = new Later() // Resolve references from instructions to other variables (global or local) and basic blocks
Kunshan Wang's avatar
Kunshan Wang committed
383

Kunshan Wang's avatar
Kunshan Wang committed
384
      def makeBB(bbCtx: BasicBlockContext): BasicBlock = {
Kunshan Wang's avatar
Kunshan Wang committed
385
        val bb = new BasicBlock()
Kunshan Wang's avatar
Kunshan Wang committed
386
387
        bb.id = idFactory.getID()
        bb.name = Some(globalize(bbCtx.label().name()))
Kunshan Wang's avatar
Kunshan Wang committed
388
        ver.bbNs.add(bb)
389
        bundle.add(bb)
Kunshan Wang's avatar
Kunshan Wang committed
390

Kunshan Wang's avatar
Kunshan Wang committed
391
        bb.insts = bbCtx.inst.map(mkInst)
Kunshan Wang's avatar
Kunshan Wang committed
392
393
394
395

        return bb
      }

Kunshan Wang's avatar
Kunshan Wang committed
396
      // Resolve local entities
Kunshan Wang's avatar
Kunshan Wang committed
397

Kunshan Wang's avatar
Kunshan Wang committed
398
399
400
401
402
403
404
      implicit def resBB(ctx: BbNameContext): BasicBlock = catchIn(ctx, "Unable to resolve basic block") {
        resBBByName(ctx.name.getText)
      }
      def resBBByName(name: String): BasicBlock = {
        val globalName = globalize(name)
        ver.bbNs(globalName)
      }
Kunshan Wang's avatar
Kunshan Wang committed
405

Kunshan Wang's avatar
Kunshan Wang committed
406
407
408
409
410
411
412
      implicit def resVar(ctx: ValueContext): SSAVariable = catchIn(ctx, "Unable to resolve variable") {
        resVarByName(ctx.name)
      }
      def resVarByName(name: String): SSAVariable = {
        val globalName = globalize(name)
        cascadeLookup(globalName, bundle.varNs, globalBundle.varNs)
      }
Kunshan Wang's avatar
Kunshan Wang committed
413

Kunshan Wang's avatar
Kunshan Wang committed
414
415
416
417
418
419
420
      def resLocalVar(ctx: ValueContext): LocalVariable = catchIn(ctx, "Unable to resolve local variable") {
        resLocalVarByName(ctx.name)
      }
      def resLocalVarByName(name: String): LocalVariable = {
        val globalName = globalize(name)
        ver.localVarNs(globalName)
      }
Kunshan Wang's avatar
Kunshan Wang committed
421

Kunshan Wang's avatar
Kunshan Wang committed
422
      // Resolve special structures
Kunshan Wang's avatar
Kunshan Wang committed
423

Kunshan Wang's avatar
Kunshan Wang committed
424
      implicit def resTypeList(a: TypeListContext): Seq[Type] = a.`type`.map(resTy)
425
      implicit def resFuncSigList(a: FuncSigListContext): Seq[FuncSig] = a.funcSig().map(resSig)
Kunshan Wang's avatar
Kunshan Wang committed
426

Kunshan Wang's avatar
Kunshan Wang committed
427
      implicit def resArgList(a: ArgListContext): Seq[SSAVariable] = a.value.map(resVar)
Kunshan Wang's avatar
Kunshan Wang committed
428

Kunshan Wang's avatar
Kunshan Wang committed
429
      implicit def resKA(ka: KeepAliveClauseContext): Seq[LocalVariable] = ka.value.map(resLocalVar)
Kunshan Wang's avatar
Kunshan Wang committed
430
431

      implicit def resOrd(ord: MemordContext): MemoryOrder.Value = {
Kunshan Wang's avatar
Kunshan Wang committed
432
        if (ord == null) {
Kunshan Wang's avatar
Kunshan Wang committed
433
          MemoryOrder.NOT_ATOMIC
Kunshan Wang's avatar
Kunshan Wang committed
434
        } else {
Kunshan Wang's avatar
Kunshan Wang committed
435
          MemoryOrder.withName(ord.getText)
Kunshan Wang's avatar
Kunshan Wang committed
436
437
438
        }
      }

Kunshan Wang's avatar
Kunshan Wang committed
439
440
      def resFuncCallBody(fcb: FuncCallBodyContext): (FuncSig, SSAVariable, Seq[SSAVariable]) =
        (fcb.funcSig, fcb.callee, fcb.argList)
Kunshan Wang's avatar
Kunshan Wang committed
441

Kunshan Wang's avatar
Kunshan Wang committed
442
443
444
      def asgnFuncCallBody(cl: CallLike, fcb: FuncCallBodyContext): Unit = {
        val (sig, callee, argList) = resFuncCallBody(fcb)
        cl.sig = sig; cl.callee = callee; cl.argList = argList
Kunshan Wang's avatar
Kunshan Wang committed
445
446
      }

Kunshan Wang's avatar
Kunshan Wang committed
447
448
449
450
451
452
453
      implicit def resExcClause(ec: ExcClauseContext): Option[ExcClause] =
        if (ec.nor == null) {
          None
        } else {
          val nor = resBB(ec.nor)
          val exc = resBB(ec.exc)
          Some(ExcClause(nor, exc))
Kunshan Wang's avatar
Kunshan Wang committed
454
        }
Kunshan Wang's avatar
Kunshan Wang committed
455
456

      // Make instruction
Kunshan Wang's avatar
Kunshan Wang committed
457
458
459
460
461

      def mkInst(instDef: InstContext): Instruction = {

        val inst: Instruction = instDef.instBody match {
          case ii: InstBinOpContext =>
Kunshan Wang's avatar
Kunshan Wang committed
462
463
            InstBinOp(BinOptr.withName(ii.binop.getText), ii.`type`, null, null, null).later(phase4) { i =>
              i.op1 = ii.op1; i.op2 = ii.op2; i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
464
465
            }
          case ii: InstCmpContext =>
Kunshan Wang's avatar
Kunshan Wang committed
466
467
            InstCmp(CmpOptr.withName(ii.cmpop.getText), ii.`type`, null, null).later(phase4) { i =>
              i.op1 = ii.op1; i.op2 = ii.op2
Kunshan Wang's avatar
Kunshan Wang committed
468
469
            }
          case ii: InstConversionContext =>
Kunshan Wang's avatar
Kunshan Wang committed
470
471
            InstConv(ConvOptr.withName(ii.convop.getText), ii.fromTy, ii.toTy, null).later(phase4) { i =>
              i.opnd = ii.opnd
Kunshan Wang's avatar
Kunshan Wang committed
472
473
            }
          case ii: InstSelectContext =>
Kunshan Wang's avatar
Kunshan Wang committed
474
475
            InstSelect(ii.condTy, ii.resTy, null, null, null).later(phase4) { i =>
              i.cond = ii.cond; i.ifTrue = ii.ifTrue; i.ifFalse = ii.ifFalse
Kunshan Wang's avatar
Kunshan Wang committed
476
477
            }
          case ii: InstBranchContext =>
Kunshan Wang's avatar
Kunshan Wang committed
478
479
480
            InstBranch(null).later(phase4) { i =>
              i.dest = ii.bbName
            }
Kunshan Wang's avatar
Kunshan Wang committed
481
          case ii: InstBranch2Context =>
Kunshan Wang's avatar
Kunshan Wang committed
482
483
            InstBranch2(null, null, null).later(phase4) { i =>
              i.cond = ii.cond; i.ifTrue = ii.ifTrue; i.ifFalse = ii.ifFalse
Kunshan Wang's avatar
Kunshan Wang committed
484
485
            }
          case ii: InstSwitchContext =>
Kunshan Wang's avatar
Kunshan Wang committed
486
487
            InstSwitch(ii.`type`, null, null, null).later(phase4) { i =>
              i.opnd = ii.opnd; i.defDest = ii.defDest
Kunshan Wang's avatar
Kunshan Wang committed
488
              i.cases = for ((v, b) <- ii.caseVal.zip(ii.caseDest)) yield (resVar(v), resBB(b))
Kunshan Wang's avatar
Kunshan Wang committed
489
490
            }
          case ii: InstPhiContext =>
Kunshan Wang's avatar
Kunshan Wang committed
491
492
            InstPhi(ii.`type`, null).later(phase4) { i =>
              i.cases = for ((b, v) <- ii.caseSrc.zip(ii.caseVal)) yield (resBB(b), resVar(v))
Kunshan Wang's avatar
Kunshan Wang committed
493
494
            }
          case ii: InstCallContext =>
Kunshan Wang's avatar
Kunshan Wang committed
495
496
497
498
            InstCall(null, null, null, null, null).later(phase4) { i =>
              asgnFuncCallBody(i, ii.funcCallBody)
              i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
            }
Kunshan Wang's avatar
Kunshan Wang committed
499
          case ii: InstTailCallContext =>
Kunshan Wang's avatar
Kunshan Wang committed
500
501
502
            InstTailCall(null, null, null).later(phase4) { i =>
              asgnFuncCallBody(i, ii.funcCallBody)
            }
Kunshan Wang's avatar
Kunshan Wang committed
503
          case ii: InstRetContext =>
Kunshan Wang's avatar
Kunshan Wang committed
504
505
            InstRet(ii.`type`, null).later(phase4) { i =>
              i.retVal = ii.retVal
Kunshan Wang's avatar
Kunshan Wang committed
506
507
508
509
510
            }
          case ii: InstRetVoidContext =>
            InstRetVoid()
          case ii: InstThrowContext =>
            InstThrow(null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
511
              i.excVal = ii.exc
Kunshan Wang's avatar
Kunshan Wang committed
512
513
            }
          case ii: InstLandingPadContext =>
Kunshan Wang's avatar
Kunshan Wang committed
514
            InstLandingPad()
Kunshan Wang's avatar
Kunshan Wang committed
515
          case ii: InstExtractValueContext =>
Kunshan Wang's avatar
Kunshan Wang committed
516
517
            InstExtractValue(needStruct(ii.`type`), ii.intLiteral.intValue, null).later(phase4) { i =>
              i.opnd = ii.opnd
Kunshan Wang's avatar
Kunshan Wang committed
518
519
            }
          case ii: InstInsertValueContext =>
Kunshan Wang's avatar
Kunshan Wang committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
            InstInsertValue(needStruct(ii.`type`), ii.intLiteral.intValue, null, null).later(phase4) { i =>
              i.opnd = ii.opnd; i.newVal = ii.newVal
            }
          case ii: InstExtractElementContext =>
            InstExtractElement(needVector(ii.vecTy), needInt(ii.indTy), null, null).later(phase4) { i =>
              i.opnd = ii.opnd; i.index = ii.index
            }
          case ii: InstInsertElementContext =>
            InstInsertElement(needVector(ii.vecTy), needInt(ii.indTy), null, null, null).later(phase4) { i =>
              i.opnd = ii.opnd; i.index = ii.index; i.newVal = ii.newVal
            }
          case ii: InstShuffleVectorContext =>
            InstShuffleVector(needVector(ii.vecTy), needVector(ii.maskTy), null, null, null).later(phase4) { i =>
              i.vec1 = ii.vec1; i.vec2 = ii.vec2; i.mask = ii.mask
            }
          case ii: InstNewContext =>
            InstNew(ii.allocTy, null).later(phase4) { i =>
              i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
538
539
            }
          case ii: InstNewHybridContext =>
Kunshan Wang's avatar
Kunshan Wang committed
540
            InstNewHybrid(needHybrid(ii.allocTy), needInt(ii.lenTy), null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
541
542
543
544
545
              i.length = ii.length; i.excClause = ii.excClause
            }
          case ii: InstAllocaContext =>
            InstAlloca(ii.allocTy, null).later(phase4) { i =>
              i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
546
547
            }
          case ii: InstAllocaHybridContext =>
Kunshan Wang's avatar
Kunshan Wang committed
548
            InstAllocaHybrid(needHybrid(ii.allocTy), needInt(ii.lenTy), null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
549
              i.length = ii.length; i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
550
551
            }
          case ii: InstGetIRefContext =>
Kunshan Wang's avatar
Kunshan Wang committed
552
            InstGetIRef(ii.refTy, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
553
              i.opnd = ii.opnd
Kunshan Wang's avatar
Kunshan Wang committed
554
555
            }
          case ii: InstGetFieldIRefContext =>
556
            InstGetFieldIRef(ii.ptr != null, needStruct(ii.refTy), ii.intLiteral.intValue, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
557
              i.opnd = ii.opnd
Kunshan Wang's avatar
Kunshan Wang committed
558
559
            }
          case ii: InstGetElemIRefContext =>
560
            InstGetElemIRef(ii.ptr != null, needSeq(ii.refTy), needInt(ii.indTy), null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
561
              i.opnd = ii.opnd; i.index = ii.index
Kunshan Wang's avatar
Kunshan Wang committed
562
563
            }
          case ii: InstShiftIRefContext =>
564
            InstShiftIRef(ii.ptr != null, ii.refTy, needInt(ii.offTy), null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
565
              i.opnd = ii.opnd; i.offset = ii.offset
Kunshan Wang's avatar
Kunshan Wang committed
566
567
            }
          case ii: InstGetFixedPartIRefContext =>
568
            InstGetFixedPartIRef(ii.ptr != null, needHybrid(ii.refTy), null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
569
              i.opnd = ii.opnd
Kunshan Wang's avatar
Kunshan Wang committed
570
571
            }
          case ii: InstGetVarPartIRefContext =>
572
            InstGetVarPartIRef(ii.ptr != null, needHybrid(ii.refTy), null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
573
              i.opnd = ii.opnd
Kunshan Wang's avatar
Kunshan Wang committed
574
575
            }
          case ii: InstLoadContext =>
576
            InstLoad(ii.ptr != null, ii.memord, ii.`type`, null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
577
              i.loc = ii.loc
Kunshan Wang's avatar
Kunshan Wang committed
578
              i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
579
580
            }
          case ii: InstStoreContext =>
581
            InstStore(ii.ptr != null, ii.memord, ii.`type`, null, null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
582
              i.loc = ii.loc; i.newVal = ii.newVal
Kunshan Wang's avatar
Kunshan Wang committed
583
              i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
584
585
            }
          case ii: InstCmpXchgContext =>
586
            InstCmpXchg(ii.ptr != null, ii.isWeak != null, ii.ordSucc, ii.ordFail, ii.`type`, null, null, null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
587
              i.loc = ii.loc; i.expected = ii.expected; i.desired = ii.desired
Kunshan Wang's avatar
Kunshan Wang committed
588
              i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
589
            }
Kunshan Wang's avatar
Kunshan Wang committed
590
          case ii: InstAtomicRMWContext =>
591
            InstAtomicRMW(ii.ptr != null, ii.memord, AtomicRMWOptr.withName(ii.atomicrmwop.getText), ii.`type`, null, null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
592
              i.loc = ii.loc; i.opnd = ii.opnd
Kunshan Wang's avatar
Kunshan Wang committed
593
              i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
594
            }
Kunshan Wang's avatar
Kunshan Wang committed
595
596
          case ii: InstFenceContext =>
            InstFence(ii.memord)
Kunshan Wang's avatar
Kunshan Wang committed
597
          case ii: InstTrapContext =>
Kunshan Wang's avatar
Kunshan Wang committed
598
599
600
            InstTrap(ii.`type`, null, null).later(phase4) { i =>
              i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
            }
Kunshan Wang's avatar
Kunshan Wang committed
601
          case ii: InstWatchPointContext =>
Kunshan Wang's avatar
Kunshan Wang committed
602
            InstWatchPoint(ii.intLiteral.intValue(), ii.`type`, null, null, null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
603
              i.dis = ii.dis; i.ena = ii.ena; i.exc = Option(ii.wpExc).map(resBB); i.keepAlives = ii.keepAliveClause
Kunshan Wang's avatar
Kunshan Wang committed
604
            }
Kunshan Wang's avatar
Kunshan Wang committed
605
          case ii: InstCCallContext =>
606
607
            InstCCall(ii.callConv, ii.funcTy, ii.funcSig, null, null, null).later(phase4) { i =>
              i.callee = ii.callee; i.argList = ii.argList; i.keepAlives = ii.keepAliveClause
Kunshan Wang's avatar
Kunshan Wang committed
608
            }
Kunshan Wang's avatar
Kunshan Wang committed
609
          case ii: InstNewStackContext =>
Kunshan Wang's avatar
Kunshan Wang committed
610
611
612
            InstNewStack(null, null, null, null).later(phase4) { i =>
              asgnFuncCallBody(i, ii.funcCallBody)
              i.excClause = ii.excClause
Kunshan Wang's avatar
Kunshan Wang committed
613
            }
Kunshan Wang's avatar
Kunshan Wang committed
614
615
616
617
618
619
620
621
622
          case ii: InstSwapStackContext =>
            InstSwapStack(null, null, null, null, null).later(phase4) { i =>
              i.swappee = ii.swappee;
              i.curStackAction = ii.curStackClause match {
                case a: CurStackRetWithContext => RetWith(a.`type`)
                case a: CurStackKillOldContext => KillOld()
              }
              i.newStackAction = ii.newStackClause match {
                case a: NewStackPassValueContext => PassValue(a.`type`, a.value)
623
624
                case a: NewStackPassVoidContext  => PassVoid()
                case a: NewStackThrowExcContext  => ThrowExc(a.exc)
Kunshan Wang's avatar
Kunshan Wang committed
625
626
627
628
              }
              i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
            }
          case ii: InstCommInstContext =>
629
            InstCommInst(CommInsts(ii.nam), Option(ii.flagList()).map(convFlagList).getOrElse(Seq()), null, null, null, null, null).later(phase4) { i =>
Kunshan Wang's avatar
Kunshan Wang committed
630
              i.typeList = Option(ii.typeList).map(resTypeList).getOrElse(Seq())
631
              i.funcSigList = Option(ii.funcSigList).map(resFuncSigList).getOrElse(Seq())
Kunshan Wang's avatar
Kunshan Wang committed
632
633
              i.argList = Option(ii.argList).map(resArgList).getOrElse(Seq())
              i.excClause = ii.excClause; i.keepAlives = ii.keepAliveClause
Kunshan Wang's avatar
Kunshan Wang committed
634
635
636
            }
        }

Kunshan Wang's avatar
Kunshan Wang committed
637
        inst.id = idFactory.getID()
638
639
        inst.name = Option(instDef.name).map(n => globalize(n.getText))

Kunshan Wang's avatar
Kunshan Wang committed
640
        addLocalVar(inst, ver.localVarNs)
Kunshan Wang's avatar
Kunshan Wang committed
641
642
643
644

        return inst
      }

Kunshan Wang's avatar
Kunshan Wang committed
645
      val bbs = fDefCtx.funcBody.basicBlock().map(makeBB)
Kunshan Wang's avatar
Kunshan Wang committed
646

Kunshan Wang's avatar
Kunshan Wang committed
647
      ver.bbs = bbs
Kunshan Wang's avatar
Kunshan Wang committed
648
      ver.entry = bbs.head
Kunshan Wang's avatar
Kunshan Wang committed
649
650
651
652

      phase4.doAll()
    }

Kunshan Wang's avatar
Kunshan Wang committed
653
654
    for ((func, fDefCtx) <- funcDefs) {
      defFunc(func, fDefCtx)
Kunshan Wang's avatar
Kunshan Wang committed
655
656
    }

Kunshan Wang's avatar
Kunshan Wang committed
657
658
    return bundle
  }
Kunshan Wang's avatar
Kunshan Wang committed
659
660
661
662
663
664
}

object UIRTextReader {
  def globalize(name: String, fvName: String): String = {
    val sigil = name.charAt(0)
    sigil match {
665
666
667
      case '@' => name
      case '%' => fvName + "." + name.substring(1)
      case _   => throw new UvmException("Illegal name '%s'. Name must begin with either '@' or '%%'".format(name))
Kunshan Wang's avatar
Kunshan Wang committed
668
669
    }
  }
Kunshan Wang's avatar
Kunshan Wang committed
670
}